Esempio n. 1
0
void QStreamCubeChat::onSmilesLoaded()
{
    QNetworkReply * reply = qobject_cast< QNetworkReply * >( sender() );

    QJsonParseError parseError;

    QJsonDocument jsonDoc = QJsonDocument::fromJson( reply->readAll(), &parseError );

    if( QJsonParseError::NoError == parseError.error && jsonDoc.isArray() )
    {
        QJsonArray jsonArr =jsonDoc.array();

        for( const QJsonValue & smileVal : jsonArr )
        {
            QJsonArray smileInfo = smileVal.toArray();

            addSmile( smileInfo[ 0 ].toString(), DEFAULT_STREAM_CUBE_SMILE_PREFIX + smileInfo[ 1 ].toString() );
        }

        if( isShowSystemMessages() )
        {
            emit newMessage( ChatMessage( SERVICE_NAME, SERVICE_USER_NAME, tr( "Smiles loaded..." ), QString(), this ) );
            emitSystemMessage( SERVICE_NAME, SERVICE_USER_NAME, tr( "Smiles loaded..." ) );
        }
    }
    else
    {
        emit newMessage( ChatMessage( SERVICE_NAME, SERVICE_USER_NAME, tr( "Can not load smiles..." ), QString(), this ) );
        emitSystemMessage( SERVICE_NAME, SERVICE_USER_NAME, tr( "Can not laod smiles..." ) );
    }

    reply->deleteLater();
}
Esempio n. 2
0
inline bool loadDocument(const std::string &path, QJsonValue &root)
{
    // Load schema JSON from file
    QFile file(QString::fromStdString(path));
    if (!file.open(QFile::ReadOnly)) {
        std::cerr << "Failed to load json from file '" << path << "'." << std::endl;
        return false;
    }

    QByteArray data = file.readAll();

    // Parse schema
    QJsonParseError parseError;
    QJsonDocument doc = QJsonDocument::fromJson(data);
    if (doc.isNull()) {
        std::cerr << "qt failed to parse the document:" << std::endl
                  << parseError.errorString().toStdString() << std::endl;
        return false;
    } else if (doc.isObject()) {
        root = QJsonValue(doc.object());
    } else if (doc.isArray()) {
        root = QJsonValue(doc.array());
    } else if (doc.isEmpty()) {
        root = QJsonValue();
    }

    return true;
}
Esempio n. 3
0
QString Api::getDefaultPatcherSecret(CancellationToken cancellationToken) const
{
    qInfo() << "Getting the default patcher secret";
    QString path = "1/system/patchers";

    QJsonDocument document = get(path, cancellationToken);

    if (!document.isArray())
    {
        throw InvalidFormatException("Expected document root to be array");
    }

    QJsonArray array = document.array();

    QString platformString = Globals::currentPlatformString();

    for (QJsonValueRef item : array)
    {
        if (item.isObject())
        {
            QJsonObject object = item.toObject();

            if (object.contains(platformString))
            {
                return object[platformString].toString();
            }
        }
    }

    throw InvalidFormatException("Failed to resolve patcher for platform " + platformString);
}
Esempio n. 4
0
int TestMonitor::loadJsonArray(QString &fileName,QJsonArray &jsonAry )
{
    pthread_mutex_lock(&conn_mutex);
    QFile file;

    QString sampleDir = "doc/json_sample/";
    file.setFileName(sampleDir + fileName);
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        DEBUG_INFO << "Failed to open json sameple file:" + fileName;
        return PL_RET_FAIL;
    }

    QString data = file.readAll();
    file.close();

    QJsonDocument sd = QJsonDocument::fromJson(data.toUtf8());
    if (!sd.isArray() || sd.isNull() || sd.isEmpty())
    {
        DEBUG_INFO << "Failed to open json sameple file:" + fileName;
        pthread_mutex_unlock(&conn_mutex);
        return PL_RET_FAIL;
    }

    jsonAry = sd.array();

    return PL_RET_OK;

}
Esempio n. 5
0
std::vector<CGorjunFileInfo>
CRestWorker::get_gorjun_file_info(const QString &file_name) {
  static const QString str_fi("file/info");
  int http_code, err_code, network_error;
  QUrl url_gorjun_fi(CSettingsManager::Instance().gorjun_url().arg(str_fi));
  QUrlQuery query_gorjun_fi;
  query_gorjun_fi.addQueryItem("name", file_name);
  url_gorjun_fi.setQuery(query_gorjun_fi);
  QNetworkRequest request(url_gorjun_fi);
  request.setHeader(QNetworkRequest::ContentTypeHeader,"application/json");
  QByteArray arr = send_get_request(request, http_code, err_code, network_error);
  QJsonDocument doc  = QJsonDocument::fromJson(arr);

  std::vector<CGorjunFileInfo> lst_res;
  if (doc.isNull()) {
    err_code = RE_NOT_JSON_DOC;
    return lst_res;
  }

  if (doc.isArray()) {
    QJsonArray json_arr = doc.array();
    for (auto i = json_arr.begin(); i != json_arr.end(); ++i) {
      if (i->isNull() || !i->isObject()) continue;
      lst_res.push_back(CGorjunFileInfo(i->toObject()));
    }
  } else if (doc.isObject()) {
    lst_res.push_back(CGorjunFileInfo(doc.object()));
  }

  return lst_res;
}
Esempio n. 6
0
bool CurrencyPane::LoadCurrencyRates(const QString &data)
{
    QMap<QString, QJsonObject> dataObjects;
    QJsonDocument doc = QJsonDocument::fromJson(data.toLatin1());
    if (!doc.isNull() && doc.isArray()) {
        QJsonArray arr = doc.array();
        for (QJsonValue v : arr) {
            if (!v.isObject()) continue;
            QJsonObject obj = v.toObject();
            dataObjects.insert(obj.value("currency").toString(), obj);
        }
    }

    for (int i = 0; i < ui->currencyTable->rowCount(); i++) {
        QTableWidgetItem* header = ui->currencyTable->verticalHeaderItem(i);
        if (dataObjects.contains(header->text())) {
            QJsonObject obj = dataObjects.value(header->text());
            int count = obj.value("count").toInt();
            int chaos = obj.value("chaos").toInt();

            QWidget* widget = ui->currencyTable->cellWidget(i, 1);
            QSpinBox* currencyBox = widget->findChild<QSpinBox*>("CurrencyCount");
            QSpinBox* chaosBox = widget->findChild<QSpinBox*>("ChaosCount");

            if (currencyBox && chaosBox) {
                currencyBox->setValue(count);
                chaosBox->setValue(chaos);
            }
        }
    }
    UpdateItemChaosValues();
    return true;
}
Esempio n. 7
0
void QEglFSEmulatorIntegration::screenInit()
{
    QEglFSIntegration *integration = static_cast<QEglFSIntegration *>(QGuiApplicationPrivate::platformIntegration());

    // Use qgsGetDisplays() call to retrieve the available screens from the Emulator
    if (getDisplays) {
        QByteArray displaysInfo = getDisplays();
        QJsonParseError error;
        QJsonDocument displaysDocument = QJsonDocument::fromJson(displaysInfo, &error);
        if (error.error == QJsonParseError::NoError) {
            // Document should be an array of screen objects
            if (displaysDocument.isArray()){
                QJsonArray screenArray = displaysDocument.array();
                for (auto screenValue : screenArray) {
                    if (screenValue.isObject())
                        integration->addScreen(new QEglFSEmulatorScreen(screenValue.toObject()));
                }
            }
        } else {
            qWarning() << "eglfs_emu: Failed to parse display info JSON with error: " << error.errorString()
                       << " at offset " << error.offset << " : " << displaysInfo;

        }
    } else {
        qFatal("EGL library doesn't support Emulator extensions");
    }
}
Esempio n. 8
0
QString CurrencyPane::SaveCurrencyHistoryPoint()
{
    QJsonObject point;
    double time = (double)QDateTime(QDate::currentDate()).toTime_t();
    point.insert("value", totalValue);
    point.insert("time", time);

    QByteArray data = QByteArray::fromStdString(app_->data_manager().Get("currency_history"));
    QJsonDocument doc = QJsonDocument::fromJson(data);
    QJsonArray array;
    if (!doc.isNull() && doc.isArray()) {
        array = doc.array();
    }
    bool insert = true;
    for (QJsonValue val : array) {
        if (val.isObject() && val.toObject().value("time").toDouble() == time) {
            insert = false;
            break;
        }
    }
    if (insert) array.append(point);
    doc.setArray(array);

    QString newData = doc.toJson(QJsonDocument::Compact);
    app_->data_manager().Set("currency_history", newData.toStdString());
    LoadCurrencyHistory(newData);
    return newData;
}
Esempio n. 9
0
void MainWindow::fetchListFinished()
{
    ui->loadButton->setEnabled(true);

    QNetworkReply *reply = senderAsReply();
    if (reply == nullptr || reply->error() != QNetworkReply::NoError)
    {
        return;
    }

    QJsonDocument json = jsonFromReply(reply);
    if (!json.isArray())
    {
        logMessage(tr("Error: not array"));
        return;
    }

    QJsonArray arr = json.array();
    for (QJsonValue v : arr)
    {
        QJsonObject task = v.toObject();
        QVariant taskId = task["id"].toVariant();
        QString taskName = task["name"].toString();
        createListItem(taskId, taskName);
    }

    ui->deleteButton->setEnabled(true);
    ui->addButton->setEnabled(true);
}
QVector<Language> LoadSupportLanguage() {
    QFile json(":/support_languages.json");
    qDebug()<<"Open File"<<json.open(QIODevice::ReadOnly);

    QVector<Language> supportLanguagesList;
    QJsonParseError json_error;
    QJsonDocument supportLanguages = QJsonDocument::fromJson(json.readAll(), &json_error);
    json.close();
    if(json_error.error == QJsonParseError::NoError) {
        if (supportLanguages.isArray()) {
            QJsonArray languresArray = supportLanguages.array();
            int size = languresArray.size();
            for (int i = 0; i < size; ++i) {
                Language language;
                QJsonValue languageJson = languresArray.at(i);
                QJsonObject languageObject = languageJson.toObject();
                language.Locale =languageObject.take("Locale").toString();
                language.Description = languageObject.take("Description").toString();
                language.LanguageCode = languageObject.take("LanguageCode").toString();
                language.CountryCode = languageObject.take("CountryCode").toString();
                supportLanguagesList.push_back(language);
            }
        }
    }
    return supportLanguagesList;
}
Esempio n. 11
0
void JSONDataSource::load()
{
    QByteArray data;
    
    QFile file(QDir::toNativeSeparators(QDir::homePath()) + "/" + FILENAME);
    if (!file.open(QIODevice::ReadOnly))
    {
        return;
    }
    else
    {        
        QJsonDocument doc = QJsonDocument::fromJson(file.readAll());
        
        if(doc.isArray())
        {
            QJsonArray pupilObjects = doc.array();
            for (int i = 0; i < pupilObjects.count(); i++)
            {
                Pupil* p = decode(pupilObjects.at(i).toObject());
                pupils->append(p);
            }
        }
        
        file.close();
        
    }
}
Esempio n. 12
0
void WebRequest::replyFinished(QNetworkReply* reply)
{
    if(reply == nullptr)
        return;

    mtxCallback.lock();
    CallbackReply callback = mapCallback[reply];
    mapCallback.remove(reply);
    mtxCallback.unlock();

    if(reply->error() == QNetworkReply::NoError)
    {
        QByteArray raw = reply->readAll();
        QJsonDocument doc = QJsonDocument::fromJson(raw);
        if(doc.isArray())
        {
            QJsonObject obj;
            obj["array"] = doc.array();
            callback(obj);
        }
        else
        {
            callback(doc.object());
        }
    }
    else
    {
        callback(QJsonObject());
    }

    reply->deleteLater();
}
Esempio n. 13
0
    void mergeJson(const QJsonDocument &mergeFrom, QJsonDocument &mergeTo, bool overwrite, CompareValuesJson &comparer) {
        if (mergeFrom.isNull()) {
            LOG_WARNING << "attempted to merge with Null json document";
            return;
        }

        if (overwrite || mergeTo.isNull()) {
            LOG_DEBUG << "Overwriting the document";
            mergeTo = mergeFrom;
        } else {
            if (mergeFrom.isArray()) {
                QJsonArray arrayFrom = mergeFrom.array();
                QJsonArray arrayTo = mergeTo.array();

                if (mergeJsonArrays(arrayFrom, arrayTo, comparer)) {
                    mergeTo.setArray(arrayTo);
                }
            } else {
                QJsonObject objectFrom = mergeFrom.object();
                QJsonObject objectTo = mergeTo.object();

                if (mergeJsonObjects(objectFrom, objectTo, comparer)) {
                    mergeTo.setObject(objectTo);
                }
            }
        }
    }
