Exemple #1
0
void CmdProvider::enqueuePacket(QString pkt_str)
{
    QJsonDocument jdoc = QJsonDocument::fromJson(pkt_str.toLocal8Bit());
    qDebug()<<"pkt type:"<<jdoc.isArray()<<jdoc.isObject()<<jdoc.isEmpty();
    if (jdoc.isEmpty()) {
        return;
    }

    QJsonObject jobj = jdoc.object();
    assert(jobj.contains("id") && jobj.contains("cmd"));
    this->m_q_cmds.enqueue(jobj);

    emit newCommand(jobj);
}
Exemple #2
0
QJsonDocument jsonparser::jsonOpenFile(QString filename){
    QFile jDocFile;
    QFileInfo cw(filename);
    if(startDir.isEmpty()){
        startDir = cw.absolutePath();
        jDocFile.setFileName(startDir+"/"+cw.fileName());
    }else
        jDocFile.setFileName(startDir+"/"+cw.fileName());
    if (!jDocFile.exists()) {
        sendProgressTextUpdate(tr("Failed due to the file %1 not existing").arg(jDocFile.fileName()));
        return QJsonDocument();
    }
    if (!jDocFile.open(QIODevice::ReadOnly|QIODevice::Text)) {
        sendProgressTextUpdate(tr("Failed to open the requested file"));
        return QJsonDocument();
    }
    QJsonParseError initError;
    QJsonDocument jDoc = QJsonDocument::fromJson(jDocFile.readAll(),&initError);
    if (initError.error != 0){
        reportError(2,tr("ERROR: jDoc: %s\n").arg(initError.errorString()));
        sendProgressTextUpdate(tr("An error occured. Please take a look at the error message to see what went wrong."));
        return QJsonDocument();
    }
    if (jDoc.isNull() || jDoc.isEmpty()) {
        sendProgressTextUpdate(tr("Failed to import file"));
        return QJsonDocument();
    }
    return jDoc;
}
Connection* ConfigHelper::configJsonToConnection(const QString &file)
{
    QFile JSONFile(file);
    JSONFile.open(QIODevice::ReadOnly | QIODevice::Text);
    if (!JSONFile.isOpen()) {
        qCritical() << "Error: cannot open " << file;
    }
    if(!JSONFile.isReadable()) {
        qCritical() << "Error: cannot read " << file;
    }

    QJsonParseError pe;
    QJsonDocument JSONDoc = QJsonDocument::fromJson(JSONFile.readAll(), &pe);
    JSONFile.close();
    if (pe.error != QJsonParseError::NoError) {
        qCritical() << pe.errorString();
    }
    if (JSONDoc.isEmpty()) {
        qCritical() << "JSON Document" << file << "is empty!";
        return nullptr;
    }
    QJsonObject configObj = JSONDoc.object();
    SQProfile p;
    p.serverAddress = configObj["server"].toString();
    p.serverPort = configObj["server_port"].toInt();
    p.localAddress = configObj["local_address"].toString();
    p.localPort = configObj["local_port"].toInt();
    p.method = configObj["method"].toString();
    p.password = configObj["password"].toString();
    p.timeout = configObj["timeout"].toInt();
    Connection *con = new Connection(p, this);
    return con;
}
QVariant ContentItemInterfacePrivate::parseReplyDataVariant(const QByteArray &replyData, bool *ok)
{
    QVariant parsed;

#if (QT_VERSION < QT_VERSION_CHECK(5, 0, 0))
    QJson::Parser jsonParser;
    parsed = jsonParser.parse(replyData, ok);
    if (!*ok) {
        qWarning() << Q_FUNC_INFO << "Error parsing JSON file:" << jsonParser.errorString()
                   << "at" << jsonParser.errorLine();
    }
#else
    QJsonParseError jsonError;
    QJsonDocument jsonDocument = QJsonDocument::fromJson(replyData, &jsonError);
    *ok = !jsonDocument.isEmpty();
    if (!*ok) {
        qWarning() << Q_FUNC_INFO << "Error parsing JSON file:" << jsonError.errorString()
                   << "at" << jsonError.offset;
    }
    parsed = jsonDocument.toVariant();
#endif

    if (!*ok) {
        parsed.clear();
    }

    return parsed;
}
Exemple #5
0
bool SaveToJSON(QVariantMap &data, QIODevice &f, const char *magicIdentifier, uint32_t magicVersion)
{
  // marker that this data is valid
  data[magicIdentifier] = magicVersion;

  QJsonDocument doc = QJsonDocument::fromVariant(data);

  if(doc.isEmpty() || doc.isNull())
  {
    qCritical() << "Failed to convert data to JSON document";
    return false;
  }

  QByteArray jsontext = doc.toJson(QJsonDocument::Indented);

  qint64 ret = f.write(jsontext);

  if(ret != jsontext.size())
  {
    qCritical() << "Failed to write JSON data: " << ret << " " << f.errorString();
    return false;
  }

  return true;
}
Exemple #6
0
void Repository::requestedDataReceived(const QByteArray& data) noexcept {
  QJsonDocument doc = QJsonDocument::fromJson(data);
  if (doc.isNull() || doc.isEmpty() || (!doc.isObject())) {
    emit errorWhileFetchingLibraryList(
        tr("Received JSON object is not valid."));
    return;
  }
  QJsonValue nextResultsLink = doc.object().value("next");
  if (nextResultsLink.isString()) {
    QUrl url = QUrl(nextResultsLink.toString());
    if (url.isValid()) {
      qDebug() << "Request more results from repository:" << url.toString();
      requestLibraryList(url);
    } else {
      qWarning() << "Invalid URL in received JSON object:"
                 << nextResultsLink.toString();
    }
  }
  QJsonValue reposVal = doc.object().value("results");
  if ((reposVal.isNull()) || (!reposVal.isArray())) {
    emit errorWhileFetchingLibraryList(
        tr("Received JSON object does not contain "
           "any results."));
    return;
  }
  emit libraryListReceived(reposVal.toArray());
}
Exemple #7
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;

}
Exemple #8
0
bool LoadFromJSON(QVariantMap &data, QIODevice &f, const char *magicIdentifier, uint32_t magicVersion)
{
  QByteArray json = f.readAll();

  if(json.isEmpty())
  {
    qCritical() << "Read invalid empty JSON data from file " << f.errorString();
    return false;
  }

  QJsonDocument doc = QJsonDocument::fromJson(json);

  if(doc.isEmpty() || doc.isNull())
  {
    qCritical() << "Failed to convert file to JSON document";
    return false;
  }

  data = doc.toVariant().toMap();

  if(data.isEmpty() || !data.contains(magicIdentifier))
  {
    qCritical() << "Converted config data is invalid or unrecognised";
    return false;
  }

  if(data[magicIdentifier].toUInt() != magicVersion)
  {
    qCritical() << "Converted config data is not the right version";
    return false;
  }

  return true;
}
QList<QString> SingleWeatherParamWidget::getDataFromJson(QString jsonStr){
    QList<QString> valueList;
    QJsonParseError jsonErr;
    QJsonDocument jsonDoc = QJsonDocument::fromJson(jsonStr.toUtf8(), &jsonErr);
    if(jsonErr.error == QJsonParseError::NoError){
        if(!jsonDoc.isEmpty()){
            if(jsonDoc.isObject()){
                QJsonObject jobj = jsonDoc.object();
                QJsonObject::iterator it = jobj.begin();
                while(it != jobj.end()){
                    if(QJsonValue::Array == it.value().type()){
                        QJsonArray array = it.value().toArray();
                        int subArrayCount = array.count();
                        for(int i = 0;i < subArrayCount;i++){
                            QJsonArray subArray = array.at(i).toArray();
                            valueList.append(subArray.at(0).toString());
                            valueList.append(subArray.at(1).toString());
                        }
                    }
                    it++;
                }
            }
        }
    }
    return valueList;
}
Exemple #10
0
bool Storage::getUserLimits (const QString& user, QVariantMap& target)
{
    QString val;
    QFile file;
    QString filename = QString (CLEPSYDRA_WORKING_FOLDER).append(CLEPSYDRA_JSON_USERDATA_FILENAME);
    file.setFileName(filename);
    if ( !file.isReadable() ) {
        //
        return false;
    }
    if (file.open(QIODevice::ReadOnly | QIODevice::Text)==true) {
        val = file.readAll();
        file.close();
    } else {
        qDebug () << filename << "json file not found";
        return false;
    }

    QJsonDocument d = QJsonDocument::fromJson(val.toUtf8());
    if (d.isEmpty()) {
        qDebug () << "Not valid document.";
        return false;
    }

    QJsonObject obj = d.object();
    QJsonValue mapArray = obj.value(user);
    if (mapArray.isUndefined()) {
        qDebug () << "User not found from limits.";
        return false;
    }

    QVariantMap dataC = mapArray.toObject().toVariantMap();
    target = dataC.take(user).toMap();
    return true;
}
void WeatherWorker::requestPingBackWeatherServer()
{
    QNetworkReply *reply = m_networkManager->get(QNetworkRequest(QString("http://service.ubuntukylin.com:8001/weather/pinginformation/")));
    connect(reply, &QNetworkReply::finished, this, [=] () {
        QNetworkReply *m_reply = qobject_cast<QNetworkReply*>(sender());
        int statusCode = m_reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
        if(m_reply->error() != QNetworkReply::NoError || statusCode != 200) {//200 is normal status
            qDebug() << "pingback request error:" << m_reply->error() << ", statusCode=" << statusCode;
            emit responseFailure(statusCode);
            return;
        }

        QByteArray ba = m_reply->readAll();
        m_reply->close();
        m_reply->deleteLater();

        QJsonParseError err;
        QJsonDocument jsonDocument = QJsonDocument::fromJson(ba, &err);
        if (err.error != QJsonParseError::NoError) {// Json type error
            qDebug() << "Json type error";
            return;
        }
        if (jsonDocument.isNull() || jsonDocument.isEmpty()) {
            qDebug() << "Json null or empty!";
            return;
        }

        QJsonObject jsonObject = jsonDocument.object();
        QString notifyInfo = jsonObject.value("info").toString();
        if (!notifyInfo.isEmpty() && !notifyInfo.isNull()) {
            emit requestDiplayServerNotify(notifyInfo);
        }
    });
}
Exemple #12
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;
}
Exemple #13
0
void Job::loadBrains(const QString & brainJson, bool & ok)
{
    QJsonDocument jsonDoc;
    // Check Json validity
    if(ok)
    {
        jsonDoc = QJsonDocument::fromJson(brainJson.toUtf8());
        if(jsonDoc.isEmpty())
        {
            ok = false;
            Util::writeError("the Json for the brain is unvalid");
        }
    }
    // Add brains
    if(ok)
    {
        brains.clear();
        for(int i = 0 ; i < brainCount ; i++)
        {
            brains.push_back(new Brain(this, i+1, jsonDoc.object(),
                                       qrand(), mode));
        }
        //
        copyToBestBrain(brains[0]);
        copyToBestBrainEver(brains[0]);
        mutexBestBrain.lock();
        bestBrain.json = brains[0]->json;
        mutexBestBrain.unlock();
        mutexBestBrainEver.lock();
        bestBrainEver.json = brains[0]->json;
        mutexBestBrainEver.unlock();
    }
}
Exemple #14
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++;
            }
