//! Called when a REST request for fetching object version information becomes available. void ObjectCore::versionAvailable( QNetworkReply* reply, bool latest ) { // Process only if there was no error. if( reply->error() != QNetworkReply::NoError ) { qDebug( "Error when sending the property values." ); return; } // Parse the returned JSON. QByteArray replyContent = reply->readAll(); QJsonDocument result = QJsonDocument::fromJson( replyContent ); QJsonObject extendedVersion = result.object(); // Populate the cache. bool latestKnownVersionChanged = false; { // Construct properties array and then remove it to rever the extended version to standard object version. QJsonArray properties = extendedVersion[ "Properties" ].toArray(); extendedVersion.remove( "Properties" ); QJsonArray propertiesForDisplay; if( extendedVersion.contains( "PropertiesForDisplay" ) ) { propertiesForDisplay = extendedVersion[ "PropertiesForDisplay" ].toArray(); extendedVersion.remove( "PropertiesForDisplay" ); } QJsonObject objverObject = extendedVersion[ "ObjVer" ].toObject(); int version = objverObject[ "Version" ].toDouble(); // Store the new object. QMutexLocker lock( &m_mtx ); // Was the latest known version changed? if( latest ) { // Did the latest known version change? if( version != m_latestKnownVersion ) latestKnownVersionChanged = true; m_latestKnownVersion = version; } // end if // Create and cache the version core. MFiles::ObjVer objver( m_id, version ); ObjectVersionCore* versionCore = new ObjectVersionCore( this, objver ); versionCore->setProperties( properties ); if( ! propertiesForDisplay.empty() ) versionCore->setPropertiesForDisplay( propertiesForDisplay ); else versionCore->requestPropertiesForDisplay(); m_versions.insert( objver.version(), versionCore ); } // end lock // Was latest version changed? if( latestKnownVersionChanged ) emit latestVersionChanged(); }
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); } } }
void collectmailsesb::__testjson() { QJsonDocument doc; QJsonObject data; data.insert("data", QJsonValue(QJsonObject())); { //QJsonObject esb; //esb.insert("[ESB]", QJsonValue(QJsonArray())); QJsonArray a; a.append(QJsonValue(QString("ae"))); data.insert("data2", QJsonValue(a)); QJsonArray aa = data.value("data2").toArray(); aa.append(QJsonValue(QString("aee"))); data.remove("data2"); data.insert("data2", QJsonValue(aa)); //doc.object().value("data").toObject().insert("[ESB]", QJsonValue(a)); //QJsonObject data2; //data2.insert("data2", QJsonValue(QJsonObject())); //data.insert("data2", QJsonValue(QString("val2"))); } doc.setObject(data); QMessageBox::warning(0, "__testjson", doc.toJson()); /* QFile file("c:/temp/test.json"); file.open(QFile::WriteOnly | QFile::Text | QFile::Truncate); file.write(doc.toJson()); file.close(); */ }
void MessageTest::parseErrorHandling() { // If the message isn't raw, we should return true -- nothing to parse! QVERIFY(Message(Message::Request).parse()); QVERIFY(Message(Message::Notification).parse()); QVERIFY(Message(Message::Response).parse()); QVERIFY(Message(Message::Error).parse()); QVERIFY(Message(Message::Invalid).parse()); // Construct a valid object and verify that it parses. QJsonObject validObj; validObj.insert("jsonrpc", QLatin1String("2.0")); validObj.insert("id", QLatin1String("5")); validObj.insert("method", QLatin1String("testMethod")); QVERIFY(Message(validObj).parse()); // This will be our test object. QJsonObject obj; // Must contain 'jsonrpc' member obj = validObj; obj.remove("jsonrpc"); QVERIFY(!Message(obj).parse()); // 'jsonrpc' member must be a string obj = validObj; obj["jsonrpc"] = 2.0; QVERIFY(!Message(obj).parse()); // 'jsonrpc' member must be exactly "2.0" obj = validObj; obj["jsonrpc"] = QString("1.0 + 1.0"); QVERIFY(!Message(obj).parse()); // Must have either id or method obj = validObj; obj.remove("id"); obj.remove("method"); QVERIFY(!Message(obj).parse()); // If present, method must be a string obj = validObj; obj["method"] = true; QVERIFY(!Message(obj).parse()); }
QJsonObject SyncEngine::journalStateForVersion(QJsonObject journal_state, int maximum_version) { foreach (const QString &key, journal_state.keys()) { if (key.split(':').value(1).toInt() > maximum_version) { journal_state.remove(key); } } return journal_state; }
void JensonTests::testSerialization() { // // Test serialization // Testobject p(2, 3); p.setOptionalStr("This is a Testobject"); p.nestedObj()->setSomeString("This is a nested object"); QJsonObject obj = jenson::JenSON::serialize(&p); // // Test deserialization // sptr<QObject> o = jenson::JenSON::deserializeToObject(&obj); QCOMPARE(o->metaObject()->className(), p.metaObject()->className()); Testobject *to = (Testobject*)o.get(); // test members QCOMPARE(to->x(), p.x()); QCOMPARE(to->y(), p.y()); QCOMPARE(to->optionalStr(), p.optionalStr()); // test single property nested object QCOMPARE(to->singleProp()->someUuid(), p.singleProp()->someUuid()); // test Lists QCOMPARE(to->internalList()->first()->someUuid(), p.internalList()->first()->someUuid()); QVERIFY(to->internalList()->at(0)->metaObject()->className() != to->internalList()->at(1)->metaObject()->className()); QVERIFY(to->internalList()->at(0)->metaObject()->className() == to->internalList()->at(2)->metaObject()->className()); QCOMPARE(to->intList().last(), p.intList().last()); // test nested object Nestedobject *no = to->nestedObj(); QVERIFY(no != nullptr); QCOMPARE(no->someString(), p.nestedObj()->someString()); // // Test optional property deserialization // QJsonObject pObj = obj[jenson::JenSON::toSerialName(p.metaObject()->className())].toObject(); pObj.remove("optionalStr"); obj[jenson::JenSON::toSerialName(p.metaObject()->className())] = pObj; sptr<Testobject> optionalObj = jenson::JenSON::deserialize<Testobject>(&obj); QCOMPARE(optionalObj->optionalStr(), QStringLiteral("initialized")); }
void LiFistEyeJSON::cleanJSONObjeck(QJsonObject &jsonObj) { if(!jsonObj.isEmpty()) { QStringList tempList=jsonObj.keys(); QList<QString>::iterator tempIterator=tempList.begin(); while(tempIterator!=tempList.end()) { qDebug()<<*tempIterator; jsonObj.remove(*tempIterator); tempIterator++; } } }
bool Srudp::schedRealSendto(QJsonObject jobj) { QString peer_addr = jobj.value("peer_addr").toString(); jobj.remove("peer_addr"); QString npkt = QJsonDocument(jobj).toJson(QJsonDocument::Compact); qint64 cseq = jobj.value("reliable").toInt(); QString host = peer_addr.split(':').at(0); quint16 port = peer_addr.split(':').at(1).toUShort(); qDebug()<<"sending pkt:"<<cseq<<npkt.length()<<m_proto_host<<m_proto_port<<host<<port; if (m_client_mode) { m_stun_client->replyIndication(peer_addr, npkt.toLatin1()); } else { m_stun_client->sendIndication(peer_addr, npkt.toLatin1()); } return true; }
void Device::onReadyRead() { const auto buf = m_device->readAll(); // qDebug() << buf; if(m_deviceSettings->maxSingleReceivedBytesCount() != -1) { m_singleReceivedBytesCount += buf.size(); if(m_singleReceivedBytesCount > m_deviceSettings->maxSingleReceivedBytesCount()) { this->waitForCloseAndDelete(OverMaxSingleReceivedBytesCountError); return; } } if(m_deviceSettings->maxAltogetherReceivedBytesCount() != -1) { m_altogetherReceivedBytesCount += buf.size(); if(m_altogetherReceivedBytesCount > m_deviceSettings->maxAltogetherReceivedBytesCount()) { this->waitForCloseAndDelete(OverMaxAltogetherReceivedBytesCount); return; } } m_reader->addData(buf); while(m_reader->readyRead()) { if(m_receivedIntervalTimer) { m_receivedIntervalTimer->stop(); m_receivedIntervalTimer->start(); } if(m_deviceSettings->maxSingleReceivedBytesCount() != -1) { m_singleReceivedBytesCount = 0; } QJsonObject data; if(!m_reader->read(data)) { continue; } if(!data.contains("__SjfType") || !data.contains("__SjfAction") || !data.contains("__SjfFlag")) { continue; } auto packageType = data["__SjfType"].toString(); auto packageAction = data["__SjfAction"].toString(); auto packageFlag = data["__SjfFlag"].toInt(); if(m_deviceSettings->removeSjfFlag()) { data.remove("__SjfType"); data.remove("__SjfAction"); data.remove("__SjfFlag"); } if(m_receivedManage->setCurrentThreadDeviceCallback()) { m_receivedManage->setCurrentThreadDeviceCallback()(this); } if(packageType == "request") { if(!m_receivedManage->requestPackageReceivedCallback()) { qDebug("Device::onReadyRead: Request package is received, buf callback is NULL"); return; } QJsonObject buf; m_receivedManage->requestPackageReceivedCallback()(packageAction, data, buf); if(!buf.isEmpty()) { this->writeReturnPackage(packageAction, buf, packageFlag); } } else if(packageType == "return") { if(!m_receivedManage->returnPackageReceivedCallback()) { qDebug("Device::onReadyRead: Return package is received, buf callback is NULL"); return; } m_receivedManage->returnPackageReceivedCallback()(packageAction, data, packageFlag); } else if(packageType == "post") { if(!m_receivedManage->postPackageReceivedCallback()) { qDebug("Device::onReadyRead: Post package is received, buf callback is NULL"); return; } m_receivedManage->postPackageReceivedCallback()(packageAction, data); } else { qDebug() << "Device::onReadyRead: Unknow package type:" << packageType; } } }
void JensonTests::testSerializationFailures() { // // Test deserialization failure and error message for empty JSON object // QJsonObject json; QString errorMsg; QVERIFY(errorMsg.isEmpty()); sptr<QObject> qObj = jenson::JenSON::deserializeToObject(&json, &errorMsg); QVERIFY(qObj == 0); QVERIFY(!errorMsg.isEmpty()); // Test exception version QTR_ASSERT_THROW(jenson::JenSON::deserializeToObject(&json), jenson::SerializationException) // // Test deserialization failure and error message for unkown JSON object // QString errorMsg2; QString className("NotRegisteredClass"); json.insert(className, QJsonValue()); qObj = jenson::JenSON::deserializeToObject(&json, &errorMsg2); QVERIFY(qObj == 0); QVERIFY(errorMsg != errorMsg2); QVERIFY(errorMsg2.contains(className)); // Test exception version QTR_ASSERT_THROW(jenson::JenSON::deserializeToObject(&json), jenson::SerializationException) // // Test deserialization failure on non-resetable missing field // QString errorMsg3; Testobject p(0.2, -5.3); QJsonObject json2 = jenson::JenSON::serialize(&p); QJsonObject pObj = json2[jenson::JenSON::toSerialName(p.metaObject()->className())].toObject(); pObj.remove("x"); json2[jenson::JenSON::toSerialName(p.metaObject()->className())] = pObj; qObj = jenson::JenSON::deserializeToObject(&json2, &errorMsg3); QVERIFY(qObj == 0); QVERIFY(errorMsg2 != errorMsg3); QVERIFY(errorMsg3.contains("x")); // Test exception version QTR_ASSERT_THROW(jenson::JenSON::deserializeToObject(&json2), jenson::SerializationException) // // Test exception on cast failure // QJsonObject json3 = jenson::JenSON::serialize(&p); QTR_ASSERT_THROW(sptr<Nestedobject> invalidCast = jenson::JenSON::deserialize<Nestedobject>(&json3), jenson::SerializationException) }
// ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- void DREAM3DSettings::remove(const QString& key) { QJsonObject obj = m_Stack.top()->group; obj.remove(key); }
void MessageTest::interpretError() { // If the error is malformed, parsing will NOT fail, as we cannot send an // error reply. Instead, the error metadata is replaced with a server error // (code = -32000) // Construct a valid object and verify that it parses. QJsonObject validErrorObj; validErrorObj.insert("code", 2); validErrorObj.insert("message", QString("Error message")); validErrorObj.insert("data", 5); QJsonObject validObj; validObj.insert("jsonrpc", QLatin1String("2.0")); validObj.insert("id", QLatin1String("5")); validObj.insert("error", validErrorObj); TEST_ERROR_PARSING(validObj, false); // This will be our test object. QJsonObject obj; QJsonObject errorObj; // error must be an object obj = validObj; obj["error"] = 5; TEST_ERROR_PARSING(obj, true); // error.code must be present errorObj = validErrorObj; errorObj.remove("code"); obj = validObj; obj["error"] = errorObj; TEST_ERROR_PARSING(obj, true); // error.code must be numeric errorObj = validErrorObj; errorObj["code"] = true; obj = validObj; obj["error"] = errorObj; TEST_ERROR_PARSING(obj, true); // error.code must be integral errorObj = validErrorObj; errorObj["code"] = 2.3; obj = validObj; obj["error"] = errorObj; TEST_ERROR_PARSING(obj, true); // error.message must be present errorObj = validErrorObj; errorObj.remove("message"); obj = validObj; obj["error"] = errorObj; TEST_ERROR_PARSING(obj, true); // error.message must be a string errorObj = validErrorObj; errorObj["message"] = 2.66; obj = validObj; obj["error"] = errorObj; TEST_ERROR_PARSING(obj, true); }
// Build list of scheduled cron snapshot jobs QJsonObject LifePreserver::listCron() { QJsonObject retObject; QStringList output = General::RunCommand("lpreserver cronsnap list").split("\n"); output << General::RunCommand("lpreserver cronscrub list").split("\n"); QList<QStringList> snaps; // Parse the output bool inSnapSection = false; bool inScrubSection = false; for ( int i = 0; i < output.size(); i++) { if ( output.at(i).indexOf("-----------------") != -1 ) { inSnapSection = true; continue; } if (!inSnapSection) continue; if ( output.at(i).indexOf("Pools scheduled for scrub") != -1 ) { inScrubSection = true; continue; } if ( output.at(i).isEmpty() || output.at(i).indexOf("-----------------") != -1 ) continue; if ( inSnapSection && ! inScrubSection ) { // Breakdown this cron job QString pool = output.at(i).section("-", 0, 0).simplified(); QString freq = output.at(i).section("-", 1, 1).simplified(); QString keep = output.at(i).section("-", 2, 2).simplified().replace("total: ", ""); QJsonObject values; values.insert("schedule", freq); values.insert("keep", keep); retObject.insert(pool, values); } else if (inSnapSection && inScrubSection ) { // Add a cron scrub QString pool = output.at(i).section("-", 0, 0).simplified(); QString freq = output.at(i).section("-", 1, 1).simplified().replace(" ", ""); qDebug() << "Found scrub:" << pool << freq; QJsonObject values; QStringList keys = retObject.keys(); if( keys.contains(pool)){ // We have an existing pool object, add it values = retObject[pool].toObject(); retObject.remove(pool); values.insert("scrub", freq); retObject.insert(pool, values); } else { // Add a new pool object with the scrub values.insert("scrub", freq); retObject.insert(pool, values); } } } return retObject; }