Ejemplo n.º 1
0
void ImgurUpload::processReply(const QByteArray &data)
{
    // Obtain the root object from the JSON response
    QJsonObject object(QJsonDocument::fromJson(data).object());

    // Attempt to retrieve the value for "success" and "data->link"
    bool success = object.value(QStringLiteral("success")).toBool();
    QJsonObject dataObject = object.value(QStringLiteral("data")).toObject();
    QString dataLink = dataObject.value(QStringLiteral("link")).toString();
    QString dataError = dataObject.value(QStringLiteral("error")).toString();

    // Ensure that "success" is true & link is valid, otherwise throw an error
    if (!success || dataLink.isNull()) {
        if (dataError.isNull()) {
            dataError = tr("unknown error response");
        }
        Q_EMIT error(dataError);
    } else {
        Q_EMIT completed(dataLink);
    }
}
Ejemplo n.º 2
0
void Plugin14CForm::setData(const QJsonObject& data, bool isCombined)
{
    QLocale locale=QLocale();
    double a = data.value(DATE_14C_AGE_STR).toDouble();
    double e = data.value(DATE_14C_ERROR_STR).toDouble();
    double r = data.value(DATE_14C_DELTA_R_STR).toDouble();
    double re = data.value(DATE_14C_DELTA_R_ERROR_STR).toDouble();
    QString c = data.value(DATE_14C_REF_CURVE_STR).toString().toLower();
    
    mAverageEdit->setText(locale.toString(a));
    mErrorEdit->setText(locale.toString(e));
    mREdit->setText(locale.toString(r));
    mRErrorEdit->setText(locale.toString(re));
    mRefCombo->setCurrentText(c);
    
    mAverageEdit->setEnabled(!isCombined);
    mErrorEdit->setEnabled(!isCombined);
    mREdit->setEnabled(!isCombined);
    mRErrorEdit->setEnabled(!isCombined);
    mRefCombo->setEnabled(!isCombined);
}
Ejemplo n.º 3
0
void BillingInstrument::loadFromJson(const QJsonObject &json)
{
    if (json.isEmpty()) {
        return;
    }

    setBillingAgreementId(json.value(QStringLiteral("billing_agreement_id")).toString());

    const QJsonObject sio = json.value(QStringLiteral("selected_installment_option")).toObject();
    InstallmentDescription *oldSio = selectedInstallmentOption();
    if (!sio.isEmpty()) {
        if (oldSio) {
            oldSio->loadFromJson(sio);
        } else {
            setSelectedInstallmentOption(new InstallmentDescription(sio, this));
        }
    } else {
        setSelectedInstallmentOption(nullptr);
        delete oldSio;
    }
}
Ejemplo n.º 4
0
void Lines::read(const QJsonObject &jsonObj)
{
    QJsonArray ar = jsonObj["lines"].toArray();

    for(int i = 0; i < ar.size(); i++)
    {
        QJsonObject jObj = ar.at(i).toObject();
        Line *line = new Line(jObj.value("id").toVariant().toInt(),
                              jObj.value("type_id").toVariant().toInt(),
                              jObj.value("line").toString(),
                              jObj.value("type_name").toString());

        if(getCurrentGettingLineType() == line->getLineType())
            mLines.push_back(line);
//        else if(getCurrentGettingLineType() == "0" || getCurrentGettingLineType() == "")
//            qWarning() << "" << getCurrentGettingLineType() << line->getLineType();
//        else  //is not a bus|metro|rer ...

    }
    emit linesListChanged();
}
Ejemplo n.º 5
0
void SailfishPlatform::actionTriggered(const QUuid &uuid, const QString &actToken, const QJsonObject &param) const
{
    qDebug() << "Triggering notification" << uuid << "action" << actToken << QJsonDocument(param).toJson();
    watchfish::Notification *notif = m_notifs.value(uuid);
    if (notif) {
        if(actToken.split(":").first()=="open") {
            notif->invokeAction(actToken.split(":").last());
        } else if(actToken == "response") {
            if(param.contains("sender") && !notif->actionArgs(param.value("sender").toString()).isEmpty()
                    && notif->actionArgs(param.value("sender").toString()).at(0).toString().startsWith("/org/freedesktop/Telepathy/Account"))
                telepathyResponse(
                            notif->actionArgs(param.value("sender").toString()).at(0).toString(), // account dbus path
                            notif->actionArgs(param.value("sender").toString()).at(1).toString(), // destination contact
                            param.value("title").toString() // message text
                            );
            else
                qDebug() << "Don't know how to respond to" << notif->category() << notif->actionArgs(actToken);
        }
    } else
        qDebug() << "Not found";
}
Ejemplo n.º 6
0
    void EtherIPC::handleGetBlock() {
        QJsonValue jv;
        if ( !readReply(jv) ) {
            return bail();
        }

        const QJsonObject block = jv.toObject();
        const quint64 num = Helpers::toQUInt64(block.value("number"));
        emit getBlockNumberDone(num);
        emit newBlock(block);
        done();
    }