Exemple #15
0
/**
 * @brief TimerWindow::getDataByDate 根据用户ID和日获取数据
 * @param data 存储有数据的QVector<double>对象
 * @param labels 存储有绘图文本的QVector<QString>对象
 * @param u_id 存储有用户id的int对象
 * @param beginDate 开始日期
 * @param endDate 结束日期
 * @return 成功:true,否则:false
 */
bool TimerWindow::getDataByDate(QVector<double> &data, QVector<QString> &labels,
                                int u_id, QDate &beginDate, QDate &endDate)
{
    if(u_id == -1){
        return false;
    }
    data.clear();
    labels.clear();

#ifdef USE_DB_HELPER
    QSqlQuery query;
    QString sql = "SELECT times,date FROM times WHERE user_id = ? AND date >= ? AND date <= ? ORDER BY date ASC";
    QStringList params;
    params.append(QString::number(u_id));
    params.append(beginDate.toString("yyyy-MM-dd"));
    params.append(endDate.toString("yyyy-MM-dd"));
//    qDebug()<<"u_id "<<QString::number(u_id);
//    qDebug()<<"beginDate "<<beginDate.toString("yyyy-MM-dd");
//    qDebug()<<"endDate "<<endDate.toString("yyyy-MM-dd");
//    int result = db.excuteSql(query, sql, params);
//    if(result != db.e_result::excuteSueecss){
//        emit signalSetStatus(tr("Get data error!code:")+QString::number(result),true);
//        return false;
//    }
    while(query.next()){
        data.append(query.value(0).toDouble() / 3600);//times
        labels.append(query.value(1).toString());//date
    }
#else
    //查询用户时间
    int code = -1;
    QString add = addHeader + "Times/getUserTimes";
    //生成post数据
    QJsonObject json;
    json.insert("user_id", QString::number(u_id));
    json.insert("start_date", beginDate.toString("yyyy-MM-dd"));
    json.insert("end_date", endDate.toString("yyyy-MM-dd"));
    QJsonDocument document;
    document.setObject(json);
    QByteArray postData = document.toJson(QJsonDocument::Compact);

    //向服务器发出post请求
    request.setUrl(QUrl(add));
    manager->post(request, postData);
    connect(manager, &QNetworkAccessManager::finished,
            [&](QNetworkReply *reply){
        //解析数据
        QJsonParseError jsonError;
        QJsonDocument jsonDocument = QJsonDocument::fromJson(reply->readAll(), &jsonError);
        if(jsonError.error == QJsonParseError::NoError){
            if(!(jsonDocument.isNull()||jsonDocument.isEmpty())&&jsonDocument.isObject()){
                code = jsonDocument.object().value("code").toInt();
                if(code == 0){//获取成功
                    QJsonArray timeArray = jsonDocument.object().value("times").toArray();
                    foreach (QJsonValue timeValue, timeArray) {
                        labels.append(timeValue.toObject().value("times_date").toString());
                        data.append((timeValue.toObject().value("times_count").toString()).toDouble()/3600);
                    }
                }
Exemple #16
0
void Job::loadProblems(const QString & trainingSetJson, bool & ok)
{
    //
    QJsonDocument json;
    QJsonArray problemsJsonArray;
    problems.clear();
    int minPonyCount = 1;
    int maxPonyCount = 20;
    //
    if(ok)
    {
        minPonyCount = Util::getLineFromConf("minPonyCount", &ok).toInt();
        maxPonyCount = Util::getLineFromConf("maxPonyCount", &ok).toInt();
    }
    if(ok)
    {
        json = QJsonDocument::fromJson(trainingSetJson.toUtf8());
        if(json.isEmpty())
        {
            ok = false;
            Util::writeError("can't load training set");
        }
    }
    if(ok)
    {
        problemsJsonArray = json.object()["problems"].toArray();
    }
    if(ok)
    {

    }
    if(ok)
    {
        for(int i = 0 ; i < problemsJsonArray.size() ; i++)
        {
            problems.push_back(new Problem(
                                   problemsJsonArray[i].toObject(), inputCount));
        }
        for(int i = 0 ; i < problems.size() ; i++)
        {
            if(!(minPonyCount <= problems.at(i)->getCount()
                 && problems.at(i)->getCount() <= maxPonyCount))
            {
                problems.removeAt(i);
                i--;
            }
        }
        Util::write("Working on "
                    + QString::number(problems.size())
                    + " problems after filtering");
    }
}
void SearchSuggester::handleReplyFinished()
{
	if (!m_networkReply)
	{
		return;
	}

	if (m_model)
	{
		m_model->clear();
	}

	m_networkReply->deleteLater();

	if (m_networkReply->size() <= 0)
	{
		m_networkReply = nullptr;

		return;
	}

	const QJsonDocument document(QJsonDocument::fromJson(m_networkReply->readAll()));

	if (!document.isEmpty() && document.isArray() && document.array().count() > 1 && document.array().at(0).toString() == m_query)
	{
		const QJsonArray completionsArray(document.array().at(1).toArray());
		const QJsonArray descriptionsArray(document.array().at(2).toArray());
		const QJsonArray urlsArray(document.array().at(3).toArray());

		m_suggestions.reserve(completionsArray.count());

		for (int i = 0; i < completionsArray.count(); ++i)
		{
			SearchSuggestion suggestion;
			suggestion.completion = completionsArray.at(i).toString();
			suggestion.description = descriptionsArray.at(i).toString();
			suggestion.url = urlsArray.at(i).toString();

			m_suggestions.append(suggestion);

			if (m_model)
			{
				m_model->appendRow(new QStandardItem(suggestion.completion));
			}
		}

		emit suggestionsChanged(m_suggestions);
	}

	m_networkReply = nullptr;
}
void QProcessResultThread::ParseSpResult( QByteArray& byJson, bool& bSuccess, QString& strUUID )
{
    strUUID = "";
    bSuccess = false;
    QJsonParseError jsonError;
    QJsonDocument jsonDoc = QJsonDocument::fromJson( byJson, &jsonError );

    if ( QJsonParseError::NoError != jsonError.error ) {
        qDebug( ) << jsonError.errorString( ) << endl;
        return;
    }

    if ( jsonDoc.isNull( ) || jsonDoc.isEmpty( ) ) {
        return;
    }

    QJsonObject jsonObj = jsonDoc.object( );
    if ( jsonObj.isEmpty( ) ) {
        return;
    }

    QJsonValue jsonVal = jsonObj.value( "Flag" );
    if ( jsonVal.isDouble( ) ) {
        bSuccess = jsonVal.toInt( );
    }

    GetStringValue( strUUID, "UUID",  jsonObj );

    if ( !bSuccess ) {
        return;
    }

    QString strDateTime = "";
    GetStringValue( strDateTime, "DateTime",  jsonObj );

    QString strPlate = "";
    GetStringValue( strPlate, "Plate",  jsonObj );

    QString strMobile = "";
    GetStringValue( strMobile, "MobilePhone",  jsonObj );

    QString strName = "";
    GetStringValue( strName, "Name",  jsonObj );

    if ( strMobile.isEmpty( ) ) {
        return;
    }

    SendShortMessage( strPlate, strDateTime, strName, strMobile );
}
/**
 * @brief DBusPebble::insertTimelinePin
 * @param jsonPin
 * Example usage:
 * dbus-send --session --dest=org.rockwork --type=method_call --print-reply
 *  /org/rockwork/XX_XX_XX_XX_XX_XX org.rockwork.Pebble.insertTimelinePin
 *  string:"$(cat pin.json)"
 * where pin.json is file with raw pin json object
 */
void DBusPebble::insertTimelinePin(const QString &jsonPin)
{
    QJsonParseError jpe;
    QJsonDocument json = QJsonDocument::fromJson(jsonPin.toUtf8(),&jpe);
    if(jpe.error != QJsonParseError::NoError) {
        qWarning() << "Cannot parse JSON Pin:" << jpe.errorString() << jsonPin;
        return;
    }
    if(json.isEmpty() || !json.isObject()) {
        qWarning() << "Empty or flat JSON Pin constructed, ignoring" << jsonPin;
        return;
    }
    m_pebble->insertPin(json.object());
}
bool
BodyMeasureParser::unserialize(QFile &file, QList<BodyMeasure> &data) {

    // open file - truncate contents
    if (!file.open(QFile::ReadOnly)) {
        QMessageBox msgBox;
        msgBox.setIcon(QMessageBox::Critical);
        msgBox.setText(QObject::tr("Problem Reading Body Measurements"));
        msgBox.setInformativeText(QObject::tr("File: %1 cannot be opened for 'Reading'. Please check file properties.").arg(file.fileName()));
        msgBox.exec();
        return false;
    };
    QByteArray jsonFileContent = file.readAll();
    file.close();

    QJsonParseError parseError;
    QJsonDocument document = QJsonDocument::fromJson(jsonFileContent, &parseError);

    if (parseError.error != QJsonParseError::NoError || document.isEmpty() || document.isNull()) {
        QMessageBox msgBox;
        msgBox.setIcon(QMessageBox::Critical);
        msgBox.setText(QObject::tr("Problem Parsing Body Measurements"));
        msgBox.setInformativeText(QObject::tr("File: %1 is not a proper JSON file. Parsing error: %2").arg(file.fileName()).arg(parseError.errorString()));
        msgBox.exec();
        return false;
    }

    data.clear();
    QJsonObject object = document.object();
    QJsonArray measures = object["measures"].toArray();
    for (int i = 0; i < measures.count(); i++) {
        QJsonObject measure = measures.at(i).toObject();
        BodyMeasure m;
        m.when = QDateTime::fromMSecsSinceEpoch(measure["when"].toDouble()*1000);
        m.comment = measure["comment"].toString();
        m.weightkg = measure["weightkg"].toDouble();
        m.fatkg = measure["fatkg"].toDouble();
        m.boneskg = measure["boneskg"].toDouble();
        m.musclekg = measure["musclekg"].toDouble();
        m.leankg = measure["leankg"].toDouble();
        m.fatpercent = measure["fatpercent"].toDouble();
        m.source = static_cast<Measure::MeasureSource>(measure["source"].toInt());
        m.originalSource = measure["originalsource"].toString();
        data.append(m);
    }

    file.close();
    return true;
}
Exemple #21
0
int jsonparser::jsonParse(QJsonDocument jDoc){
    ActiveOptionsContainer* activeOpts = new ActiveOptionsContainer();
    VariableHandler* varHandler = new VariableHandler();
    EnvironmentContainer* envContainer = new EnvironmentContainer(this,varHandler);
    JasonCore* jCore = new JasonCore(this,varHandler,envContainer);

    QVariantMap* totalMap = new QVariantMap();

    connect(varHandler,&VariableHandler::sendProgressTextUpdate,[=](QString message){this->sendProgressTextUpdate(message);});
    connect(jCore,&JasonCore::reportError,[=](int severity,QString message){this->reportError(severity,message);});

    QJsonObject mainTree = jDoc.object();
    if((mainTree.isEmpty())||(jDoc.isEmpty())){
//        sendProgressTextUpdate(tr("No objects found. Will not proceed."));
        return 1;
    }

    QVariantMap *mainMap = new QVariantMap(mainTree.toVariantMap());

    getMap(mainMap,totalMap,activeOpts,jCore);

    QList<QVariant> shellOpts = activeOpts->getOption("shell.properties");
    QProcessEnvironment sysEnv = QProcessEnvironment::systemEnvironment();
    for(QVariant opt : shellOpts){
        QMap<QString,QVariant> optMap = opt.toMap();
        for(QString var : optMap.value("import-env-variables").toString().split(",")){
            varHandler->variableHandle(var,sysEnv.value(var));
        }
        for(QString key : optMap.keys()){
            if(key=="shell")
                shellString = optMap.value(key).toString();
            if(key=="shell.argument")
                shellArgString = optMap.value(key).toString();
        }
    }
    QList<QVariant> jOpts = activeOpts->getOption("global.jason-opts");
    for(QVariant optMap : jOpts){
        QMap<QString,QVariant> opts = optMap.toMap();
        for(QString optkey : opts.keys())
            windowOpts.insert(optkey,opts.value(optkey));
    }

    runQueue = jCore->resolveDependencies(totalMap,activeOpts);

    if(runQueue->getQueue().size()>0)
        b_hasCompleted = true;

    return 0;
}
Exemple #22
0
void TagModel::processData(QJsonDocument data)
{
    if (!data.isArray() || data.isEmpty() || data.isNull()) {
        qWarning() << "No data to process:" << data;
        return;
    }

    beginInsertRows(QModelIndex(), m_tags.size(), m_tags.size() + data.array().size()-1);
    foreach (const QJsonValue obj, data.array())
    {
        Tag t = Tag::fromJson(obj.toObject());
        m_tags.append(t);
    }
    endInsertRows();
}
Exemple #23
0
JsonMessage
JsonMessage::fromTagMessage( const TagMessage & message )
{
    CARTA_ASSERT( message.tag() == TAG || message.tag() == "async" );
    QJsonParseError jsonError;
    QJsonDocument doc = QJsonDocument::fromJson( message.data(), & jsonError );
    if ( doc.isEmpty() || jsonError.error != QJsonParseError::NoError ) {
        qWarning() << "error in parsing received JSON";
        qWarning() << jsonError.errorString();
        qWarning() << "...in...";
        qWarning() << message.data();
        return JsonMessage( QJsonDocument() );
    }
    return JsonMessage( doc );
}
Exemple #24
0
QString Job::getPrediction(QString problemsJson, QString brainJson, bool & ok, Brain::Mode mode)
{
    QJsonDocument json;
    QJsonArray problemsJsonArray;
    QVector<Problem*> problems;
    QString prediction;
    // Brain
    Brain brain(nullptr, 0,
                QJsonDocument::fromJson(brainJson.toUtf8()).object(), qrand(), mode);
    // Problems
    if(ok)
    {
        json = QJsonDocument::fromJson(problemsJson.toUtf8());
        if(json.isEmpty())
        {
            ok = false;
            Util::writeError("can't load problems");
        }
    }
    if(ok)
    {
        problemsJsonArray = json.object()["problems"].toArray();
    }
    if(ok)
    {
        problems.clear();
        for(int i = 0 ; i < problemsJsonArray.size() ; i++)
        {
            problems.push_back(new Problem(problemsJsonArray[i].toObject(),
                                           inputCount));
        }
    }
    // Compute
    if(ok)
    {
        prediction = "{ ";
        for(int i = 0 ; i < problems.size() ; i++)
        {
            if(i)
            {
                prediction += " ; ";
            }
            prediction += (brain.getPrediction(problems[i]->getInputs()));
        }
        prediction += " }";
    }
    return prediction;
}
Exemple #25
0
// This method save all users limists to working dir and file
void Storage::saveLimits(const QVariantMap& map )
{
    QJsonDocument d = QJsonDocument::fromVariant(map);
    if (d.isEmpty())  {
        qDebug () << "empty";
    } else {
        QString filename = CLEPSYDRA_WORKING_FOLDER;
        filename.append(CLEPSYDRA_JSON_USERDATA_FILENAME);
        QFile file(filename);
        if (!file.open(QIODevice::Append | QIODevice::Text))
            return;
        QTextStream out(&file);
        // out << d.toJson();
        file.close();
    }
}
Exemple #26
0
QJsonObject Api::parseJson(QByteArray response)
{
    QJsonDocument jsonDocument = QJsonDocument::fromJson(response);
    QJsonObject jsonObject;
    jsonObject.insert("length", response.length());
    if (jsonDocument.isEmpty() || jsonDocument.isNull()) {
        jsonObject.insert("data", QJsonObject());
    } else {
        QJsonValue value;
        if (jsonDocument.isObject()) {
            value = QJsonValue(jsonDocument.object());
        } else {
            value = QJsonValue(jsonDocument.array());
        }
        jsonObject.insert("content", value);
    }
    return jsonObject;
}
Exemple #27
0
//FIXME: If we load too much contents it will be really slow
void MainWindow::handleContentsResp(QByteArray data)
{
    QJsonParseError jerror;
    QJsonDocument doc = QJsonDocument::fromJson(data,&jerror);
    QString tempTitle,tempContent,tempEntryId,tempHref;
    bool Unread;
    QJsonObject tempObject;
    QJsonArray tempArray;
    int i = 1;
    //qDebug()<<doc;
    if(jerror.error == QJsonParseError::NoError || ! doc.isEmpty()) {
        listModel->clear();
        QJsonObject obj = doc.object();
        QJsonArray arr = obj.value("items").toArray();
        for(int row = 0;row<arr.size();row++)
        {
            QJsonObject obj2 = arr[row].toObject();
            tempTitle = obj2.value("title").toString();
            Unread = obj2.value("unread").toBool();

            if(!tempTitle.isEmpty()) {
                qDebug() << tempTitle;
                tempObject = obj2.value("summary").toObject();
                tempContent = tempObject.value("content").toString();
                tempEntryId = obj2.value("id").toString();

                tempArray = obj2.value("alternate").toArray();
                tempHref = tempArray.at(0).toObject().value("href").toString();

                QStandardItem *contentTitle = new QStandardItem(tempTitle);
                contentTitle->setData(QVariant::fromValue(tempContent),CONTENT);
                contentTitle->setData(QVariant::fromValue(tempEntryId),CONTENT_ENTRY_ID);
                contentTitle->setData(QVariant::fromValue(tempHref),CONTENT_HREF);
                contentTitle->setData(QVariant::fromValue(Unread),CONTENT_UNREAD);

                if(Unread) {
                    alterItemFont(true,contentTitle);
                }
                listModel->appendRow(contentTitle);
            }
        }
    }
}
Exemple #28
0
//------------------------------------------------------------------------------
// Name: operator==
//------------------------------------------------------------------------------
bool QJsonDocument::operator==(const QJsonDocument &other) const {

	if(isArray() && other.isArray()) {
		return array() == other.array();
	}

	if(isObject() && other.isObject()) {
		return object() == other.object();
	}

	if(isEmpty() && other.isEmpty()) {
		return true;
	}

	if(isNull() && other.isNull()) {
		return true;
	}

	return false;
}
Exemple #29
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);
                }
            }
        }
    }
}
Exemple #30
0
void Storage::readDefaultLimits()
{
    QString filename = QString(CLEPSYDRA_CONFIG_FOLDER).append(CLEPSYDRA_JSON_DEFAULTS_FILENAME);
    QFile file;
    QString data=NULL;
    file.setFileName(filename);
    if (file.open(QIODevice::ReadOnly | QIODevice::Text)==true) {
        data = file.readAll();
        file.close();
    } else {
        qDebug () << filename << "json file not found";
        return;
    }
    QJsonDocument d = QJsonDocument::fromJson(data.toUtf8());
    if (d.isEmpty()) {
        qDebug () << "Not valid document.";
        return;
    }
    QJsonObject obj = d.object();
    QVariantMap tempData = obj.toVariantMap();
    m_defaultLimits = tempData.take("default").toMap();
}