Пример #1
0
/**
 * @brief Algorithm::initialize Loads the corresponding QJsonObject for this algorithm
 * @param loader The plugin loader which loads the QJsonObject
 * @return True, if all went well.
 */
bool Algorithm::initialize(QPluginLoader *loader) {
    //read the QJsonObject parameter
    if (!loader) return false;
    QJsonObject tmp = loader->metaData();
    if (tmp.isEmpty()) return false;
    QJsonValue v = tmp.value("MetaData");
    if (v.isUndefined()) return false;
    QJsonObject o = v.toObject();
    if (o.isEmpty()) return false;

    mId = "";
    mName = "";
    mDescription = "";

    QString version = "";
    if (o.contains("Author")) {}
    if (o.contains("Date")) {}
    if (o.contains("Name")) mName = o.value("Name").toString();
    else {} //LOG WARNING
    if (o.contains("Version")) version = o.value("Version").toString();
    else {} //LOG WARNING
    if (o.contains("Description")) mDescription = o.value("Description").toString();
    else {} //LOG WARNING
    mId = mName + " " + version;
    if (mId.trimmed() == "") {} //LOG WARNING

    if (o.contains("Properties")) mDefaultParameters = o.value("Properties").toObject();
    else {} //LOG WARNING

    return true;
}
Пример #2
0
void loadGeometry(QWidget *widget, const QJsonObject& parent)
{
  if( parent.isEmpty() ) {
    return;
  }

  const QJsonObject geomObj = parent[QStringLiteral("geometry")].toObject();
  if( geomObj.isEmpty() ) {
    return;
  }

  const int error = std::numeric_limits<int>::lowest();

  const int x = geomObj[QStringLiteral("x")].toInt(error);
  const int y = geomObj[QStringLiteral("y")].toInt(error);
  if( x != error  &&  y != error ) {
    widget->move(x, y);
  }

  const int w = geomObj[QStringLiteral("width")].toInt(error);
  const int h = geomObj[QStringLiteral("height")].toInt(error);
  if( w != error  &&  h != error ) {
    widget->resize(w, h);
  }
}
Пример #3
0
void AuthorizationManager::ListCertificates(QString token, QJsonObject *out){
  QStringList keys; //Format: "RegisteredCerts/<user>/<key>"
  if( hasFullAccess(token) ){ 
    //Read all user's certs
    keys = CONFIG->allKeys().filter("RegisteredCerts/");
    //qDebug() << "Found SSL Keys to List:" << keys;
  }else{
    //Only list certs for current user
    QString cuser = hashID(token).section("::::",2,2);
    keys = CONFIG->allKeys().filter("RegisteredCerts/"+cuser+"/");
    //qDebug() << "Found SSL Keys to List:" << keys;
  }
  keys.sort();
  //Now put the known keys into the output structure arranged by username/key
  QJsonObject user; QString username;
  for(int i=0; i<keys.length(); i++){
    if(username!=keys[i].section("/",1,1)){
      if(!user.isEmpty()){ out->insert(username, user); user = QJsonObject(); } //save the current info to the output
      username = keys[i].section("/",1,1); //save the new username for later
    }
    QString info = CONFIG->value(keys[i]).toString();
    QString key = keys[i].section("/",2,-1);//just in case the key has additional "/" in it
    user.insert(key,info);
  }
  if(!user.isEmpty() && !username.isEmpty()){ out->insert(username, user); }
}
Пример #4
0
nd::model::model(modelDefinition *def, QJsonObject attributes, QObject *parent) :
    protoObject(parent)
{
    definition = def;
    QStringList keys = definition->fieldNames();
    modelDefinition::modelFieldDefinition field;
    setObjectName(def->name());

    for (int i = 0; i < keys.count(); i++) {        
        field = definition->field(keys.at(i));
        qDebug() << keys.at(i) << field.name;
        if (field.type == modelDefinition::object) {
            QVariant variant;
            variant = QVariant::fromValue(QSharedPointer<protoObject>());
            this->setProperty(field.name.toLatin1(), variant);
            continue;
        };

        if (field.type == modelDefinition::array) {
            QList< QSharedPointer<protoObject> > list;
            QVariant variant = QVariant::fromValue(list);
            this->setProperty(field.name.toLatin1(), variant);
            continue;
        };

        this->setProperty(field.name.toLatin1(), QString(""));
    };

    if (!attributes.isEmpty()) {
        // load model
    };
}
Пример #5
0
void NetWork::dealSeach(QNetworkReply *reply)
{
	QJsonObject obj = getObject(*reply);
	if (obj.isEmpty())
		return;
	QJsonObject resultObj = obj.find("result").value().toObject();
	QJsonArray objList = resultObj.find("songs").value().toArray();

	m_list.clear();
	m_songIds.clear();
	for (int i = 0; i < objList.count(); i++)
	{
		QJsonObject songObj = objList.at(i).toObject();
		int songId = songObj.find("id").value().toInt();
		QString name = songObj.find("name").value().toString();
		QJsonArray artistsList = songObj.find("artists").value().toArray();
		QString artists = "";
		for (int j = 0; j < artistsList.count(); j++)
			artists.append(artistsList.at(j).toObject().find("name").value().toString());
		QString album = songObj.find("album").value().toObject().find("name").value().toString();

		m_songIds.insert(songId, i);
		QStringList list;
		list << name << artists << album << "" << QString::number(songId);
		m_list.insert(i, list);
	}
}
Пример #6
0
void PomfUploader::verify(const QString &url, VerificationCallback callback)
{
    QNetworkRequest request(QUrl::fromUserInput(QString("%1/upload.php").arg(url)));

    if (!request.url().isValid()) {
        callback(false);
    }

    QNetworkReply *reply = Uploader::network()->get(request);

    connect(reply, &QNetworkReply::finished, [reply, callback] {
        reply->deleteLater();

        const QJsonObject pomfResponse = QJsonDocument::fromJson(reply->readAll()).object();

        if (!pomfResponse.isEmpty() && pomfResponse.contains("success")) {
            callback(true);
        } else {
            callback(false);
        }
    });

    connect(reply, &QNetworkReply::sslErrors, [reply](const QList<QSslError> &errors) {
        Q_UNUSED(errors);
        if (QSysInfo::WindowsVersion == QSysInfo::WV_XP) {
            reply->ignoreSslErrors();
        }
    });
}
Пример #7
0
QJsonObject HeadData::toJson() const {
    QJsonObject headJson;
    const auto& blendshapeLookupMap = getBlendshapesLookupMap();
    QJsonObject blendshapesJson;
    for (auto name : blendshapeLookupMap.keys()) {
        auto index = blendshapeLookupMap[name];
        if (index >= _blendshapeCoefficients.size()) {
            continue;
        }
        auto value = _blendshapeCoefficients[index];
        if (value == 0.0f) {
            continue;
        }
        blendshapesJson[name] = value;
    }
    if (!blendshapesJson.isEmpty()) {
        headJson[JSON_AVATAR_HEAD_BLENDSHAPE_COEFFICIENTS] = blendshapesJson;
    }
    if (getRawOrientation() != quat()) {
        headJson[JSON_AVATAR_HEAD_ROTATION] = toJsonValue(getRawOrientation());
    }
    if (getLeanForward() != 0.0f) {
        headJson[JSON_AVATAR_HEAD_LEAN_FORWARD] = getLeanForward();
    }
    if (getLeanSideways() != 0.0f) {
        headJson[JSON_AVATAR_HEAD_LEAN_SIDEWAYS] = getLeanSideways();
    }
    auto lookat = getLookAtPosition();
    if (lookat != vec3()) {
        vec3 relativeLookAt = glm::inverse(_owningAvatar->getOrientation()) *
            (getLookAtPosition() - _owningAvatar->getPosition());
        headJson[JSON_AVATAR_HEAD_LOOKAT] = toJsonValue(relativeLookAt);
    }
    return headJson;
}
Пример #8
0
void ImgurUploader::authorizationReply(QNetworkReply *reply, AuthorizationCallback callback)
{
#ifdef Q_OS_WIN
    connect(reply, &QNetworkReply::sslErrors, [reply](const QList<QSslError> &errors) {
        Q_UNUSED(errors);
        if (QSysInfo::WindowsVersion <= QSysInfo::WV_2003) {
            reply->ignoreSslErrors();
        }
    });
#endif

    connect(reply, &QNetworkReply::finished, [reply, callback] {
        reply->deleteLater();

        bool authorized = false;

        const QJsonObject imgurResponse = QJsonDocument::fromJson(reply->readAll()).object();

        if (!imgurResponse.isEmpty() && imgurResponse.contains("access_token")) {
            QVariantHash newSettings;
            newSettings["access_token"]     = imgurResponse.value("access_token").toString();
            newSettings["refresh_token"]    = imgurResponse.value("refresh_token").toString();
            newSettings["account_username"] = imgurResponse.value("account_username").toString();
            newSettings["expires_in"]       = imgurResponse.value("expires_in").toInt();
            ImgurUploader::saveSettings("imgur", newSettings);

            authorized = true;
        }

        callback(authorized);
    });
}
Пример #9
0
void ImportDialog::setImportTypes() {
    QFile config(Application::resourcesPath() + "config/config.json");
    config.open(QFile::ReadOnly | QFile::Text);
    QJsonDocument document = QJsonDocument::fromJson(config.readAll());
    if (!document.isNull() && !document.isEmpty()) {

        QString importFormatsInfo;
        QString importFormatsFilterList;
        QHash<QString, QString> iconsMap;

        QJsonObject configObject = document.object();
        if (!configObject.isEmpty()) {
            QJsonArray fileFormats = configObject["importFormats"].toArray();
            int formatsCounter = 0;
            foreach (const QJsonValue& fileFormat, fileFormats) {
                QJsonObject fileFormatObject = fileFormat.toObject();

                QString ext(fileFormatObject["extension"].toString());
                QString icon(fileFormatObject.value("icon").toString());

                if (formatsCounter > 0) {
                    importFormatsInfo.append(",");
                }

                // set ' or' on last import type text
                if (formatsCounter == fileFormats.count() - 1) {
                    importFormatsInfo.append(" or");
                }

                importFormatsFilterList.append(QString("*.%1 ").arg(ext));
                importFormatsInfo.append(" .").append(ext);
                iconsMap[ext] = icon;
                formatsCounter++;
            }
Пример #10
0
QJsonObject HeadData::toJson() const {
    QJsonObject headJson;
    const auto& blendshapeLookupMap = getBlendshapesLookupMap();
    QJsonObject blendshapesJson;
    for (auto name : blendshapeLookupMap.keys()) {
        auto index = blendshapeLookupMap[name];
        float value = 0.0f;
        if (index < _blendshapeCoefficients.size()) {
            value += _blendshapeCoefficients[index];
        }
        if (index < _transientBlendshapeCoefficients.size()) {
            value += _transientBlendshapeCoefficients[index];
        }
        if (value != 0.0f) {
            blendshapesJson[name] = value;
        }
    }
    if (!blendshapesJson.isEmpty()) {
        headJson[JSON_AVATAR_HEAD_BLENDSHAPE_COEFFICIENTS] = blendshapesJson;
    }
    if (getRawOrientation() != quat()) {
        headJson[JSON_AVATAR_HEAD_ROTATION] = toJsonValue(getRawOrientation());
    }
    auto lookat = getLookAtPosition();
    if (lookat != vec3()) {
        vec3 relativeLookAt = glm::inverse(_owningAvatar->getOrientation()) *
            (getLookAtPosition() - _owningAvatar->getPosition());
        headJson[JSON_AVATAR_HEAD_LOOKAT] = toJsonValue(relativeLookAt);
    }
    return headJson;
}
Пример #11
0
bool nd::model::loadModel(QJsonObject attributes)
{
    if (attributes.isEmpty()) return true;    
    QStringList keys = attributes.keys();
    QString key;
    foreach (key, keys) {
        qDebug() << key;
        if (hasAttribute(key)){
            QVariant value;
            modelDefinition::modelFieldDefinition field = definition->field(key);
            if (field.type == modelDefinition::object || field.type == modelDefinition::array) {
                if (field.type == modelDefinition::object)  {
                    QJsonObject field_def = attributes.value(key).toObject();
                    value = QVariant::fromValue(QSharedPointer<protoObject>(definition->application()->model(field.objectName)->create(field_def)));
                } else {
                    QJsonArray field_list = attributes.value(key).toArray();
                    QList<QSharedPointer<protoObject> > list;
                    int i = 0, len = field_list.count();
                    for (; i < len; i++) {
                        qDebug() << i;
                        QJsonObject field_def = field_list.at(i).toObject();
                        qDebug() << field.name << field.objectName;
                        list.append(QSharedPointer<protoObject>(definition->application()->model(field.objectName)->create(field_def)));
                    }
                    value = QVariant::fromValue(list);
                };
            } else {
                value = QVariant(attributes.value(key).toVariant());
            };
            this->setProperty(key.toLatin1(), value);
        };
    }
Пример #12
0
QRect KonvergoWindow::loadGeometryRect()
{
  QJsonObject obj = QJsonObject::fromVariantMap(SettingsComponent::Get().value(SETTINGS_SECTION_STATE, "geometry").toMap());
  if (obj.isEmpty())
    return QRect();

  QRect rc(obj["x"].toInt(), obj["y"].toInt(), obj["width"].toInt(), obj["height"].toInt());

  if (rc.width() < 1280)
    rc.setWidth(1280);

  if (rc.height() < 720)
    rc.setHeight(720);

  // make sure our poisition is contained in one of the current screens
  foreach (QScreen *screen, QGuiApplication::screens())
  {
    if (screen->availableGeometry().contains(rc))
      return rc;
  }

 // otherwise default to center of current screen
  return QRect((screen()->geometry().width() - geometry().width()) / 2,
               (screen()->geometry().height() - geometry().height()) / 2,
               geometry().width(),
               geometry().height());
}
Пример #13
0
void ServerSummaryPage::saveSettings()
{
	QJsonObject o {
		{config::ClientTimeout.name, int(d->clientTimeout->value() * 60)},
		{config::AllowGuests.name, d->allowGuests->isChecked()},
		{config::AllowGuestHosts.name, d->allowGuestHosts->isChecked()},
		{config::SessionSizeLimit.name, d->sessionSizeLimit->value() * 1024 * 1024},
		{config::IdleTimeLimit.name, d->idleTimeout->value() * 60},
		{config::SessionCountLimit.name, d->sessionSizeLimit->value()},
		{config::EnablePersistence.name, d->persistence->isChecked()},
		{config::ArchiveMode.name, d->archiveSessions->isChecked()},
		{config::PrivateUserList.name, d->privateUserList->isChecked()}
	};

	QJsonObject update;
	for(auto i=o.constBegin();i!=o.constEnd();++i) {
		if(d->lastUpdate[i.key()] != i.value())
			update[i.key()] = i.value();
	}

	if(!update.isEmpty()) {
		d->lastUpdate = o;

		qDebug() << "update" << update;
		d->server->makeApiRequest(REQ_ID, JsonApiMethod::Update, QStringList() << "server", update);
	}
}
Пример #14
0
void ServerImpl::handleRegisterFiles(QHttpRequest *req, QHttpResponse *resp)
{
    req->storeBody();
    connect(req, &QHttpRequest::end,  [this, req, resp]() {
        QByteArray jsonTextBin = req->body();
        QJsonObject json = QJsonDocument::fromJson(jsonTextBin).object();
        QByteArray content("ok");
        if (!json.isEmpty()) {
            FileInfo fi;
            fi.filename = json["filename"].toString();
            fi.filepath = json["filepath"].toString();
            fi.hash = json["md5"].toString();
            fi.ttl = json["ttl"].toInt();
            fi.registeredTime = QDateTime::currentDateTime();

            if (!fi.filename.isEmpty() && !fi.hash.isEmpty() && QFile::exists(fi.filepath)) {
                mRegisteredFiles[fi.hash] = fi;
            }
        }

        resp->setHeader("Content-Length", QString::number(content.length()));
        setContentType(resp, "text/plain");
        resp->writeHead(200); // everything is OK
        resp->write(content);
        resp->end();
    });
}
Пример #15
0
//TODO: Separate class for Parsed result (allows managing error info)
QList<GoogleFeedQueryResult*> QtGoogleFeedApi::parseFindResponse(QJsonObject response, QString* parseError)
{
    if (parseError == 0) { QString tempError; parseError = &tempError; }

    QList<GoogleFeedQueryResult*> results;
    QJsonObject responseData = getResponseData(response, parseError);
    if (responseData.isEmpty()) {
        return results;
    }

    QJsonArray entries = responseData["entries"].toArray();
    foreach (QJsonValue value, entries)
    {
        QJsonObject entry = value.toObject();

        // TODO: Instead of having a builder, I should just have a constructor
        // (or virtual function) that takes a QJsonObject... (like GoogleFeedItem)
        GoogleFeedQueryResultBuilder builder(this);

        builder.setUrl(QUrl(entry["url"].toString()));
        builder.setTitle(entry["title"].toString());
        builder.setLink(QUrl(entry["link"].toString()));
        builder.setContentSnippet(entry["contentSnippet"].toString());

        results.append(builder.createResultObject());
    }
Пример #16
0
bool VDirectoryTree::pasteAvailable() const
{
    QJsonObject obj = VUtils::clipboardToJson();
    if (obj.isEmpty()) {
        return false;
    }

    if (!obj.contains(ClipboardConfig::c_type)) {
        return false;
    }

    ClipboardOpType type = (ClipboardOpType)obj[ClipboardConfig::c_type].toInt();
    if (type != ClipboardOpType::CopyDir) {
        return false;
    }

    if (!obj.contains(ClipboardConfig::c_magic)
        || !obj.contains(ClipboardConfig::c_isCut)
        || !obj.contains(ClipboardConfig::c_dirs)) {
        return false;
    }

    int magic = obj[ClipboardConfig::c_magic].toInt();
    if (!checkMagic(magic)) {
        return false;
    }

    QJsonArray dirs = obj[ClipboardConfig::c_dirs].toArray();
    return !dirs.isEmpty();
}
Пример #17
0
QList<QString> Parser::parseFeatures(QNetworkReply *reply)
{
    // Empfangene Nachricht auslesen und als JSON interpretieren
    QByteArray response(reply->readAll());
    QJsonDocument document = QJsonDocument::fromJson(response);
    QJsonObject object = document.object();

    QList<QString> activeFeatures;

    if(object.isEmpty())
    {
        QLOG_INFO() << tr("Featureinformationen leer bzw. nicht lesbar.") <<":"<<reply->url();
        return activeFeatures;
    }

    if(!object["Status"].toBool())
    {
        QLOG_ERROR() << tr("Status der Featureinformationen nicht ok: ") <<
                        QString(document.toJson());
        return activeFeatures;
    }

    // Array mit allen einzelnen Vorlesungen/Veranstaltungen
    QJsonArray courses = object["active"].toArray();

    // Für jede Veranstaltung ein neues Strukturelement anlegen
    foreach(QJsonValue element, courses)
    {
        activeFeatures << element.toString();
    }

    return activeFeatures;
}
Пример #18
0
void UserActivityLogger::logAction(QString action, QJsonObject details, JSONCallbackParameters params) {
    if (_disabled.get()) {
        return;
    }
    
    auto accountManager = DependencyManager::get<AccountManager>();
    QHttpMultiPart* multipart = new QHttpMultiPart(QHttpMultiPart::FormDataType);
    
    // Adding the action name
    QHttpPart actionPart;
    actionPart.setHeader(QNetworkRequest::ContentDispositionHeader, "form-data; name=\"action_name\"");
    actionPart.setBody(QByteArray().append(action));
    multipart->append(actionPart);
    
    // If there are action details, add them to the multipart
    if (!details.isEmpty()) {
        QHttpPart detailsPart;
        detailsPart.setHeader(QNetworkRequest::ContentDispositionHeader, "form-data;"
                              " name=\"action_details\"");
        detailsPart.setBody(QJsonDocument(details).toJson(QJsonDocument::Compact));
        multipart->append(detailsPart);
    }
    
    // if no callbacks specified, call our owns
    if (params.isEmpty()) {
        params.errorCallbackReceiver = this;
        params.errorCallbackMethod = "requestError";
    }
    
    accountManager->sendRequest(USER_ACTIVITY_URL,
                               AccountManagerAuth::Optional,
                               QNetworkAccessManager::PostOperation,
                               params, NULL, multipart);
}
Пример #19
0
void NetWork::dealGetListInfo(QNetworkReply *reply)
{
	QJsonObject obj = getObject(*reply);
	if (obj.isEmpty())
		return;
	QJsonObject resultObj = obj.find("result").value().toObject();
	QJsonArray listObj = resultObj.find("tracks").value().toArray();

	QList<QStringList> rev_list;
	for (int i = 0; i < listObj.size(); i++)
	{
		QJsonObject mp3Obj = listObj.at(i).toObject();
		QString url = mp3Obj.find("mp3Url").value().toString();
		QString name = mp3Obj.find("name").value().toString();
		QJsonArray artistsList = mp3Obj.find("artists").value().toArray();
		QString artists = "";
		for (int j = 0; j < artistsList.count(); j++)
		{
			QJsonObject artistsObjName = artistsList.at(j).toObject();
			artists.append(artistsObjName.find("name").value().toString() + " ");
		}
		QJsonObject albumObj = mp3Obj.find("album").value().toObject();
		QString album = albumObj.find("name").value().toString();
		int songId = mp3Obj.find("id").value().toInt();
		QStringList list;
		list << name << artists << album << url << QString::number(songId);
		rev_list.insert(i, list);
	}
	emit musicInfo(rev_list);
}
Пример #20
0
void YunClient::replyFinished()
{
    if (reply->error() == QNetworkReply::NoError){
        QByteArray str = reply->readAll();
        qDebug() << " request return ::: " << str;

        QJsonObject dataJson = getRequestData(QString(str));
        switch (request_type) {
        case get_version_list:{
            QJsonArray listJson = setPagingInfo(dataJson);
            setVersionList(listJson);
            break;
        }
        case get_media_list:{
            if (dataJson.isEmpty())
                dialog->close();
            else
                setUpdateList(dataJson);
            break;
        }
        default:
            break;
        }
    } else {
        //获取响应的信息,状态码为200表示正常
        QVariant status_code = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);
        qDebug() << "request error! return code : " << status_code.toInt();
    }


    reply->deleteLater();
    reply = 0;
}
Пример #21
0
void Item::loadFromJson(const QJsonObject &json)
{
    if (json.isEmpty()) {
        return;
    }

    setSku(json.value(QStringLiteral("sku")).toString());

    setName(json.value(QStringLiteral("name")).toString());

    setDescription(json.value(QStringLiteral("description")).toString());

    setQuantity(json.value(QStringLiteral("quantity")).toInt());

    setPrice(json.value(QStringLiteral("price")).toString().toFloat());

    setCurrency(json.value(QStringLiteral("currency")).toString());

    setTax(json.value(QStringLiteral("tax")).toString().toFloat());

    const QString sUrl = json.value(QStringLiteral("url")).toString();
    if (!sUrl.isEmpty()) {
        setUrl(QUrl(sUrl));
    } else {
        setUrl(QUrl());
    }
}
Пример #22
0
//******************************************************************************************
//function: doQuery
//params: const QString &lpzQuery
//return: QJsonArray
//Description:
//******************************************************************************************
QJsonArray WSClient::doQuery( const QString &lpzQuery )
{
    if (!this->getCheckLogin()) {
        throw WSClientException( this->jsLoginError );
    }

    QHash<QString, QString> params;
    params.insert("query", lpzQuery);

    QJsonObject response = Get("query", params);
    params.clear();

    if ( !response.isEmpty() ) {
        QVariantMap map_json  = response.toVariantMap();
        QVariant success      = map_json.value("success");

        if ( success.toBool() ) {
            return response.value("result").toArray();
        }
        else {
            QJsonObject error = response.value("error").toObject();
            throw WSClientException( error );
        }
    }
    throw WSClientException( jsNoData );
}
Пример #23
0
//******************************************************************************************
//function: doSetRelated
//params: const QString &relate_this_id, const QString &with_this_ids
//return: QJsonObject
//Description:
//Set relation between records.
//param relate_this_id string ID of record we want to related other records with
//param with_this_ids string/array either a string with one unique ID or an array of IDs to relate to the first parameter
//******************************************************************************************
QJsonObject WSClient::doSetRelated(const QString &relate_this_id, const QString &with_these_ids)
{
    if (!this->getCheckLogin()) {
        throw WSClientException( this->jsLoginError );
    }

    QHash<QString, QString> params;
    params.insert("relate_this_id", relate_this_id);
    params.insert("with_these_ids", with_these_ids);

    qDebug() << params;

    QJsonObject response = Post("SetRelation", params);
    params.clear();

    if ( !response.isEmpty() ) {
        QVariantMap map_json  = response.toVariantMap();
        QVariant success      = map_json.value("success");

        if ( success.toBool() ) {
            return response.value("result").toObject();
        }
        else {
            QJsonObject error = response.value("error").toObject();
            throw WSClientException( error );
        }
    }
    throw WSClientException( jsNoData );
}
Пример #24
0
    SearchResponseSnippet VideoStructure::extractVideoItemSnippet( QJsonObject const & object )
    {
        SearchResponseSnippet response_snippet{};
        if( object.isEmpty() ) return response_snippet;

        QString snippet_publishDate = object["publishedAt"].toString(),
                snippet_channelID = object["channelId"].toString(),
                snippet_title = object["title"].toString(),
                snippet_description = object["description"].toString(),
                snippet_channelTitle = object["channelTitle"].toString(),
                snippet_liveBroadcatContent = object["liveBroadcastContent"].toString();

        response_snippet.setPublishedDate( snippet_publishDate );
        response_snippet.setChannelID( snippet_channelID );
        response_snippet.setTitle( snippet_title );
        response_snippet.setDescription( snippet_description );
        response_snippet.setChannelTitle( snippet_channelTitle );
        response_snippet.setLiveBroadcastContent( snippet_liveBroadcatContent );

        QJsonObject snippet_thumbnails = object["thumbnails"].toObject();
        if( !snippet_thumbnails.isEmpty() )
        {
            QJsonObject default_key = snippet_thumbnails["default"].toObject(),
                        medium_key = snippet_thumbnails["medium"].toObject(),
                        high_key = snippet_thumbnails["high"].toObject();
            response_snippet.addThumbnail( "default", getSnippetThumbnailKey( default_key ));
            response_snippet.addThumbnail( "medium", getSnippetThumbnailKey( medium_key ) );
            response_snippet.addThumbnail( "high", getSnippetThumbnailKey( high_key ) );
        }
        return response_snippet;
    }
Пример #25
0
//******************************************************************************************
//function: doRetrieve
//params: const QString id
//return: QJsonObject
//Description:
//******************************************************************************************
QJsonObject WSClient::doRetrieve(const QString id)
{
    if (!this->getCheckLogin()) {
        throw WSClientException( this->jsLoginError );
    }

    QHash<QString, QString> params;
    params.insert("id", id);

    QJsonObject response = Get("retrieve", params);
    params.clear();

    if ( !response.isEmpty() ) {
        QVariantMap map_json  = response.toVariantMap();
        QVariant success      = map_json.value("success");

        if ( success.toBool() ) {
            return response.value("result").toObject();
        }
        else {
            QJsonObject error = response.value("error").toObject();
            throw WSClientException( error );
        }
    }

    return response;
}
void sampledetailwidget::queryPatientSuccess(const QJsonObject & patient) {
    if (!patient.isEmpty()) {
//        patient_id_edit->setText(patient["patient_id"].toString());
        patient_id_edit->setText(patient["patient_fake_id"].toString());
        patient_name_edit->setText(patient["patient_name"].toString());

        int n = patient["patient_gender"].toInt();
        patient_gender_box->setCurrentIndex(n);

        int age = patient["patient_age"].toInt();
        patient_age_edit->setText(QString("%1").arg(age));

        QString section = patient["patient_section"].toString();
        patient_section_edit->setText(section);

        QString section_no = patient["patient_section_no"].toString();
        patient_section_id_edit->setText(section_no);

        QString bed_no = patient["patient_bed_no"].toString();
        patient_section_bed_id_edit->setText(bed_no);

    } else {
        qDebug() << "query patient empty" << endl;
    }
}
Пример #27
0
Tweet::Tweet(const QJsonObject &json)
{
    // Use the retweeted status when possible
    QJsonObject tweet {json};
    QJsonObject retweetedTweet {json.value(QLatin1String("retweeted_status")).toObject()};
    QJsonObject displayedTweet {tweet};
    if (!retweetedTweet.isEmpty()) {
        displayedTweet = retweetedTweet;

        // Adding the retweeting user when retweeting
        m_retweetingUser = std::move(User(tweet.value(QLatin1String("user")).toObject()));
    }

    m_id = std::move(tweet.value(QLatin1String("id_str")).toString());
    m_originalId = std::move(displayedTweet.value(QLatin1String("id_str")).toString());
    m_text = std::move(displayedTweet.value(QLatin1String("text")).toString());
    m_favoriteCount = displayedTweet.value(QLatin1String("favorite_count")).toInt();
    m_favorited = displayedTweet.value(QLatin1String("favorited")).toBool();
    m_retweetCount = displayedTweet.value(QLatin1String("retweet_count")).toInt();
    m_retweeted = displayedTweet.value(QLatin1String("retweeted")).toBool();
    m_inReplyTo = std::move(displayedTweet.value(QLatin1String("in_reply_to_status_id")).toString());
    m_source = std::move(tweet.value(QLatin1String("source")).toString());
    m_timestamp = std::move(private_util::fromUtc(displayedTweet.value(QLatin1String("created_at")).toString()));
    m_user = std::move(User(displayedTweet.value(QLatin1String("user")).toObject()));

    QJsonObject entities {displayedTweet.value(QLatin1String("entities")).toObject()};
    QJsonObject extendedEntities {displayedTweet.value(QLatin1String("extended_entities")).toObject()};
    m_entities = Entity::create(entities, extendedEntities);
    m_quotedStatus = std::move(QuotedTweet(displayedTweet.value(QLatin1String("quoted_status")).toObject()));
}
Пример #28
0
GeometryPtr JSonGeometryParser::toGeometry(const QJsonObject& object)
{
    if (object.isEmpty()) return GeometryPtr();

    GeometryPtr geometry(new Geometry());

    geometry->setType(keys::typeMap.key(
                          object.value(keys::geometryType).toString()));

    const QJsonArray& coordinatesArray =
            object.value(keys::coordinates).toArray();
    if (!coordinatesArray.isEmpty())
    {
        geometry->setPoints(::jSonArrayToPoints(coordinatesArray,
                                                geometry->type()));
    }

    const QJsonArray& geometriesArray =
            object.value(keys::geometries).toArray();
    if (!geometriesArray.isEmpty())
    {
        GeometryPtrList geometries;
        for (const QJsonValue& geometryValue: geometriesArray)
        {
            geometries.append(JSonGeometryParser::
                              toGeometry(geometryValue.toObject()));
        }
        geometry->setChildGeometries(geometries);
    }

    return geometry;
}
Пример #29
0
void GetRequest::exec(AbstractWeiboApi *apiRequest)
{
  QByteArray responseStr;
  if (apiRequest->isHttpGet())
    responseStr = manager->getMethod(apiRequest->getUrl());
  else {
    QHttpMultiPart multiPart(QHttpMultiPart::FormDataType);
    QList<QHttpPart> partList = apiRequest->setPostMultiPart();
    for (int i = 0; i < partList.size(); i++)
      multiPart.append(partList.at(i));

    responseStr = manager->postMethod(apiRequest->getUrl(), multiPart);
  }
  QString error;
  JsonParser parser(responseStr);

  QJsonObject responseMap = parser.getJsonObject();

  if (responseMap.isEmpty())
    error = responseStr;
  else
    error = apiRequest->parse(responseMap);

  if (responseMap.find("error") != responseMap.end())
    error = responseStr;

  emit sendLog(apiRequest->getUrl().toString(), QDateTime::currentDateTime(),
               responseMap, error);
}
Пример #30
0
QVariant Expression::view(int column) const {
    if (column == 1) {
        QString key = expression[column].toString();
        QJsonObject prop = Config::expressionsDefinitions[key];
        if (!prop.isEmpty()) return createView(prop);
    }
    return expression[column].toString();
}