Ejemplo n.º 7
0
State buildState (QJsonObject const &stateObj)
{
  State state;

  state.name = stateObj.value("name").toString();
  auto transitionsValue = stateObj.value("transitions");
  if (!transitionsValue.isUndefined()) {
    state.transitions = buildTransitionList(transitionsValue.toArray());
  }
  auto typeValue = stateObj.value("type");
  if (!typeValue.isUndefined()) {
    state.type = typeValue.toString();
  }

  auto commandValue = stateObj.value("command");
  if (!commandValue.isUndefined()) {
    state.command = commandValue.toString();
  }
  
  return state;
}
void MusicRadioSongsThread::downLoadFinished()
{
    if(m_reply == nullptr)
    {
        deleteAll();
        return;
    }

    if(m_reply->error() == QNetworkReply::NoError)
    {
        QByteArray bytes = m_reply->readAll();
#ifdef MUSIC_QT_5
        QJsonParseError jsonError;
        QJsonDocument parseDoucment = QJsonDocument::fromJson(bytes, &jsonError);
        ///Put the data into Json
        if(jsonError.error != QJsonParseError::NoError ||
           !parseDoucment.isObject())
        {
            deleteAll();
            return ;
        }

        QJsonObject jsonObject = parseDoucment.object();
        if(jsonObject.contains("data"))
        {
            jsonObject = jsonObject.value("data").toObject();
            if(jsonObject.contains("songList"))
            {
                QJsonArray array = jsonObject.value("songList").toArray();
                foreach(QJsonValue value, array)
                {
                    if(!value.isObject())
                    {
                       continue;
                    }
                    QJsonObject object = value.toObject();

                    m_songInfo.m_songUrl = object.value("songLink").toString();
                    m_songInfo.m_songName = object.value("songName").toString();
                    m_songInfo.m_artistName = object.value("artistName").toString();
                    m_songInfo.m_songPicUrl = object.value("songPicRadio").toString();
                    m_songInfo.m_albumName = object.value("albumName").toString();
                    QString lrcLink = object.value("lrcLink").toString();
                    if(!lrcLink.contains( LRC_PREFIX ))
                    {
                        lrcLink = LRC_PREFIX + lrcLink;
                    }
                    m_songInfo.m_lrcUrl = lrcLink;
                }
            }
Ejemplo n.º 9
0
void BuyoutManager::Deserialize(const std::string &data, QMap<QString, Buyout> *buyouts) {
    buyouts->clear();

    // if data is empty (on first use) we shouldn't make user panic by showing ERROR messages
    if (data.empty())
        return;

    QJsonParseError err;
    QJsonDocument doc = QJsonDocument::fromJson(QByteArray::fromStdString(data), &err);
    if (err.error != QJsonParseError::NoError) {
        QLOG_ERROR() << "Error while parsing buyouts.";
        QLOG_ERROR() << err.errorString();
        return;
    }
    if (!doc.isObject()) {
        QLOG_ERROR() << "Error while parsing buyouts.";
        QLOG_ERROR() << "Value is not an object.";
        return;
    }

    for (QString key : doc.object().keys()) {
        QJsonObject object = doc.object().value(key).toObject();
        Buyout bo;

        bo.currency = static_cast<Currency>(Util::TagAsCurrency(object.value("currency").toString().toStdString()));
        bo.type = static_cast<BuyoutType>(Util::TagAsBuyoutType(object.value("type").toString().toStdString()));
        bo.value = object.value("value").toDouble();
        bo.last_update = QDateTime();
        bo.set_by = "";

        if (object.contains("last_update")) {
            bo.last_update = QDateTime::fromTime_t(object.value("last_update").toInt());
        }
        if (object.contains("set_by")) {
            bo.set_by = object.value("set_by").toString();
        }

        buyouts->insert(key, bo);
    }
}
Ejemplo n.º 10
0
void MainWindow::slotGetIssuesFinished(const QList<QJsonValue> &issues)
{
    qDebug() << "slotGetMyIssuesFinished count: " << issues.count();

    // getting list of current issues
    QStringList currentIssuesList;
    for (int i = 0; i<m_issuesModel->rowCount(); i++) {
        currentIssuesList << m_issuesModel->index(i, Globals::IdColumn).data().toString();
    }

    QStringList projectsList;

    foreach (QJsonValue i, issues) {
        QJsonObject obj = i.toObject();
        QList<QStandardItem *> row;
        QStandardItem *project = new QStandardItem(obj.value("project").toObject().value("name").toString());
        QStandardItem *id = new QStandardItem(QString::number(obj.value("id").toDouble()));
        QStandardItem *priority = new QStandardItem(obj.value("priority").toObject().value("name").toString());
        QStandardItem *subject = new QStandardItem(obj.value("subject").toString());

        // sort everything alphabetically and only priority by a real priority (from blocker to low)
        project->setData(project->text(), Globals::SortRole);
        id->setData(id->text(), Globals::SortRole);
        priority->setData(ui->comboFilterByPriority->findText(priority->text()), Globals::SortRole);
        subject->setData(subject->text(), Globals::SortRole);

        // adding new projects
        if (!projectsList.contains(project->text())) {
            projectsList << project->text();
        }

        // adding new issues
        if (m_issuesModel->findItems(id->text(), Qt::MatchExactly, Globals::IdColumn).size() == 0) {
            row << project << id << priority << subject;
            m_issuesModel->appendRow(row);
        }
        else {
            currentIssuesList.removeAll(id->text());
        }
    }
Ejemplo n.º 11
0
void PluginMagForm::setData(const QJsonObject& data, bool isCombined)
{
    QLocale locale=QLocale();
    bool is_inc = data.value(DATE_AM_IS_INC_STR).toBool();
    bool is_dec = data.value(DATE_AM_IS_DEC_STR).toBool();
    bool is_int = data.value(DATE_AM_IS_INT_STR).toBool();
    
    double inc = data.value(DATE_AM_INC_STR).toDouble();
    double dec = data.value(DATE_AM_DEC_STR).toDouble();
    double intensity = data.value(DATE_AM_INTENSITY_STR).toDouble();
    double error = data.value(DATE_AM_ERROR_STR).toDouble();
    QString ref_curve = data.value(DATE_AM_REF_CURVE_STR).toString().toLower();
    
    mIncRadio->setChecked(is_inc);
    mDecRadio->setChecked(is_dec);
    mIntensityRadio->setChecked(is_int);
    
    mIncEdit->setText(locale.toString(inc));
    mDecEdit->setText(locale.toString(dec));
    mDecIncEdit->setText(locale.toString(inc));
    mIntensityEdit->setText(locale.toString(intensity));
    mAlpha95Edit->setText(locale.toString(error));
    
    mRefCombo->setCurrentText(ref_curve);
    
  //  updateOptions();
}
Ejemplo n.º 12
0
int Evaluator::target(const QString &target)
{
	for (LangSpec *spec : langSpecs)
	{
		int ret = this->target(target, spec);
		if (ret != 0)
			return ret;
	}
	if (target == "deploy" && mgr)
	{
		bool gameExists = false; int gameid = -1;
		QPair<QString, QByteArray> result = apiGetCall("/api/gametypes");
		if (!result.first.isEmpty())
		{
			fprintf(stderr, "Fehler beim Abrufen der Spiele: %s\n", qPrintable(result.first));
			return 1;
		}
		QJsonDocument jsonDoc = QJsonDocument::fromJson(result.second);
		QJsonArray gametypes = jsonDoc.array();
		for (int i = 0; i < gametypes.size(); i++)
		{
			QJsonObject gametype = gametypes[i].toObject();
			
			if (gametype.value("name").toString() == instructions().values().value("NAME"))
			{
				gameExists = true;
				gameid = gametype.value("id").toInt();
			}
			
		}
		
		if (gameExists)
		{
			QString error = apiGetCall("/api/make_data_container/" + QString::number(gameid)).first;
			if (!error.isEmpty())
				fprintf(stderr, "Fehler beim Bauen dese Daten-Containers (wird von Codr benötigt): %s\n", qPrintable(error));
		}
	}
	return 0;
}
Ejemplo n.º 13
0
static std::vector<TVertex> LoadJsonModel(const QString& fileName) {
      QString val;
      QFile file;
      file.setFileName(fileName);
      file.open(QIODevice::ReadOnly | QIODevice::Text);
      val = file.readAll();
      file.close();

      QJsonDocument d = QJsonDocument::fromJson(val.toUtf8());
      QJsonObject meshes = d.object().value("meshes").toArray().at(0).toObject();

      QJsonArray vertices = meshes.value("vertices").toArray();
      QJsonArray normals = meshes.value("normals").toArray();
      QJsonArray tangents = meshes.value("tangents").toArray();
      QJsonArray bitangents = meshes.value("bitangents").toArray();
      QJsonArray texturecoords = meshes.value("texturecoords").toArray().at(0).toArray();
      QJsonArray faces = meshes.value("faces").toArray();

      std::vector<TVertex> data;
      size_t objectSize = vertices.size() / 3;
      for (size_t i = 0; i < objectSize; ++i) {
          TVertex v;

          size_t idx = i * 3;
          size_t idx2 = i * 2;

          v.Position.setX(vertices.at(idx + 0).toDouble());
          v.Position.setY(vertices.at(idx + 1).toDouble());
          v.Position.setZ(vertices.at(idx + 2).toDouble());

          v.Normal.setX(normals.at(idx + 0).toDouble());
          v.Normal.setY(normals.at(idx + 1).toDouble());
          v.Normal.setZ(normals.at(idx + 2).toDouble());

          v.Tangent.setX(tangents.at(idx + 0).toDouble());
          v.Tangent.setY(tangents.at(idx + 1).toDouble());
          v.Tangent.setZ(tangents.at(idx + 2).toDouble());

          v.Bitangent.setX(bitangents.at(idx + 0).toDouble());
          v.Bitangent.setY(bitangents.at(idx + 1).toDouble());
          v.Bitangent.setZ(bitangents.at(idx + 2).toDouble());

          v.UV.setX(texturecoords.at(idx2 + 0).toDouble());
          v.UV.setY(texturecoords.at(idx2 + 1).toDouble());

          data.push_back(v);
      }

      std::vector<TVertex> dataFull;
      for (size_t i = 0; i < faces.size(); ++i) {
          QJsonArray face = faces.at(i).toArray();
          Q_ASSERT(face.size() == 3);
          for (size_t j = 0; j < face.size(); ++j) {
              int idx = face.at(j).toInt();
              dataFull.push_back(data[idx]);
          }
      }

      return dataFull;
}
Ejemplo n.º 14
0
//FIXME: Can't handle subscriptions with many labels(tags, whatever)
void MainWindow::handleSubscriptionsResp(QByteArray data)
{
    QJsonParseError jerror;
    QJsonDocument doc = QJsonDocument::fromJson(data,&jerror);
    qDebug()<<doc;
    if(jerror.error == QJsonParseError::NoError || ! doc.isEmpty()) {
        QJsonArray arr = doc.array();
        QString tempTitle,templabel,tempId;
        QStandardItem *parent;
        QStandardItem *sub;
        for(int row = 0;row<arr.size();row++)
        {
            QJsonObject obj = arr[row].toObject();
            tempTitle = obj.value("title").toString();
            tempId = obj.value("id").toString();
            qDebug()<<tempTitle;
            qDebug()<<tempId;
            if(!subscription.contains(tempTitle)) {
                subscription.append(tempTitle);
                sub = new QStandardItem(tempTitle);
                QJsonArray ca = obj.value("categories").toArray();
                if(!ca.isEmpty()) {
                    for(int row2 = 0;row2<ca.size();row2++) {
                        QJsonObject obj2 = ca[row2].toObject();
                        templabel = obj2.value("label").toString();
                        qDebug()<<templabel;
                    }
                }
                else {
                    templabel = "Uncategorized";
                }
                parent = categorieMap.find(templabel).value();
                if(parent && !tempId.isEmpty()) {
                    sub->setData(QVariant::fromValue(tempId),FEED_ID);
                    parent->appendRow(sub);
                }
            }
        }
    }
}
Ejemplo n.º 15
0
bool ColorSchemePresets::initialize(const QJsonObject & presets)
{
    static const auto warning = QString("Cannot retrieve color scheme category \"%1\" from Json object: ");

    auto categoryNamesByIndex = QMultiMap<int, QString>();

    static const auto CATEGORY_INDEX = QString{ "index" };

    for (const auto & identifier : presets.keys())
    {
        auto schemes = presets.value(identifier).toObject();
        if (schemes.isEmpty())
        {
            qWarning() << qPrintable(warning.arg(identifier) + "value object is empty.");
            return false;
        }

        if (!schemes.contains(CATEGORY_INDEX))
        {
            qWarning() << qPrintable(warning.arg(identifier) + "value object is missing category index.");
            return false;
        }

        const auto index = schemes.value(CATEGORY_INDEX).toInt();
        categoryNamesByIndex.insertMulti(index, identifier);
    }

    for (const auto index : categoryNamesByIndex.keys())
    {
        for (const auto & identifier : categoryNamesByIndex.values(index))
        {
            auto schemes = presets.value(identifier).toObject();
            schemes.take(CATEGORY_INDEX);

            push_back(new ColorSchemeGroup(identifier, schemes));
        }
    }

    return !isEmpty();
}
Ejemplo n.º 16
0
void SymbolBehavior::fromJson(const QJsonObject &json)
{
    ItemBehavior::fromJson(json);

    int type = json.value(DataKey::SymbolType).toInt();
    setData(type, LP::SymbolType);

    int instrument = json.value(DataKey::Instrument).toInt();
    setData(instrument, LP::SymbolInstrument);

    QString name = json.value(DataKey::SymbolName).toString();
    setData(name, LP::SymbolName);

    if (hasOption(HasLength)) {
        int length = json.value(DataKey::Lenght).toInt();
        Length::Value lengthValue = static_cast<Length::Value>(length);
        setData(QVariant::fromValue<Length::Value>(lengthValue), LP::SymbolLength);
    }

    if (hasOption(HasPitch)) {
        QJsonObject pitchObject = json.value(DataKey::Pitch).toObject();
        Pitch pitch;
        pitch.fromJson(pitchObject);
        setData(QVariant::fromValue<Pitch>(pitch), LP::SymbolPitch);
    }

    int spanType = json.value(DataKey::SymbolSpanType).toInt();
    if (spanType != 0) {
        SpanType type = static_cast<SpanType>(spanType);
        setData(QVariant::fromValue<SpanType>(type), LP::SymbolSpanType);
    }
}
Ejemplo n.º 17
0
int Branch::makePart(bool isHandler, QJsonArray *arr)
{
    for (int i=0; i < arr->count(); i++) {
        if (arr->at(i).isObject() != true)
            return -1;

        QJsonObject obj = arr->at(i);

        if (obj.value("Type").isString() != true)
           return -1;

        if (obj.value("Options").isObject() != true)
            return -1;

        IConnector *part;
        if (isHandler) {
            part = HandlerFact::MakeHandler(obj.value("Type").toString(), obj.value("Options").toObject());
        } else {
            part = TransportFact::makeTransport(obj.value("Type").toString(), obj.value("Options").toObject());
        }

        if (part == NULL)
            return -1;

        addPart(part);
    }
    return 0;
}
Ejemplo n.º 18
0
CharacterItemLocation::CharacterItemLocation(const QJsonObject& data)
    : ItemLocation()
{
    QJsonObject characterData = data.value("character").toObject();
    QJsonArray itemData = data.value("items").toArray();
    _name = characterData.value("name").toString();
    _league = characterData.value("league").toString();
    _class = characterData.value("class").toString();
    _level = characterData.value("level").toInt();

    for (QJsonValue itemVal : itemData) {
        auto item = new Item(itemVal.toObject());
        _items.append(item);
    }

    if (InventoryLayout.isEmpty()) {
        InventoryLayout.insert("Weapon", QPointF(0,0));
        InventoryLayout.insert("Offhand", QPointF(2,0));
        InventoryLayout.insert("Weapon2", QPointF(8,0));
        InventoryLayout.insert("Offhand2", QPointF(10,0));
        InventoryLayout.insert("Helm", QPointF(5,0));
        InventoryLayout.insert("BodyArmour", QPointF(5,2));
        InventoryLayout.insert("Belt", QPointF(5,5));
        InventoryLayout.insert("Gloves", QPointF(3,4));
        InventoryLayout.insert("Boots", QPointF(7,4));
        InventoryLayout.insert("Ring", QPointF(4,3));
        InventoryLayout.insert("Ring2", QPointF(7,3));
        InventoryLayout.insert("Amulet", QPointF(7,2));
        InventoryLayout.insert("Flask", QPointF(3.5,6));
    }
}
Ejemplo n.º 19
0
void EglFSKmsIntegration::saveConfiguration(const QString &fileName)
{
    qCInfo(lcKms) << "Saving configuration to" << fileName;

    QFileInfo fileInfo(fileName);
    fileInfo.absoluteDir().mkpath(QLatin1String("."));

    QFile file(fileName);
    if (!file.open(QFile::ReadWrite)) {
        qCWarning(lcKms) << "Could not open configuration file"
                         << fileName << "for writing";
        return;
    }

    QJsonDocument doc = QJsonDocument::fromJson(file.readAll());

    QJsonObject rootObject;
    if (doc.isObject())
        rootObject = doc.object();

    file.seek(0);

    // Save device only if it was specified by the original configuration,
    // this will disable autodetect next time the configuration is
    // loaded: comes in handy on systems with multiple GPUs where the
    // user wants to pick a specific one instead of the first that
    // is autodetected
    QVariantMap map;
    map[QStringLiteral("hwcursor")] = m_hwCursor;
    map[QStringLiteral("pbuffers")] = m_pbuffers;
    const QString devicePath = rootObject.value(QStringLiteral("kms")).toObject().value(QStringLiteral("device")).toString();
    if (!devicePath.isEmpty())
        map[QStringLiteral("device")] = devicePath;
    map[QStringLiteral("separateScreens")] = m_separateScreens;

    QJsonArray outputs;
    Q_FOREACH (const QScreen *screen, QGuiApplication::screens()) {
        EglFSKmsScreen *kmsScreen = static_cast<EglFSKmsScreen *>(screen->handle());
        if (!kmsScreen)
            continue;

        QVariantMap output;
        output[QStringLiteral("name")] = screen->name();
        if (kmsScreen->currentMode() == kmsScreen->preferredMode())
            output[QStringLiteral("mode")] = QStringLiteral("preferred");
        else
            output[QStringLiteral("mode")] = QStringLiteral("%1x%2")
                                             .arg(QString::number(kmsScreen->geometry().size().width()))
                                             .arg(QString::number(kmsScreen->geometry().size().height()));

        outputs.append(QJsonValue::fromVariant(output));
    }
Ejemplo n.º 20
0
bool Option::loadOption()
{
    QJsonDocument jsonDocument;


    fileOption = new QFile(this->jsonFilename);
    if(fileOption->open(QIODevice::ReadOnly))
    {
        QTextStream fileStream(fileOption);
        QString dataFromJson = fileStream.readAll();
        jsonDocument = QJsonDocument::fromJson(dataFromJson.toUtf8());


        QJsonObject jobjOption = jsonDocument.object();

        if(jobjOption.value("language").toString() == "french")
            this->language = Option::french;
        else if(jobjOption.value("language").toString() == "english")
            this->language = Option::english;
        else
        {

            this->language = Option::english;
        }

        this->volume = jobjOption.value("volume").toDouble(-1);
        this->mute = jobjOption.value("mute").toBool(false);

        fileOption->close();
        return true;
    }
    else
    {
        fileOption->close();

        return false;
    }

}
Ejemplo n.º 21
0
//! [onTextMessageReceived]
void EchoClient::onTextMessageReceived(QString message)
{
    // only resume if greeting was successful
    if(!m_greetingFinished){
        return;
    }

    qDebug() << "Message received:" << message;
    QJsonDocument jsonMessage = QJsonDocument::fromJson(message.toUtf8());
    QJsonObject localObject = jsonMessage.object();
    QJsonObject header = localObject.value("header").toObject();
    int messageType = header.value("contentType").toInt();

    switch (messageType) {
    case Greeting:
        if(header.value("userId").toString() == m_userId){
            // greeting finished successfully, allow further communication
            m_greetingFinished = true;
        } else {
            m_greetingFinished = false;
        }
        break;
    case Ack_Server:


        break;
    case Ack_Destination:
    // update local db
        if(localObject.value("body").toObject().value("desc").toString() == "ChatData"){
            // its a chat ack, lets update the chat
            emit updateChatStatus(localObject.value("body").toObject().value("id").toInt(), ReachedDestination);
        }

        break;
    case ChatData:
        // save data
        emit incomingChatData(localObject);
        // send ack-destination
        sendAcknowledgement(Ack_Destination,
                            header.value("sender").toString(),
                            header.value("severName").toString(),
                            "ChatData",
                            localObject.value("body").toObject().value("id").toString());

        break;
    default:
        break;
    }
}
void tst_JsonBuffer::utf8()
{
    int n = sizeof(utf8spaces) / sizeof(utf8spaces[0]);
    for (int i = 0 ; i < n ; i++ ) {
        QJsonBuffer buf;
        buf.append(utf8spaces[i], strlen(utf8spaces[i]));

        QVERIFY(buf.messageAvailable());
        QJsonObject a = buf.readMessage();
        QCOMPARE(a.value("a").toDouble(), 123.0);

        QVERIFY(buf.messageAvailable());
        QJsonObject b = buf.readMessage();
        QCOMPARE(b.value("b").toDouble(), 234.0);

        QVERIFY(!buf.messageAvailable());
        QVERIFY(buf.format() == FormatUTF8);

        if (0 == i)
            QVERIFY(buf.size() == 0); // buffer should be empty at the end
    }
}
Ejemplo n.º 23
0
QJsonValue Config::findKey(const QString& name)
{
	QStringList strList = name.split('/', QString::SkipEmptyParts);

	QJsonValue jVal(config);
	for (QStringList::const_iterator sIter = strList.constBegin(); sIter != strList.constEnd(); ++sIter)
	{
		QJsonObject jObj = jVal.toObject();
		jVal = jObj.value(*sIter);
	}

	return jVal;
}
Ejemplo n.º 24
0
void NotificationsModel::_addItems(const QJsonObject& data)
{
    int size = _notifs.size();
    auto list = data.value("notifications").toArray();
    if (list.isEmpty())
    {
        _totalCount = size;
        emit hasMoreChanged();
        return;
    }

    _totalCount = data.value("total_count").toInt();
    
    beginInsertRows(QModelIndex(), size, size + list.size() - 1);

    _notifs.reserve(size + list.size());
    foreach(auto notif, list)
    {
        auto notification = new Notification(notif.toObject(), this);
        _notifs.insert(size, notification);
        _ids << notification->id(); //! \todo check existing ids
    }
Ejemplo n.º 25
0
void VirtTcpC::onPacketRecieved(QJsonObject jobj)
{
    int pkt_id = jobj.value("id").toInt();
    QString str_pkt_id = pkt_id == 0 ? jobj.value("id").toString() : QString("%1").arg(pkt_id);

    QByteArray hex_pkt = jobj.value("pkt").toString().toLocal8Bit();
    QByteArray pkt = QByteArray::fromHex(hex_pkt);

    qDebug()<<"SBR got pkt_id:"<<str_pkt_id<<pkt.length()<<"Bytes";

    QByteArray ba = "realClientDisconnected-hoho";
    if (pkt == ba) {
        this->m_sock->close();
    } else {
        if (this->m_sock->state() == QAbstractSocket::UnconnectedState) {
            this->connectToHost();
        }
        int rc = this->m_sock->write(pkt);
        qDebug()<<"SBR -> SSHD: Write: "<<rc;
        assert(rc == pkt.length());
    }
}
Ejemplo n.º 26
0
static Nuria::JsonMetaObjectReader::Error parseMethodObject (Nuria::MetaMethod::Type type, const QJsonObject &method,
							     Nuria::RuntimeMetaObject *metaObject) {
	using namespace Nuria;
	
	QJsonValue annotationsValue = method.value (QStringLiteral("annotations"));
	QJsonValue argNamesValue = method.value (QStringLiteral("argumentNames"));
	QJsonValue argTypesValue = method.value (QStringLiteral("argumentTypes"));
	QJsonValue resultTypeValue = method.value (QStringLiteral("resultType"));
	QJsonValue nameValue = method.value (QStringLiteral("name"));
	
	// Type checks
	if (!annotationsValue.isArray ()) return JsonMetaObjectReader::AnnotationsIsNotAnArray;
	if (!argNamesValue.isArray ()) return JsonMetaObjectReader::MethodArgumentNamesIsNotAnArray;
	if (!argTypesValue.isArray ()) return JsonMetaObjectReader::MethodArgumentTypesIsNotAnArray;
	if (!resultTypeValue.isString ()) return JsonMetaObjectReader::MethodResultTypeIsNotAString;
	if (!nameValue.isString ()) return JsonMetaObjectReader::MethodNameIsNotAString;
	
	// Parse annotations
	Nuria::JsonMetaObjectReader::Error error;
	
	RuntimeMetaObject::AnnotationMap annotations;
	error = parseAnnotationsArray (annotationsValue.toArray (), annotations);
	if (error != Nuria::JsonMetaObjectReader::NoError) return error;
	
	// Arguments
	QVector< QByteArray > argNames;
	QVector< QByteArray > argTypes;
	
	error = parseMethodArgumentList (argNamesValue.toArray (), argTypesValue.toArray (), argNames, argTypes);
	if (error != Nuria::JsonMetaObjectReader::NoError) return error;
	
	// Base
	QByteArray name = nameValue.toString ().toLatin1 ();
	QByteArray resultType = resultTypeValue.toString ().toLatin1 ();
	
	// Store
	metaObject->addMethod (type, name, resultType, argNames, argTypes, annotations, invalidCallbackCreator);
	return Nuria::JsonMetaObjectReader::NoError;
}
Ejemplo n.º 27
0
void ImageObject::setObject(const QJsonObject &object)
{
    m_object = object;
    QString fileId;
    fileId = object.value("file").toObject().value("id").toString();

    if (!fileId.isEmpty()) {
        QJsonObject fileObject;
        fileObject.insert("id", fileId);
        fileObject.insert("variant", QString("thumbnail"));
        EnginioReply *reply = m_enginio->downloadFile(fileObject);
        connect(reply, SIGNAL(finished(EnginioReply*)), this, SLOT(replyFinished(EnginioReply*)));
    } else {
Ejemplo n.º 28
0
bool Lz::PresetStorage::loadPresets(const QJsonObject& config)
{
    for(auto key : config.keys())
    {
        if(checkKey(key) && checkPresetConfig(config.value(key)))
        {
            Lz::Preset preset;
            for(auto s: config.value(key).toArray())
            {
                preset.append(s.toString());
            }
            m_presets[key] = preset;
        }
        else
        {
            /* TODO error report*/
            /* then change to 'return false;'. */
        }
    }
    emit presetsUpdated();
    return true;
}
Ejemplo n.º 29
0
// ========================================================================== //
// On reply data read.
// ========================================================================== //
bool AFtcomRequest::onReplyDataReady(int http_code, QByteArray &data) {
    int status_code = -1;

    if(!data.isEmpty()) {
        QJsonDocument doc = QJsonDocument::fromJson(data);
        if(doc.isObject()) {
            QJsonObject obj = doc.object();

            if(obj.contains(QStringLiteral("status")))
                status_code = obj.value(QStringLiteral("status")).toInt();

            if(obj.contains(QStringLiteral("message"))) {
                const QString msg
                    = obj.value(QStringLiteral("message")).toString();

                if(!msg.isEmpty()) emit message(msg);
            }
        }
    }

    return (http_code == 200 && status_code == 0) ? true : false;
}
Ejemplo n.º 30
0
 static void fillFrom(const QJsonObject& jo, GetPushersJob::Pusher& result)
 {
     fromJson(jo.value("pushkey"_ls), result.pushkey);
     fromJson(jo.value("kind"_ls), result.kind);
     fromJson(jo.value("app_id"_ls), result.appId);
     fromJson(jo.value("app_display_name"_ls), result.appDisplayName);
     fromJson(jo.value("device_display_name"_ls), result.deviceDisplayName);
     fromJson(jo.value("profile_tag"_ls), result.profileTag);
     fromJson(jo.value("lang"_ls), result.lang);
     fromJson(jo.value("data"_ls), result.data);
 }