Esempio n. 14
0
bool RuleListModel::realDeserializeData()
{
    QSettings setting("Ray Fung", "Excel JSON");
    QByteArray json = setting.value("rule_list", QByteArray("[]")).toByteArray();
    QJsonDocument doc = QJsonDocument::fromJson(json);

    ruleList.clear();

    if(doc.isArray() == false)
        return false;

    QJsonArray array = doc.array();
    int count = array.size();

    for(int i = 0; i < count; ++i)
    {
        QJsonValue val = array.at(i);

        if(val.isObject() == false)
            return false;

        QJsonObject data = val.toObject();
        RuleData rule;
        RuleItem item;

        rule.isEnabled = data.value("enable").toBool(true);
        rule.excelPath = data.value("excel_path").toString();
        rule.jsonPath = data.value("json_path").toString();

        item.setRule(rule);
        ruleList.append(item);
    }

    return true;
}
Esempio n. 15
0
void QStreamCubeChat::onChannelInfoLoaded()
{
    QNetworkReply * reply = qobject_cast< QNetworkReply * >( sender() );

    QJsonParseError parseError;

    QJsonDocument jsonDoc = QJsonDocument::fromJson( reply->readAll(), &parseError );

    if( QJsonParseError::NoError == parseError.error && jsonDoc.isArray() )
    {
        QJsonArray jsonArr = jsonDoc.array();

        channelId_ = jsonArr[ 0 ].toString();

        if( isShowSystemMessages() )
        {
            emit newMessage( ChatMessage( SERVICE_NAME, SERVICE_USER_NAME, tr( "Connected to " ) + channelName_ + tr( "..." ), QString(), this ) );
            emitSystemMessage( SERVICE_NAME, SERVICE_USER_NAME, tr( "Connected to " ) + channelName_ + tr( "..." ) );
        }

        loadMessages();
        startUniqueTimer( updateTimerId_, UPDATE_INTERVAL );
    }

    reply->deleteLater();
}
Esempio n. 16
0
void RemDev::handleItem(char *data) {
	/*if (data.size() > MAX_TRANSACTION_SIZE) {
		// TODO
		return;
	}*/
	QJsonParseError error;
	QJsonDocument doc = QJsonDocument::fromJson(data, &error);
	// Check for registration before handling parsing errors because it will just
	// return if any errors occurred (we don't want to send anything to prevent
	// overload attacks if we're unregistered)
	if ( ! registered) {
		if ( ! doc.isObject()) return;
		handleRegistration(doc.object());
		return;
	}
	if (error.error != QJsonParseError::NoError) {
		
		return;
	}
	if (doc.isArray()) {
		// TODO
		return;
	}
	if (doc.isObject()) {
		QJsonObject obj = doc.object();
		handleObject(obj);
		return;
	}
	// TODO:  Failed
}
bool TestClusterModel::loadFromFile(const QString& fileName) {
    QFile file(fileName);
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        return false;
    }
    QByteArray bytes = file.readAll();
    file.close();
    QJsonParseError parseError;
    QJsonDocument doc = QJsonDocument::fromJson(bytes, &parseError);
    if (parseError.error != QJsonParseError::NoError) {
        return false;
    }
    if (!doc.isArray()) {
        return false;
    }
    QList<HostInfo> newHosts;
    QJsonArray array = doc.array();
    for (const QJsonValue& value : array) {
        HostInfo info;
        QJsonObject object = value.toObject();
        QJsonValue typeVal = object["type"];
        if (!typeVal.isString()) {
            return false;
        }
        int type = findHostTypeByInternalName(typeVal.toString().toUtf8().data());
        if (type < 0) {
            return false;
        }
        info.type = (HostType)type;
        QJsonValue portVal = object["port"];
        if (!portVal.isDouble()) {
            return false;
        }
        info.port = static_cast<int>(portVal.toDouble());
        QJsonValue dbPathVal = object["dbPath"];
        if (dbPathVal.isString()) {
            info.dbPath = dbPathVal.toString();
        }
        QJsonValue replicaSetVal = object["replicaSet"];
        if (replicaSetVal.isString()) {
            info.replicaSet = replicaSetVal.toString();
        }
        QJsonValue configDBVal = object["configDB"];
        if (configDBVal.isString()) {
            info.configDB = configDBVal.toString();
        }
        newHosts.append(info);
    }
    for (HostInfo& info : newHosts) {
        info.process = new QProcess(this);
        info.state = QProcess::NotRunning;
    }
    beginInsertRows(QModelIndex(), 0, newHosts.size() - 1);
    _hosts = newHosts;
    endInsertRows();
    _fileName = fileName;
    _dirty = false;
    return true;
}
Esempio n. 18
0
void QTweetHomeTimeline::parseJsonFinished(const QJsonDocument &jsonDoc)
{
    if (jsonDoc.isArray()) {
        QList<QTweetStatus> statuses = QTweetConvert::jsonArrayToStatusList(jsonDoc.array());

        emit parsedStatuses(statuses);
    }
}
Esempio n. 19
0
void QTweetDirectMessagesSent::parseJsonFinished(const QJsonDocument &jsonDoc)
{
    if (jsonDoc.isArray()) {
        QList<QTweetDMStatus> directMessages = QTweetConvert::jsonArrayToDirectMessagesList(jsonDoc.array());

        emit parsedDirectMessages(directMessages);
    }
}
void QTweetBlocksBlocking::parseJsonFinished(const QJsonDocument &jsonDoc)
{
    if (jsonDoc.isArray()) {
        QList<QTweetUser> userlist = QTweetConvert::jsonArrayToUserInfoList(jsonDoc.array());

        emit finishedGettingBlocks(userlist);
    }
}
Esempio n. 21
0
void NgfpReader::formFromJson (const QJsonDocument &j_form, NgmFormView *form, Project *project, Screen *screen)
{
    if (!j_form.isArray())
        throw "Form: not a proper JSON object";
    QJsonArray j_form_arr = j_form.array();

    containerFromJson(j_form_arr, const_cast<Container*>(form->getContainer()), project, screen);
}
Esempio n. 22
0
void NJson::parse(QByteArray byteArray)
{
    QJsonDocument doc = QJsonDocument::fromJson(byteArray);
    if (doc.isArray()) {
        mRootValue = QJsonValue(doc.array());
    } else {
        mRootValue = QJsonValue(doc.object());
    }
}
Esempio n. 23
0
void QTweetDirectMessagesShow::parseJsonFinished(const QJsonDocument &jsonDocument)
{
    if (jsonDocument.isArray()) {
        QList<QTweetDMStatus> directMessages = QTweetConvert::jsonArrayToDirectMessagesList(jsonDocument.array());

        if (directMessages.size())
            emit parsedDirectMessage(directMessages.at(0));
    }
}
Esempio n. 24
0
Problem Problem::fromJson(const QByteArray& json)
{
    QJsonDocument document = QJsonDocument::fromJson(json);

    if (document.isObject())
        return fromJsonObject(document.object());
    else if (document.isArray())
        return fromJsonArray(document.array());

    return Problem();
}
Esempio n. 25
0
QMap<QString, QVariant> JsonDecoder::decode(QByteArray json) {
    QMap<QString, QVariant> map;
    QJsonDocument document = QJsonDocument::fromJson(json);

    if(document.isObject()) {
        map = document.object().toVariantMap();
    } else if(document.isArray()) {
        //map = document.array().to
    }

    return map;
}
QVariant NoronJsonBinarySerializer::deserialize(QByteArray bytes)
{
    QJsonDocument doc = QJsonDocument::fromJson(bytes);
    if(doc.isArray())
        return fromJson(QJsonDocument::fromJson(bytes).array());
    if(doc.isObject())
        return fromJson(QJsonDocument::fromJson(bytes).object());

    qWarning("Input string is not valid serialized json");
    qWarning(bytes);
    return QVariant();
}
Esempio n. 27
0
void StatusChecker::statusDownloadFinished()
{
	QLOG_DEBUG() << "Finished loading status JSON.";

	QByteArray data;
	{
		ByteArrayDownloadPtr dl = std::dynamic_pointer_cast<ByteArrayDownload>(m_statusNetJob->first());
		data = dl->m_data;
		m_statusNetJob.reset();
	}

	QJsonParseError jsonError;
	QJsonDocument jsonDoc = QJsonDocument::fromJson(data, &jsonError);

	if (jsonError.error != QJsonParseError::NoError)
	{
		fail("Error parsing status JSON:" + jsonError.errorString());
		return;
	}

	if (!jsonDoc.isArray())
	{
		fail("Error parsing status JSON: JSON root is not an array");
		return;
	}

	QJsonArray root = jsonDoc.array();

	for(auto status = root.begin(); status != root.end(); ++status)
	{
		QVariantMap map = (*status).toObject().toVariantMap();

		for (QVariantMap::const_iterator iter = map.begin(); iter != map.end(); ++iter)
		{
			QString key = iter.key();
			QVariant value = iter.value();

			if(value.type() == QVariant::Type::String)
			{
				m_statusEntries.insert(key, value.toString());
				//QLOG_DEBUG() << "Status JSON object: " << key << m_statusEntries[key];
			}
			else
			{
				fail("Malformed status JSON: expected status type to be a string.");
				return;
			}
		}
	}

	succeed();
}
Esempio n. 28
0
void QStreamCubeChat::onMessagesLoaded()
{
    QNetworkReply * reply = qobject_cast< QNetworkReply * >( sender() );

    QByteArray data = reply->readAll();

    QJsonParseError parseError;

    QJsonDocument jsonDoc = QJsonDocument::fromJson( data, &parseError );

    if( QJsonParseError::NoError == parseError.NoError && jsonDoc.isArray() )
    {
        QJsonArray jsonMessagesArr = jsonDoc.array();

        if( "0" == lastMessageId_ )
        {
            for( const QJsonValue & messageValue : jsonMessagesArr )
            {
                QJsonArray messageInfoArr = messageValue.toArray();

                if( messageInfoArr[ 1 ].toString().toInt() > lastMessageId_.toInt() )
                    lastMessageId_ = messageInfoArr[ 1 ].toString();
            }
        }
        else
        {
            for( const QJsonValue & messageValue : jsonMessagesArr )
            {
                QJsonArray messageInfoArr = messageValue.toArray();

                if( messageInfoArr[ 1 ].toString().toInt() > lastMessageId_.toInt() )
                {
                    QString nickName = messageInfoArr[ 3 ].toString();
                    QString message = messageInfoArr[ 5 ].toString();

                    if( "1" == messageInfoArr[ 0 ].toString() )
                    {
                        message = messageInfoArr[ 7 ].toString() + ", " + message;
                    }

                    message = insertSmiles( message );

                    lastMessageId_ = messageInfoArr[ 1 ].toString();

                    emit newMessage( ChatMessage( SERVICE_NAME, nickName, message, QString(), this ) );
                }
            }
        }
    }

    reply->deleteLater();
}
void QTweetBlocksBlockingIDs::parseJsonFinished(const QJsonDocument &jsonDoc)
{
    if (jsonDoc.isArray()) {
        QList<qint64> useridlist;

        QJsonArray varJsonArray = jsonDoc.array();

        for (int i = 0; i < varJsonArray.size(); ++i)
            useridlist.append(static_cast<qint64>(varJsonArray[i].toDouble()));

        emit finishedGettingIDs(useridlist);
    }
}
Esempio n. 30
0
void QJsonView::setJson(const QString &text)
{
    clear();
    QJsonDocument document = QJsonDocument::fromJson(text.toUtf8());

    if( document.isArray() ) {
        buildArray("", document.array());
    } else if( document.isObject() ) {
        buildObject("", document.object());
    } else {
        throw -1;
    }
}