Example #1
0
QJsonValue NJson::remove(QJsonValue parentValue, const QString &keysStr) {
    QStringList keys = keysStr.split(".");
    QString key = keys[0];
    int index = key.toInt();

    if (keys.size() == 1) {
        if (parentValue.isArray()) {
            QJsonArray array = parentValue.toArray();
            array.removeAt(index);
            return QJsonValue(array);
        } else {
            QJsonObject object = parentValue.toObject();
            object.remove(key);
            return QJsonValue(object);
        }
    } else {
        keys.pop_front();
        if (parentValue.isArray()) {
            QJsonArray array= parentValue.toArray();
            QJsonValue newValue = remove(QJsonValue(array[index]), keys.join("."));
            if (array.size() <= index) {
                array.insert(index, newValue);
            } else {
                array[index] = newValue;
            }
            return QJsonValue(array);
        } else {
            QJsonObject object = parentValue.toObject();
            object[key] = remove(QJsonValue(parentValue.toObject()[key]), keys.join("."));
            return QJsonValue(object);
        }
    }
}
Example #2
0
static bool readGpuFeatures(const QOpenGLConfig::Gpu &gpu,
                            const QString &osName,
                            const QVersionNumber &kernelVersion,
                            const QJsonDocument &doc,
                            QSet<QString> *result,
                            QString *errorMessage)
{
    result->clear();
    errorMessage->clear();
    const QJsonValue entriesV = doc.object().value(QStringLiteral("entries"));
    if (!entriesV.isArray()) {
        *errorMessage = QLatin1String("No entries read.");
        return false;
    }

    const QJsonArray entriesA = entriesV.toArray();
    for (JsonArrayConstIt eit = entriesA.constBegin(), ecend = entriesA.constEnd(); eit != ecend; ++eit) {
        if (eit->isObject()) {
            const QJsonObject object = eit->toObject();
            if (matches(object, osName, kernelVersion, gpu)) {
                const QJsonValue featuresListV = object.value(featuresKey());
                if (featuresListV.isArray()) {
                    const QJsonArray featuresListA = featuresListV.toArray();
                    for (JsonArrayConstIt fit = featuresListA.constBegin(), fcend = featuresListA.constEnd(); fit != fcend; ++fit)
                        result->insert(fit->toString());
                }
            }
        }
    }
    return true;
}
Example #3
0
Schema *MessageFacade::defineSchema(QJsonObject *root, ControllerNode *pControllerNode){
    QJsonValue jsonValue = root->value(SCHEMA);
    if (!jsonValue.isUndefined() && jsonValue.isObject()){
        QJsonObject schema= jsonValue.toObject();
        QJsonValue strings =schema.value(STRING_TYPE);
        QJsonValue ints =schema.value(INT_TYPE);
        QJsonValue primaryKey = schema.value(PRIMARY_KEY);
        if (!strings.isUndefined() && strings.isArray() &&!ints.isUndefined()
                && ints.isArray() && !primaryKey.isUndefined() && primaryKey.isObject()){
            QJsonArray columnaStringType = strings.toArray();
            QJsonArray columnaIntsType = ints.toArray();
            QJsonObject columnaPrimaryKey = primaryKey.toObject();
            bool success = true;
            QJsonObject currentObject;
            for (int x = 0; x < columnaStringType.size(); x++){
                currentObject =columnaStringType.at(x).toObject();
                success = success && currentObject.value(currentObject.keys().at(0)).isDouble();
            }
            for (int x = 0; x < columnaIntsType.size(); x++)success = success && columnaIntsType.at(x).isString();
            QString primaryKeyName =columnaPrimaryKey.keys().at(0);
            qDebug() << "validando....";
            if (success && validatingPrimaryKey(primaryKeyName,&columnaPrimaryKey)){
                qDebug() << "validacion completa el JSON es valido";
                Schema *dataSchema = StorageblockFacade::getInstance()->createSchema(1+columnaIntsType.size()+columnaStringType.size());
                unsigned int sizeOfBytes = 0;
                QJsonObject primaryKeyScheme;
                primaryKeyScheme = columnaPrimaryKey.value(primaryKeyName).toObject();
                if (primaryKeyName.compare(INT_TYPE) == 0)sizeOfBytes = sizeof(int);
                else sizeOfBytes = primaryKeyScheme.value(primaryKeyScheme.keys().at(0)).toInt()*sizeof(char);
                dataSchema->setSchemaOverColumn(0,primaryKeyScheme.keys().at(0).toStdString(),sizeOfBytes,
                (primaryKeyName.compare(INT_TYPE) == 0)?SchemeRow::INT_TYPE:SchemeRow::STRING_TYPE);
                int place= 1;
                for (int x = 0; x < columnaIntsType.size(); x++){
                    currentObject =columnaIntsType.at(x).toObject();
                    dataSchema->setSchemaOverColumn(x+(place++),columnaIntsType.at(x).toString().toStdString(),sizeof(int),SchemeRow::INT_TYPE);
                }
                for (int x = 0; x < columnaStringType.size(); x++){
                    currentObject =columnaStringType.at(x).toObject();
                    currentObject.value(currentObject.keys().at(0)).toString();
                    dataSchema->setSchemaOverColumn(x+place,currentObject.keys().at(0).toStdString(),sizeof(char)*currentObject.value(currentObject.keys().at(0)).toInt(),SchemeRow::STRING_TYPE);
                }
                SchemeRow row;
                QString type;
                for(int x = 0; x < dataSchema->getLenght();x++){
                    row = (*dataSchema)[x];
                    type= (row.getTypeRestrictor()==SchemeRow::INT_TYPE)?"int    ":"string";
                    qDebug() << "| type: "<< type<< "\t| name: " << row.toString().c_str() << "\t\t| size: \t"<< row.getByteSize();
                }
                return dataSchema;
            }
        }
    }
    return 0;
}
void jsonObjectToImportResult(const QJsonObject &object, ImportDataResult &result) {
    if (object.contains(SOURCEFILE)) {
        result.FilePath = object.value(SOURCEFILE).toString();
    }

    if (object.contains(TITLE)) {
        result.Title = object.value(TITLE).toString();
    } else if (object.contains(OBJECTNAME)) {
        result.Title = object.value(OBJECTNAME).toString();
    }

    if (object.contains(DESCRIPTION)) {
        result.Description = object.value(DESCRIPTION).toString();
    } else if (object.contains(CAPTIONABSTRACT)) {
        result.Description = object.value(CAPTIONABSTRACT).toString();
    } else if (object.contains(IMAGEDESCRIPTION)) {
        result.Description = object.value(IMAGEDESCRIPTION).toString();
    }

    if (object.contains(DATETAKEN)) {
        QString dateTime = object.value(DATETAKEN).toString();
        result.DateTimeOriginal = QDateTime::fromString(dateTime, Qt::ISODate);
    }

    bool keywordsSet = false;

    if (object.contains(KEYWORDS)) {
        QJsonValue keywords = object.value(KEYWORDS);
        if (keywords.isArray()) {
            parseJsonKeywords(keywords.toArray(), result);
            keywordsSet = true;
        } else {
            LOG_WARNING << "Keywords object in json is not array";
            QString keywordsStr = object.value(KEYWORDS).toString().trimmed();
            keywordsSet = parseStringKeywords(keywordsStr, result);
        }
    }

    if (!keywordsSet && object.contains(SUBJECT)) {
        QJsonValue subject = object.value(SUBJECT);
        if (subject.isArray()) {
            parseJsonKeywords(subject.toArray(), result);
        } else {
            QString keywordsStr = object.value(SUBJECT).toString().trimmed();
            parseStringKeywords(keywordsStr, result);
        }
    }
}
Example #5
0
JsonArray JsonObject::array(const QString& key) const {
    checkContains(key);
    QJsonValue value = o.value(key);
    if ( ! value.isArray())
        wrongType("array", key);
    return JsonArray(value.toArray());
}
SupportLibraryLoader::SupportLibraryLoader(const QFileInfo &configPath) : _configLocation(configPath)
{
    if ( !configPath.exists())
        return;

    QString operatingSystem = OSHelper::operatingSystem();
    QString path = configPath.absoluteFilePath();
    QFile file;
    file.setFileName(path);
    if (file.open(QIODevice::ReadOnly)) {
        QString settings = file.readAll();
        QJsonDocument doc = QJsonDocument::fromJson(settings.toUtf8());
        if ( !doc.isNull()){
            QJsonObject obj = doc.object();
            QJsonValue osses = obj.value("OperatingSystem");
            if ( osses.isArray()){
                QJsonArray arrOsses = osses.toArray();
                for(auto jvalue : arrOsses) {
                    QJsonObject os = jvalue.toObject();
                    if ( os["name"].toString() == operatingSystem){
                        QJsonArray libraries = os["libraries"].toArray();
                        for(auto oslibsvalue : libraries){
                            QJsonObject osprops = oslibsvalue.toObject();
                            _order[osprops["order"].toDouble()] = osprops["library"].toString();
                        }
                        return;

                    }
                }
            }
        }
    }
}
static Nuria::JsonMetaObjectReader::Error parseFieldObject (const QString &name, const QJsonObject &field,
							    Nuria::RuntimeMetaObject *metaObject) {
	using namespace Nuria;
	
	QJsonValue annotationsValue = field.value (QStringLiteral("annotations"));
	QJsonValue readOnlyValue = field.value (QStringLiteral("readOnly"));
	QJsonValue typeValue = field.value (QStringLiteral("type"));
	
	// Type check
	if (!annotationsValue.isArray ()) return JsonMetaObjectReader::AnnotationsIsNotAnArray;
	if (!readOnlyValue.isBool ()) return JsonMetaObjectReader::FieldReadOnlyIsNotABoolean;
	if (!typeValue.isString ()) return JsonMetaObjectReader::FieldTypeIsNotAString;
	
	// Parse annotations
	JsonMetaObjectReader::Error error;
	
	RuntimeMetaObject::AnnotationMap annotations;
	error = parseAnnotationsArray (annotationsValue.toArray (), annotations);
	if (error != JsonMetaObjectReader::NoError) return error;
	
	// Store and done.
	QByteArray typeName = typeValue.toString ().toLatin1 ();
	
	if (readOnlyValue.toBool ()) {
		metaObject->addField (name.toLatin1 (), typeName, annotations, invalidGetter);
	} else {
		metaObject->addField (name.toLatin1 (), typeName, annotations, invalidGetter, invalidSetter);
	}
	
	return JsonMetaObjectReader::NoError;
}
static Nuria::JsonMetaObjectReader::Error parseEnumObject (const QString &name, const QJsonObject &enumObj,
							   Nuria::RuntimeMetaObject *metaObject) {
	using namespace Nuria;
	
	QJsonValue annotationsValue = enumObj.value (QStringLiteral("annotations"));
	QJsonValue valuesValue = enumObj.value (QStringLiteral("values"));
	
	// Type check
	if (!annotationsValue.isArray ()) return JsonMetaObjectReader::AnnotationsIsNotAnArray;
	if (!valuesValue.isObject ()) return JsonMetaObjectReader::EnumValuesIsNotAnObject;
	
	// Parse annotations
	JsonMetaObjectReader::Error error;
	
	RuntimeMetaObject::AnnotationMap annotations;
	error = parseAnnotationsArray (annotationsValue.toArray (), annotations);
	if (error != JsonMetaObjectReader::NoError) return error;
	
	// Parse values
	QMap< QByteArray, int > keyValueMap;
	error = parseEnumValues (valuesValue.toObject (), keyValueMap);
	if (error != JsonMetaObjectReader::NoError) return error;
	
	// Store and done.
	metaObject->addEnum (name.toLatin1 (), annotations, keyValueMap);
	return JsonMetaObjectReader::NoError;
	
}
Example #9
0
bool QJsonValueProto::isArray() const
{
  QJsonValue *item = qscriptvalue_cast<QJsonValue*>(thisObject());
  if (item)
    return item->isArray();
  return false;
}
Example #10
0
void Client::_askForCardOrUseCard(const QJsonValue &cardUsageData){
	Q_ASSERT(cardUsageData.isArray());
	QJsonArray cardUsage = cardUsageData.toArray();
	Q_ASSERT(BP::isStringArray(cardUsage, 0, 1));
	card_pattern = cardUsage[0].toString();
	QStringList texts = cardUsage[1].toString().split(":");

	if(texts.isEmpty()){
		return;
	}else
		setPromptList(texts);

	if(card_pattern.endsWith("!"))
		is_discard_action_refusable = false;
	else
		is_discard_action_refusable = true;

	QRegExp rx("^@@?(\\w+)(-card)?$");
	if(rx.exactMatch(card_pattern)){
		QString skill_name = rx.capturedTexts().at(1);
		const Skill *skill = Bang->getSkill(skill_name);
		if(skill){
			QString text = prompt_doc->toHtml();
			text.append(tr("<br/> <b>Notice</b>: %1<br/>").arg(skill->getDescription()));
			prompt_doc->setHtml(text);
		}
	}

	setStatus(Responsing);
}
Example #11
0
bool Client::processServerRequest(const BP::Packet &packet){
	setStatus(Client::NotActive);

	last_server_serial = packet.global_serial;

	BP::CommandType command = packet.getCommandType();
	QJsonValue msg = packet.getMessageBody();

	BP::Countdown countdown;
	countdown.current = 0;

	bool use_default = !msg.isArray();
	if(!use_default){
		QJsonArray arr = msg.toArray();
		if(arr.size() <= 1 || !countdown.tryParse(arr.first())){
			use_default = true;
		}
	}
	if(use_default){
		countdown.type = BP::Countdown::UseDefault;
		countdown.max = ServerInfo.getCommandTimeout(command, BP::ClientInstance);
	}

	setCountdown(countdown);

	Callback callback = interactions[command];
	if(!callback){
		return false;
	}
	(this->*callback)(msg);

	return true;
}
Example #12
0
void Client::gameOver(const QJsonValue &argdata){
	if(!argdata.isArray()) return;
	QJsonArray arg = argdata.toArray();
	is_game_over = true;
	setStatus(Client::NotActive);
	QString winner = arg[0].toString();
	QStringList roles;
	BP::tryParse(arg[1], roles);

	Q_ASSERT(roles.length() == players.length());

	for(int i = 0; i < roles.length(); i++){
		QString name = players.at(i)->objectName();
		getPlayer(name)->setRole(roles.at(i));
	}

	if(winner == "."){
		emit standoff();
		return;
	}

	QSet<QString> winners = winner.split("+").toSet();
	foreach(const ClientPlayer *player, players){
		QString role = player->getRole();
		bool win = winners.contains(player->objectName()) || winners.contains(role);

		ClientPlayer *p = const_cast<ClientPlayer *>(player);
		p->setProperty("win", win);
	}
Example #13
0
//==== SYSCACHE ====
RestOutputStruct::ExitCode WebSocket::EvaluateSyscacheRequest(const QJsonValue in_args, QJsonObject *out){
  //syscache only needs a list of sub-commands at the moment (might change later)
  QStringList in_req;

  //Parse the input arguments structure
  if(in_args.isArray()){ in_req = JsonArrayToStringList(in_args.toArray()); }
  else if(in_args.isObject()){
    QStringList keys = in_args.toObject().keys();
    for(int i=0; i<keys.length(); i++){ in_req << JsonValueToString(in_args.toObject().value(keys[i])); }
  }else{ return RestOutputStruct::BADREQUEST; }

  //Run the Request (should be one value for each in_req)
  QStringList values = SysCacheClient::parseInputs(in_req);
  while(values.length() < in_req.length()){ values << "[ERROR]"; } //ensure lists are same length

  //Format the result
  for(int i=0; i<values.length(); i++){
      if(values[i].contains(SCLISTDELIM)){
	  //This is an array of values from syscache
	  QStringList vals = values[i].split(SCLISTDELIM);
	  vals.removeAll("");
	  QJsonArray arr;
	    for(int j=0; j<vals.length(); j++){ arr.append(vals[j]); }
	    out->insert(in_req[i],arr);
      }else{
          out->insert(in_req[i],values[i]);
      }
    }
  //Return Success
  return RestOutputStruct::OK;
}
Example #14
0
void AppModel::handleForecastNetworkData(QObject *replyObj)
{
    QNetworkReply *networkReply = qobject_cast<QNetworkReply*>(replyObj);
    if (!networkReply)
        return;

    if (!networkReply->error()) {
        QJsonDocument document = QJsonDocument::fromJson(networkReply->readAll());

        QJsonObject jo;
        QJsonValue jv;
        QJsonObject root = document.object();
        jv = root.value(QStringLiteral("list"));
        if (!jv.isArray())
            qWarning() << "Invalid forecast object";
        QJsonArray ja = jv.toArray();
        //we need 4 days of forecast -> first entry is today
        if (ja.count() != 5)
            qWarning() << "Invalid forecast object";

        QString data;
        for (int i = 1; i<ja.count(); i++) {
            WeatherData *forecastEntry = new WeatherData();

            //min/max temperature
            QJsonObject subtree = ja.at(i).toObject();
            jo = subtree.value(QStringLiteral("temp")).toObject();
            jv = jo.value(QStringLiteral("min"));
            data.clear();
            data += niceTemperatureString(jv.toDouble());
            data += QChar('/');
            jv = jo.value(QStringLiteral("max"));
            data += niceTemperatureString(jv.toDouble());
            forecastEntry->setTemperature(data);

            //get date
            jv = subtree.value(QStringLiteral("dt"));
            QDateTime dt = QDateTime::fromMSecsSinceEpoch((qint64)jv.toDouble()*1000);
            forecastEntry->setDayOfWeek(dt.date().toString(QStringLiteral("ddd")));

            //get icon
            QJsonArray weatherArray = subtree.value(QStringLiteral("weather")).toArray();
            jo = weatherArray.at(0).toObject();
            forecastEntry->setWeatherIcon(jo.value(QStringLiteral("icon")).toString());

            //get description
            forecastEntry->setWeatherDescription(jo.value(QStringLiteral("description")).toString());

            d->forecast.append(forecastEntry);
        }

        if (!(d->ready)) {
            d->ready = true;
            emit readyChanged();
        }

        emit weatherChanged();
    }
    networkReply->deleteLater();
}
Example #15
0
void GeoNamesWeatherService::parseFile( const QByteArray& file )
{
    QJsonDocument jsonDoc = QJsonDocument::fromJson(file);
    QJsonValue weatherObservationsValue = jsonDoc.object().value(QStringLiteral("weatherObservations"));

    // Parse if any result exists
    QList<AbstractDataPluginItem*> items;
    if (weatherObservationsValue.isArray()) {
        // Add items to the list
        QJsonArray weatherObservationsArray = weatherObservationsValue.toArray();
        for (int index = 0; index < weatherObservationsArray.size(); ++index) {
            QJsonObject weatherObservationObject = weatherObservationsArray[index].toObject();

            AbstractDataPluginItem* item = parse(weatherObservationObject);
            if ( item ) {
                items << item;
            }
        }
    } else {
        QJsonValue weatherObservationValue = jsonDoc.object().value(QStringLiteral("weatherObservation"));
        QJsonObject weatherObservationObject = weatherObservationValue.toObject();
        AbstractDataPluginItem* item = parse(weatherObservationObject);
        if ( item ) {
            items << item;
        }
    }

    emit createdItems( items );
}
Example #16
0
void LocationManager::errorDataReceived(QNetworkReply& errorReply) {
    
    if (errorReply.header(QNetworkRequest::ContentTypeHeader).toString().startsWith("application/json")) {
        // we have some JSON error data we can parse for our error message
        QJsonDocument responseJson = QJsonDocument::fromJson(errorReply.readAll());
        
        QJsonObject dataObject = responseJson.object()["data"].toObject();
        
        qDebug() << dataObject;
        
        QString errorString = "There was a problem creating that location.\n";
        
        // construct the error string from the returned attribute errors
        foreach(const QString& key, dataObject.keys()) {
            errorString += "\n\u2022 " + key + " - ";
            
            QJsonValue keyedErrorValue = dataObject[key];
           
            if (keyedErrorValue.isArray()) {
                foreach(const QJsonValue& attributeErrorValue, keyedErrorValue.toArray()) {
                    errorString += attributeErrorValue.toString() + ", ";
                }
                
                // remove the trailing comma at end of error list
                errorString.remove(errorString.length() - 2, 2);
            } else if (keyedErrorValue.isString()) {
Example #17
0
QStringList JSONBreakableMarshal::toStringList(const QJsonValue& jsonValue, const QString& keypath) {
    // setup the string list that will hold our result
    QStringList result;

    // figure out what type of value this is so we know how to act on it
    if (jsonValue.isObject()) {

        QJsonObject jsonObject = jsonValue.toObject();
        
        // enumerate the keys of the QJsonObject
        foreach(const QString& key, jsonObject.keys()) {
            QJsonValue childValue = jsonObject[key];

            // setup the keypath for this key
            QString valueKeypath = (keypath.isEmpty() ? "" : keypath + ".") + key;
            
            if (childValue.isObject() || childValue.isArray()) {
                // recursion is required since the value is a QJsonObject or QJsonArray
                result << toStringList(childValue, valueKeypath);
            } else {
                // no recursion required, call our toString method to get the string representation
                // append the QStringList resulting from that to our QStringList
                result << toString(childValue, valueKeypath);  
            }
        } 
    } else if (jsonValue.isArray()) {
Example #18
0
StringArray JsonObjectQt::GetNamedStringArray(const std::string& name)
{
  QJsonObject jo = this->impl_.toObject();

  if (!jo.contains(name.c_str()))
  {
    Logger::Warning(
      "JsonObjectQt::GetNamedStringArray: Can't find the key named '%s'",
      name.c_str());
    return std::vector<std::string>();
  }

  QJsonValue val = jo[name.c_str()];

  if (!val.isArray())
  {
    throw exceptions::RMSInvalidArgumentException("the value is not an array");
  }

  StringArray list;
  QJsonArray  arr = val.toArray();

  for (int i = 0; i < arr.size(); ++i)
  {
    QJsonValue val = arr[i];
    list.push_back(val.toString().toStdString());
  }

  return list;
}
QMap<QString, BlockOption> QMap_QString_BlockOption_fromJson(QJsonValue node, bool *ok) {
    bool success = true;
    bool callSuccess;
    QMap<QString, BlockOption> obj;
    if (!node.isArray()) {
        success = false;
    }
    QJsonArray nodeArr = node.toArray();
    for (auto i = nodeArr.constBegin(); i != nodeArr.constEnd(); i++) {
        QJsonObject item = (*i).toObject();
        QJsonValue keyVal = item["key"];
        if (!keyVal.isString()) {
            success = false;
        }
        QString key = keyVal.toString();
        BlockOption value = BlockOption_fromJson(item["value"], &callSuccess);
        if (!callSuccess) {
            success = false;
        }
        obj.insert(key, value);
    }
    if (ok) {
        *ok = success;
    }
    return obj;
}
Example #20
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());
}
Example #21
0
void Client::askForCard(const QJsonValue &data){
	if(!data.isArray()) return;

	QJsonArray req = data.toArray();
	if(req.size() == 0) return;
	m_isUseCard = req[0].toString().startsWith("@@");
	_askForCardOrUseCard(req);
}
Example #22
0
QString errorStringFromAPIObject(const QJsonValue& apiObject) {
    if (apiObject.isArray()) {
        return apiObject.toArray()[0].toString();
    } else if (apiObject.isString()) {
        return apiObject.toString();
    } else {
        return "is invalid";
    }
}
QStringList SshSettingsFactory::hosts(QString entry)
{
    QJsonValue value = this->m_config->value(this->m_context).toObject().value(entry).toObject().value("ssh").toObject().value("hosts");

    if(!value.isArray()) {
        return this->hosts();
    }

    return this->m_config->toStringList(value.toArray());
}
void GetManyTestCase::onTextMessageReceived(QString message)
{
    DEBUG(m_testClientId,"Message received");
    TRACE(m_testClientId,message);

    QJsonParseError parseError;
    QJsonDocument  jsonDocument;
    QJsonObject    jsonObject;

    jsonDocument = QJsonDocument::fromJson(message.toUtf8(),&parseError);
    jsonObject = jsonDocument.object();
    if (parseError.error == QJsonParseError::NoError)
    {
        QString actionString =jsonObject["action"].toString();

        if (actionString != "get")
        {
            WARNING(m_testClientId,"Received incorrect action.");
            emit finished(false);
            return;
        }

        QString requestId = jsonObject["requestId"].toString();
        QJsonObject errorObject = jsonObject["error"].toObject();
        if (!errorObject.empty())
        {
            WARNING(m_testClientId,"Get Many failed.");
            QString errorMessage = errorObject["message"].toString();
            DEBUG(m_testClientId,QString("Error! Request ID : %1, Message : %2").arg(requestId, errorMessage));
            emit finished(false);
            return;
        }

        QJsonValue receivedValue = jsonObject.value("value");
        if(receivedValue.isUndefined())
        {
            WARNING(m_testClientId,"Get response doesn't contain any values.");
            emit finished(false);
            return;
        }
        else if(!receivedValue.isArray())
        {
            WARNING(m_testClientId,"Get response doesn't contain a value array as it should.");
            emit finished(false);
            return;
        }

        INFO(m_testClientId,"Successfully got many values.");
        emit  finished(true);
    }
    else
    {
        emit  finished(false);
    }
}
Example #25
0
T glmFromJson(const QJsonValue& json) {
    T result;
    if (json.isArray()) {
        QJsonArray array = json.toArray();
        auto length = std::min(array.size(), result.length());
        for (auto i = 0; i < length; ++i) {
            result[i] = (float)array[i].toDouble();
        }
    }
    return result;
}
Example #26
0
QJsonArray Utils::getJsonArray(const QString &key, const QJsonObject &obj)
{
    QJsonArray array;
    if (obj.contains(key)) {
        QJsonValue value = obj.value(key);
        if (value.isArray()) {
            array = value.toArray();
        }
    }
    return array;
}
Example #27
0
    bool mergeJsonObjects (const QJsonObject &objectMergeFrom, QJsonObject &objectMergeTo, CompareValuesJson &comparer) {
        LOG_DEBUG << "#";

        QStringList keysMergeFrom = objectMergeFrom.keys();
        int keysSize = keysMergeFrom.size();

        bool anyError = false;

        for (int i = 0; i < keysSize; i++) {
            const QString &keyFrom = keysMergeFrom.at(i);

            if (objectMergeTo.contains(keyFrom)) {
                QJsonValue valueTo = objectMergeTo[keyFrom];
                QJsonValue valueFrom = objectMergeFrom[keyFrom];

                if (valueTo.type() != valueFrom.type()) {
                    LOG_WARNING << "Types of Json Values do not match at key:" << keyFrom;
                    continue;
                }

                if (valueTo.isObject()) {
                    QJsonObject objectTo = valueTo.toObject();
                    QJsonObject objectFrom = valueFrom.toObject();

                    if (mergeJsonObjects(objectFrom, objectTo, comparer)) {
                        valueTo = objectTo;
                    } else {
                        anyError = true;
                        break;
                    }
                } else if (valueTo.isArray()) {
                    QJsonArray arrayTo = valueTo.toArray();
                    QJsonArray arrayFrom = valueFrom.toArray();

                    if (mergeJsonArrays(arrayFrom, arrayTo, comparer)) {
                        valueTo = arrayTo;
                    } else {
                        anyError = true;
                        break;
                    }
                } else {
                    valueTo = valueFrom;
                }

                objectMergeTo[keyFrom] = valueTo;

            } else {
                objectMergeTo[keyFrom] = objectMergeFrom[keyFrom]; // insert if doesn't contain
            }
        }

        bool mergeResult = !anyError;
        return mergeResult;
    }
Example #28
0
bool BlockInfoData::readMetaData(const QJsonObject &metaData)
{
    QJsonValue value;
    value = metaData.value("IID");
    if (!value.isString()) {
        qWarning() << "Not a plugin (no IID found)";
        return false;
    }

    value = metaData.value("MetaData");
    if (!value.isObject()) {
        qWarning() << "Plugin meta data not found";
        return false;
    }
    QJsonObject pluginInfo = value.toObject();

    value = pluginInfo.value("provides");
    if (!value.isString()) {
        qWarning() << "Plugin doesn't provide anything (check \"provides\" field)";
        return false;
    }
    provides = BlockVersion(value.toString());

    if (!provides.isValid()) {
        qWarning() << "Plugin provides invalid version";
        return false;
    }

    value = pluginInfo.value("provides_compat");
    if (!value.isString()) {
        qWarning() << "Plugin doesn't provide compatibility version "
                      "(check \"provides_compat\" field)";
        return false;
    }
    provides_compat = BlockVersion(value.toString());

    if (!provides_compat.isValid()) {
        qWarning() << "Plugin provides invalid version";
        return false;
    }

    value = pluginInfo.value("needs");
    if (value.isArray()) {
        QJsonArray deps = value.toArray();
        foreach(const QJsonValue &d, deps) {
            if (d.isString()) {
                BlockVersion version(d.toString());
                if (version.isValid())
                    needs.append(version);
            }
        }
    }
bool DataFormat::setFormatInfo(const QString& path, const QString connector) {
    QFile file;
    file.setFileName(path);
    if (file.open(QIODevice::ReadOnly)) {
        QString settings = file.readAll();
        QJsonDocument doc = QJsonDocument::fromJson(settings.toUtf8());
        if ( !doc.isNull()){
            InternalDatabaseConnection sqlPublic;
            QJsonObject obj = doc.object();
            QJsonValue formats = obj.value("Formats");
            if ( formats.isArray()){
                InternalDatabaseConnection db("BEGIN TRANSACTION");
                QJsonArray arrFormats = formats.toArray();
                for(auto iter = arrFormats.begin(); iter != arrFormats.end(); ++iter) {
                    auto jsonValue  = *iter;
                    if ( jsonValue.isObject()) {
                        QJsonObject objv = jsonValue.toObject();
                        QString code = objv.value("code").toString(sUNDEF);
                        QString name = objv.value("name").toString(sUNDEF);
                        QString desc = objv.value("description").toString(sUNDEF);
                        QString type = objv.value("type").toString(sUNDEF);
                        QString ext = objv.value("extension").toString(sUNDEF);
                        QString datatp = objv.value("datatypes").toString(sUNDEF);
                        QString fileparts = objv.value("parts").toString(sUNDEF);
                        quint64 ilwtype = itUNKNOWN;
                        QStringList parts = datatp.split(",");
                        for(QString tp : parts)
                            ilwtype |= IlwisObject::name2Type(tp);
                        QString rw = objv.value("readwrite").toString("r");
                        QString extt = objv.value("extendedtype").toString(sUNDEF);
                        quint64 exttypes = itUNKNOWN;
                        parts = extt.split(",");
                        for(QString tp : parts)
                            exttypes |= IlwisObject::name2Type(tp);

                        QString parms = QString("'%1','%2','%3','%4','%5',%6,'%7','%8',%9,'%10'").arg(code.toLower(),name,desc, ext,type).arg(ilwtype).arg(connector).arg(rw).arg(exttypes).arg(fileparts);
                        QString stmt = QString("INSERT INTO dataformats VALUES(%1)").arg(parms);
                        bool ok = sqlPublic.exec(stmt);
                        if (!ok) {
                            return kernel()->issues()->logSql(sqlPublic.lastError());
                        }
                    }

                }
                db.exec("COMMIT TRANSACTION");
                return true;
            }
        }

    }
    return false;
}
Example #30
0
bool JsonDbObject::isAncestorOf(const QJsonArray &history, const int updateCount, const QString &hash) const
{
    if (updateCount < 1 || history.size() < updateCount)
        return false;

    QJsonValue knownHashes = history.at(updateCount - 1);
    if (knownHashes.isString())
        return knownHashes.toString() == hash;
    else if (knownHashes.isArray())
        return knownHashes.toArray().contains(hash);
    else
        return false;
}