QJsonValue QJsonConvert::jsonFromScriptValue(const QJSValue& jsval){ if ( jsval.isArray() ){ QJSValueIterator it(jsval); QJsonArray arr; while( it.hasNext() ){ it.next(); QJsonValue itJsonValue = jsonFromScriptValue(it.value()); if( !itJsonValue.isNull() ) arr.append(itJsonValue); } return QJsonValue(arr); } else if ( jsval.isObject() ){ QJSValueIterator it(jsval); QJsonObject obj; while( it.hasNext() ){ it.next(); QJsonValue itJsonValue = jsonFromScriptValue(it.value()); if( !itJsonValue.isNull() ) obj[it.name()] = itJsonValue; } return QJsonValue(obj); } else if ( jsval.isString() ){ return QJsonValue(jsval.toString()); } else if ( jsval.isBool() ){ return QJsonValue(jsval.toString()); } else if ( jsval.isNumber() ){ return QJsonValue(jsval.toNumber() ); } return QJsonValue(); }
bool EtherIPC::readReply(QJsonValue& result) { const QString data = fReadBuffer; fReadBuffer.clear(); if ( data.isEmpty() ) { setError("Error on socket read: " + fSocket.errorString()); fCode = 0; return false; } QJsonParseError parseError; QJsonDocument resDoc = QJsonDocument::fromJson(data.toUtf8(), &parseError); if ( parseError.error != QJsonParseError::NoError ) { qDebug() << data << "\n"; setError("Response parse error: " + parseError.errorString()); fCode = 0; return false; } const QJsonObject obj = resDoc.object(); const int objID = obj["id"].toInt(-1); if ( objID != fActiveRequest.getCallID() ) { // TODO setError("Call number mismatch " + QString::number(objID) + " != " + QString::number(fActiveRequest.getCallID())); fCode = 0; return false; } result = obj["result"]; // get filter changes bugged, returns null on result array, see https://github.com/ethereum/go-ethereum/issues/2746 if ( result.isNull() && fActiveRequest.getType() == GetFilterChanges ) { result = QJsonValue(QJsonArray()); } if ( result.isUndefined() || result.isNull() ) { if ( obj.contains("error") ) { if ( obj["error"].toObject().contains("message") ) { fError = obj["error"].toObject()["message"].toString(); } if ( obj["error"].toObject().contains("code") ) { fCode = obj["error"].toObject()["code"].toInt(); } return false; } if ( fActiveRequest.getType() != GetTransactionByHash ) { // this can happen if out of sync, it's not fatal for transaction get setError("Result object undefined in IPC response for request: " + fActiveRequest.getMethod()); qDebug() << data << "\n"; return false; } } return true; }
void MessageTest::parse() { // Fetch the current filename and load it into a ReferenceString QFETCH(QString, filename); filename.prepend("message-ref/"); ReferenceString refStr(filename); // Parse the doc and create a message QJsonDocument doc = QJsonDocument::fromJson(refStr.toString().toLatin1()); QVERIFY(doc.isObject()); QJsonObject refObj = doc.object(); QJsonValue origId; // Fixup the ids so that the MessageIdManager can resolve them. if (refObj.contains("id")) { Message request(Message::Request, &m_conn); request.setMethod("testMethod"); QVERIFY(request.send()); m_conn.popMessage(); origId = refObj.value("id"); refObj["id"] = request.id(); } // Parse the message Message message(refObj); QVERIFY(message.parse()); // Reset the id if needed if (!origId.isNull()) message.setId(origId); // Compare strings QCOMPARE(refStr.toString(), QString(message.toJson())); }
void EtherIPC::handleGetSyncing() { QJsonValue jv; if ( !readReply(jv) ) { return bail(); } if ( jv.isNull() || ( jv.isBool() && !jv.toBool(false) ) ) { if ( fSyncing ) { fSyncing = false; if ( fBlockFilterID.isEmpty() ) { newBlockFilter(); } emit syncingChanged(fSyncing); } return done(); } const QJsonObject syncing = jv.toObject(); fCurrentBlock = Helpers::toQUInt64(syncing.value("currentBlock")); fHighestBlock = Helpers::toQUInt64(syncing.value("highestBlock")); fStartingBlock = Helpers::toQUInt64(syncing.value("startingBlock")); if ( !fSyncing ) { if ( !fBlockFilterID.isEmpty() ) { uninstallFilter(fBlockFilterID); fBlockFilterID.clear(); } fSyncing = true; } emit syncingChanged(fSyncing); done(); }
bool QJsonValueProto::isNull() const { QJsonValue *item = qscriptvalue_cast<QJsonValue*>(thisObject()); if (item) return item->isNull(); return false; }
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()); }
void AzubuHandler::handleStatus(const Stream &stream, QNetworkReply* reply) { if(reply->error() != QNetworkReply::NoError) { emit streamUncertain(stream); reply->deleteLater(); return; } QByteArray data = reply->readAll(); QJsonDocument response(QJsonDocument::fromJson(data.mid(1,data.length()-2))); QJsonObject responseObject = response.object(); QJsonValue online = responseObject["Online"]; if(online.isNull()) { emit streamUncertain(stream); } else if(online.isUndefined()) { emit streamUncertain(stream); } else if(online.toString().compare("0")==0){ emit streamOffline(stream); } else { emit streamOnline(stream); } reply->deleteLater(); }
void JetmonServer::readyRead() { QByteArray a_data = m_socket->readAll(); this->closeConnection(); if ( 0 == a_data.length() ) { LOG( "NO data returned when reading jetmon response." ); emit finished( this, 0, m_timer.msecsTo( QDateTime::currentDateTime() ) ); return; } QJsonDocument json_doc = parse_json_response( a_data ); if ( json_doc.isEmpty() || json_doc.isNull() ) { LOG( "Invalid JSON document format." ); emit finished( this, 0, m_timer.msecsTo( QDateTime::currentDateTime() ) ); return; } QJsonValue response = json_doc.object().value( "response" ); if ( response.isNull() ) { LOG( "Missing 'response' JSON value." ); emit finished( this, 0, m_timer.msecsTo( QDateTime::currentDateTime() ) ); return; } emit finished( this, 1, m_timer.msecsTo( QDateTime::currentDateTime() ) ); }
QTweetPlace QTweetConvert::jsonObjectToPlace(const QJsonObject& jsonObject) { QTweetPlace place; place.setName(jsonObject["name"].toString()); place.setCountryCode(jsonObject["country_code"].toString()); place.setCountry(jsonObject["country"].toString()); place.setID(jsonObject["id"].toString()); place.setFullName(jsonObject["full_name"].toString()); QString placeType = jsonObject["place_type"].toString(); if (placeType == "poi") place.setType(QTweetPlace::Poi); else if (placeType == "neighborhood") place.setType(QTweetPlace::Neighborhood); else if (placeType == "city") place.setType(QTweetPlace::City); else if (placeType == "admin") place.setType(QTweetPlace::Admin); else if (placeType == "country") place.setType(QTweetPlace::Country); else place.setType(QTweetPlace::Neighborhood); //twitter default QJsonValue bbJsonValue = jsonObject["bounding_box"]; if (!bbJsonValue.isNull()) { QJsonObject bbJsonObject = bbJsonValue.toObject(); if (bbJsonObject["type"].toString() == "Polygon") { QJsonArray coordList = bbJsonObject["coordinates"].toArray(); if (coordList.count() == 1) { QJsonArray latLongList = coordList[0].toArray(); if (latLongList.count() == 4) { QTweetGeoBoundingBox box; QJsonArray coordsBottomLeft = latLongList[0].toArray(); box.setBottomLeft(QTweetGeoCoord(coordsBottomLeft[1].toDouble(), coordsBottomLeft[0].toDouble())); QJsonArray coordsBottomRight = latLongList[1].toArray(); box.setBottomRight(QTweetGeoCoord(coordsBottomRight[1].toDouble(), coordsBottomRight[0].toDouble())); QJsonArray coordsTopRight = latLongList[2].toArray(); box.setTopRight(QTweetGeoCoord(coordsTopRight[1].toDouble(), coordsTopRight[0].toDouble())); QJsonArray coordsTopLeft = latLongList[3].toArray(); box.setTopLeft(QTweetGeoCoord(coordsTopLeft[1].toDouble(), coordsTopLeft[0].toDouble())); place.setBoundingBox(box); } } } } return place; }
/*! * Convert variant \a data to string \a json in JSON format. * * The data is encoded as an array containing one item * to allow the same encoding to be used for both * primitive and compound data types. * * Returns true if the conversion is successful, false otherwise. * * \sa convertFromJson() */ bool VersitUtils::convertToJson(const QVariant &data, QString *json) { const QJsonValue dataAsJsonValue = QJsonValue::fromVariant(data); if (data.isValid() && dataAsJsonValue.isNull()) return false; QJsonArray jsonArray; jsonArray.append(dataAsJsonValue); const QJsonDocument jsonDocument(jsonArray); *json = QString::fromUtf8(jsonDocument.toJson()); return true; }
// ====================== // PUBLIC SLOTS // ====================== void WebSocket::EventUpdate(EventWatcher::EVENT_TYPE evtype, QJsonValue msg){ if(msg.isNull()){ msg = EVENTS->lastEvent(evtype); } //qDebug() << "Socket Status Update:" << msg; if(!ForwardEvents.contains(evtype)){ return; } RestOutputStruct out; out.CODE = RestOutputStruct::OK; out.in_struct.namesp = "events"; out.out_args = msg; out.Header << "Content-Type: text/json; charset=utf-8"; //REST header info out.in_struct.name = EventWatcher::typeToString(evtype); //Now send the message back through the socket this->sendReply(out.assembleMessage()); }
ReturnedValue JsonObject::fromJsonValue(ExecutionEngine *engine, const QJsonValue &value) { if (value.isString()) return engine->currentContext()->d()->engine->newString(value.toString())->asReturnedValue(); else if (value.isDouble()) return Encode(value.toDouble()); else if (value.isBool()) return Encode(value.toBool()); else if (value.isArray()) return fromJsonArray(engine, value.toArray()); else if (value.isObject()) return fromJsonObject(engine, value.toObject()); else if (value.isNull()) return Encode::null(); else return Encode::undefined(); }
v8::Handle<v8::Value> QV8JsonWrapper::fromJsonValue(const QJsonValue &value) { if (value.isString()) return QJSConverter::toString(value.toString()); else if (value.isDouble()) return v8::Number::New(value.toDouble()); else if (value.isBool()) return value.toBool() ? v8::True() : v8::False(); else if (value.isArray()) return fromJsonArray(value.toArray()); else if (value.isObject()) return fromJsonObject(value.toObject()); else if (value.isNull()) return v8::Null(); else return v8::Undefined(); }
//! Gets an item from the cache. QJsonValue VaultFront::get( CacheType type, //!< The type of the requested item. int id ) const { // Try fetching the item. AsyncFetch* fetch = 0; switch( type ) { case CacheType::Class : fetch = m_core->classes()->get( id ); break; case CacheType::ObjectType : fetch = m_core->objectTypes()->get( id ); break; case CacheType::PropertyDefinition : fetch = m_core->propertyDefinitions()->get( id ); // Unknown item, return the null we set earlier. default: break; }; QJsonValue value; if( fetch->state() == AsyncFetch::Finished ) { value = fetch->value(); Q_ASSERT( ! value.isNull() && ! value.isUndefined() ); } else if( fetch->state() == AsyncFetch::Error ) { value = QJsonValue::Null; } else { Q_ASSERT( false ); } fetch->deleteLater(); // Return the value. return value; }
int findId(QString id, int rowHint) { Q_ASSERT(rowHint >= 0); const int count = _data.count(); if (rowHint < count) { QJsonValue hintId = _data[rowHint].toObject()[EnginioString::id]; if (hintId == id) return rowHint; if (id.isEmpty() && (hintId.isNull() || hintId.isUndefined())) return rowHint; } // TODO optimize it, in most caseses we need to just check around rowHint for (int i = count - 1; i >= 0; --i) { if (_data[i].toObject()[EnginioString::id] == id) return i; } return -1; }
void AzubuHandler::handlePreview() { QNetworkReply *reply = qobject_cast<QNetworkReply*>(QObject::sender()); QByteArray data = reply->readAll(); // delete the reply reply->deleteLater(); QJsonDocument response(QJsonDocument::fromJson(data.mid(1,data.length()-3))); QJsonObject streamJson = response.object(); QJsonValue online = streamJson["Online"]; if(!online.isNull() && !online.isUndefined() && !online.toString().compare("0")==0) { AzubuStream stream; stream.read(streamJson); emit setPreview(stream); } else { emit resetPreview(); } }
static Nuria::JsonMetaObjectReader::Error parseAnnotationsArray (const QJsonArray &array, Nuria::RuntimeMetaObject::AnnotationMap &annotations) { for (int i = 0; i < array.size (); i++) { QJsonValue cur = array.at (i); if (!cur.isObject ()) { return Nuria::JsonMetaObjectReader::AnnotationIsNotAnObject; } // QJsonObject obj = cur.toObject (); QJsonValue name = obj.value (QStringLiteral("name")); QJsonValue value = obj.value (QStringLiteral("value")); if (!name.isString ()) return Nuria::JsonMetaObjectReader::AnnotationNameIsNotAString; if (value.isNull ()) return Nuria::JsonMetaObjectReader::AnnotationValueHasUnknownType; annotations.insert (name.toString ().toUtf8 (), value.toVariant ()); } // return Nuria::JsonMetaObjectReader::NoError; }
void SocketIOClient::parseMessage(QString message) { //qDebug() << "SocketIOClient::parseMessage" << message; QRegExp regExp("^([^:]+):([0-9]+)?(\\+)?:([^:]+)?:?([\\s\\S]*)?$", Qt::CaseInsensitive, QRegExp::RegExp2); if (regExp.indexIn(message) != -1) { QStringList captured = regExp.capturedTexts(); //qDebug() << "Found:" << regExp.capturedTexts(); int messageType = captured.at(1).toInt(); int messageId = captured.at(2).toInt(); bool mustAck = (messageId != 0); bool autoAck = mustAck && captured.at(3).isEmpty(); QString endpoint = captured.at(4); QString data = captured.at(5); /*qDebug() << "MessageType:" << messageType << "MessageId:" << messageId << "autoAck:" << autoAck << "mustAck:" << mustAck << "endpoint:" << endpoint << "data:" << data;*/ if (autoAck) { acknowledge(messageId); } switch(messageType) { case 0: //disconnect { Q_EMIT(disconnected(endpoint)); break; } case 1: //connect { m_pHeartBeatTimer->start(); Q_EMIT(connected(endpoint)); break; } case 2: //heartbeat { Q_EMIT(heartbeatReceived()); break; } case 3: //message { Q_EMIT(messageReceived(data)); break; } case 4: //json message { qDebug() << "JSON message received:" << data; break; } case 5: //event { QJsonParseError parseError; //qDebug() << "Event received:" << data; QJsonDocument document = QJsonDocument::fromJson(QByteArray(data.toLatin1()), &parseError); if (parseError.error != QJsonParseError::NoError) { qDebug() << parseError.errorString(); } else { if (document.isObject()) { QJsonObject object = document.object(); QJsonValue value = object["name"]; if (!value.isUndefined()) { QString message = value.toString(); //QVariantList arguments; QJsonArray arguments; QJsonValue argsValue = object["args"]; if (!argsValue.isUndefined() && !argsValue.isNull()) { if (argsValue.isArray()) { //QJsonArray argsArray = argsValue.toArray(); //arguments = argsArray.toVariantList(); arguments = argsValue.toArray(); //qDebug() << "Received arguments" << argsValue; /*Q_FOREACH(QJsonValue val, argsArray) { arguments << val.toVariant(); }*/ } else { qDebug() << "Args argument is not an array"; return; } } Q_EMIT(eventReceived(message, arguments)); } else { qDebug() << "Invalid event received: no name"; } } } break; } case 6: //ack { QRegExp regExp("^([0-9]+)(\\+)?(.*)$", Qt::CaseInsensitive, QRegExp::RegExp2); if (regExp.indexIn(data) != -1) { QJsonParseError parseError; //QVariantList arguments; QJsonArray arguments; int messageId = regExp.cap(1).toInt(); QString argumentsValue = regExp.cap(3); if (!argumentsValue.isEmpty()) { QJsonDocument doc = QJsonDocument::fromJson(argumentsValue.toLatin1(), &parseError); if (parseError.error != QJsonParseError::NoError) { qDebug() << "JSONParseError:" << parseError.errorString(); return; } else { if (doc.isArray()) { //arguments = doc.array().toVariantList(); arguments = doc.array(); } else { qDebug() << "Error: data of event is not an array"; return; } } } Q_EMIT(ackReceived(messageId, arguments)); } break; } case 7: //error { QStringList pieces = data.split("+"); QString reason = pieces[0]; QString advice; if (pieces.length() == 2) { advice = pieces[1]; } Q_EMIT(errorReceived(reason, advice)); break; } case 8: //noop { qDebug() << "Noop received" << data; break; } } } }
QTweetStatus QTweetConvert::jsonObjectToStatus(const QJsonObject& json) { QTweetStatus status; status.setCreatedAt(json["created_at"].toString()); status.setText(json["text"].toString()); status.setId(static_cast<qint64>(json["id"].toDouble())); status.setInReplyToUserId(static_cast<qint64>(json["in_reply_to_user_id"].toDouble())); status.setInReplyToScreenName(json["in_reply_to_screen_name"].toString()); status.setFavorited(json["favorited"].toBool()); QJsonObject userObject = json["user"].toObject(); QTweetUser user = jsonObjectToUser(userObject); status.setUser(user); status.setSource(json["source"].toString()); status.setInReplyToStatusId(static_cast<qint64>(json["in_reply_to_status_id"].toDouble())); //check if contains native retweet if (json.contains("retweeted_status")) { QJsonObject retweetObject = json["retweeted_status"].toObject(); QTweetStatus rtStatus = jsonObjectToStatus(retweetObject); status.setRetweetedStatus(rtStatus); } //parse place id if it's not null QJsonValue placeValue = json["place"]; if (!placeValue.isNull()) { QTweetPlace place = jsonObjectToPlace(placeValue.toObject()); status.setPlace(place); } //check if contains entities if (json.contains("entities")) { QJsonObject entitiesObject = json["entities"].toObject(); //url entities QJsonArray urlEntitiesList = entitiesObject["urls"].toArray(); for (int i = 0; i < urlEntitiesList.size(); ++i) { QTweetEntityUrl urlEntity = jsonObjectToEntityUrl(urlEntitiesList[i].toObject()); status.addUrlEntity(urlEntity); } //hashtag entities QJsonArray hashtagEntitiesList = entitiesObject["hashtags"].toArray(); for (int i = 0; i < hashtagEntitiesList.size(); ++i) { QTweetEntityHashtag hashtagEntity = jsonObjectToEntityHashtag(hashtagEntitiesList[i].toObject()); status.addHashtagEntity(hashtagEntity); } //user mentions QJsonArray userMentionsEntitiesList = entitiesObject["user_mentions"].toArray(); for (int i = 0; i < userMentionsEntitiesList.count(); ++i) { QTweetEntityUserMentions userMentionsEntity = jsonObjectToEntityUserMentions(userMentionsEntitiesList[i].toObject()); status.addUserMentionsEntity(userMentionsEntity); } //media QJsonArray mediaEntitiesList = entitiesObject["media"].toArray(); for (int i = 0; i < mediaEntitiesList.count(); ++i) { QTweetEntityMedia mediaEntity = jsonObjectToEntityMedia(mediaEntitiesList[i].toObject()); status.addMediaEntity(mediaEntity); } } return status; }
//not to be used in timelines api, but in geo api, where place contains other places //is it recursive responsive? QTweetPlace QTweetConvert::jsonObjectToPlaceRecursive(const QJsonObject& jsonObject) { QTweetPlace place; place.setName(jsonObject["name"].toString()); place.setCountryCode(jsonObject["country_code"].toString()); place.setCountry(jsonObject["country"].toString()); place.setID(jsonObject["id"].toString()); place.setFullName(jsonObject["full_name"].toString()); QString placeType = jsonObject["place_type"].toString(); if (placeType == "poi") place.setType(QTweetPlace::Poi); else if (placeType == "neighborhood") place.setType(QTweetPlace::Neighborhood); else if (placeType == "city") place.setType(QTweetPlace::City); else if (placeType == "admin") place.setType(QTweetPlace::Admin); else if (placeType == "country") place.setType(QTweetPlace::Country); else place.setType(QTweetPlace::Neighborhood); //twitter default QJsonValue bbVar = jsonObject["bounding_box"]; if (!bbVar.isNull()) { QJsonObject bbObject = bbVar.toObject(); if (bbObject["type"].toString() == "Polygon") { QJsonArray coordList = bbObject["coordinates"].toArray(); if (coordList.count() == 1) { QJsonArray latLongList = coordList[0].toArray(); if (latLongList.count() == 4) { QTweetGeoBoundingBox box; QJsonArray coordsBottomLeft = latLongList[0].toArray(); box.setBottomLeft(QTweetGeoCoord(coordsBottomLeft[1].toDouble(), coordsBottomLeft[0].toDouble())); QJsonArray coordsBottomRight = latLongList[1].toArray(); box.setBottomRight(QTweetGeoCoord(coordsBottomRight[1].toDouble(), coordsBottomRight[0].toDouble())); QJsonArray coordsTopRight = latLongList[2].toArray(); box.setTopRight(QTweetGeoCoord(coordsTopRight[1].toDouble(), coordsTopRight[0].toDouble())); QJsonArray coordsTopLeft = latLongList[3].toArray(); box.setTopLeft(QTweetGeoCoord(coordsTopLeft[1].toDouble(), coordsTopLeft[0].toDouble())); place.setBoundingBox(box); } } } } QJsonArray containedArray = jsonObject["contained_within"].toArray(); QList<QTweetPlace> containedInPlacesList; if (!containedArray.isEmpty()) { for (int i = 0; i < containedArray.size(); ++i) { QTweetPlace containedPlace = jsonObjectToPlaceRecursive(containedArray[i].toObject()); containedInPlacesList.append(containedPlace); } } place.setContainedWithin(containedInPlacesList); return place; }
void SubscribeThread::processSubscribeDanmakuResponse() { QNetworkReply *reply = (QNetworkReply *)sender(); int statusCode = reply->attribute( QNetworkRequest::HttpStatusCodeAttribute ).toInt(); if(reply->hasRawHeader("Location")){ QString strLocation = reply->header(QNetworkRequest::LocationHeader).toString(); this->subscribeDanmaku(strLocation); }else if(statusCode == 200){ QByteArray responseData = reply->readAll(); // qDebug()<<"response data:"<<responseData; QJsonDocument jsonDoc = QJsonDocument::fromJson(responseData); if(jsonDoc.isNull() ||!jsonDoc.isArray()) {// null or not array format goto out; } QJsonArray jsonArray = jsonDoc.array(); for(int i = 0; i < jsonArray.count();i++){ QJsonValue jsonValue = jsonArray[i]; if(jsonValue.isUndefined()||jsonValue.isNull()) { goto out; } QString text = jsonValue.toObject().value("text").toString(); QString position = jsonValue.toObject().value("position").toString(); QString style = jsonValue.toObject().value("style").toString(); if(text.size()>128){ text.resize(128); } Danmaku_Msg msg; msg.msg = text; if(style=="blue"){ msg.color = QColor("#0000FF"); }else if(style=="white"){ msg.color = QColor("#FFFFFF"); }else if(style=="red"){ msg.color = QColor("#FF0000"); }else if(style=="yellow"){ msg.color = QColor("yellow"); }else if(style=="cyan"){ msg.color = QColor("cyan"); }else if(style=="green"){ msg.color = QColor("#00FF00"); }else if(style=="purple"){ msg.color = QColor("#871F78"); }else{ msg.color = QColor("black"); } if(position=="top"){ msg.positon = BULLET_TOP; }else if(position == "bottom") { msg.positon = BULLET_BOTTOM; }else { msg.positon = BULLET_FLY; } emit this->receivedDamanku(msg); } } out: qApp->processEvents(QEventLoop::AllEvents); if(reply->error() == QNetworkReply::NoError){ this->pullDanmaku(); }else { QTimer::singleShot(2000,this,SLOT(pullDanmaku())); } reply->deleteLater(); return; }
//! Normalizes property value for use. Receives true if the property value is acceptable for the intended purpose. bool ObjectVersionCore::normalizePropertyValue( PropertyValuePurpose purpose, QJsonValueRef value ) { // Block certain property values. QJsonObject asObject = value.toObject(); switch( purpose ) { case ForDisplay : { Q_ASSERT( asObject.contains( "PropertyDef" ) ); int propertyDef = asObject[ "PropertyDef" ].toDouble(); const int* blocked = qFind( BLOCKED_FOR_DISPLAY_PROPERTY_VALUES, BLOCKED_FOR_DISPLAY_PROPERTY_VALUES + sizeof( BLOCKED_FOR_DISPLAY_PROPERTY_VALUES ) / sizeof( int ), propertyDef ); if( blocked != BLOCKED_FOR_DISPLAY_PROPERTY_VALUES + sizeof( BLOCKED_FOR_DISPLAY_PROPERTY_VALUES ) / sizeof( int ) ) return false; // The property value was blocked. } break; // All property values are accepted. case All: break; // Unexpected purpose. case Undefined : default : qCritical( "TODO: Error reporting." ); return false; break; } // Normalize the typed value part. QJsonObject typedValue = asObject[ "TypedValue" ].toObject(); if( ! typedValue.contains( "HasValue" ) ) typedValue[ "HasValue" ] = false; // MFWS REST API does not include the field "HasValue" if the value is undefined. This can be considered a bug in MFWS REST API. // Perform data type specific normalization. Q_ASSERT( typedValue.contains( "DataType" ) ); int dataType = typedValue[ "DataType" ].toDouble(); switch( dataType ) { // Single-line text. case 1: { // For single-line text values we explicitly set the value to an empty string // if we receive an undefined or null text based value. QJsonValue value = typedValue[ "Value" ]; if( ! typedValue.contains( "Value" ) || // "Value" is not included if the value in M-Files is empty/null. This is a bug in MFWS REST API. value.isUndefined() || value.isNull() ) { // Ensure that the empty single-line text is represented by a valid string. // In M-Files null, undefined and empty string are semantically equivalent. typedValue[ "Value" ] = QString( "" ); typedValue[ "DisplayValue" ] = QString( "" ); } } break; // Multi-select lookup. case 10: typedValue[ "DisplayValue" ] = QString(); break; // The data type does not require special handling. default: break; } // NOTE: QJsonXYZ objects use implicit sharing of the data. e.g. copies are only created when // something is modified. As we just modified the values and created copies we need to assign the copies // back to the original values. asObject[ "TypedValue" ] = typedValue; // Re-assign the typed value to the PropertyVAlue object. value = asObject; // Update the actual property value. // This property value was accepted. return true; }
void OnlineDataNodeOSF::nodeInfoReceived() { QNetworkReply *reply = (QNetworkReply*)this->sender(); bool success = false; bool finished = false; if (reply->error() != QNetworkReply::NoError) { setError(true, reply->errorString()); finished = true; } else { QByteArray data = reply->readAll(); QString dataString = (QString) data; QJsonParseError error; QJsonDocument doc = QJsonDocument::fromJson(dataString.toUtf8(), &error); QJsonObject json = doc.object(); QJsonObject nodeObject; if (json.value("data").isArray() && _expectedName != "") { bool lastItem = _subPath.count() == 1; QString searchName =_subPath.first(); searchName = searchName.right(searchName.length() - searchName.lastIndexOf("/") - 1); QJsonArray arrayObject = json.value("data").toArray(); bool found = searchList(searchName, lastItem ? _kind : OnlineDataNode::Folder, arrayObject, nodeObject); if ( ! found) { QJsonObject contentLevelLinks = json.value("links").toObject(); QJsonValue nextContentList = contentLevelLinks.value("next"); if (nextContentList.isNull() == false) { processUrl(QUrl(nextContentList.toString())); finished = false; } else if (lastItem) { finished = true; success = true; _exists = false; } else { finished = true; success = false; } } else if (_subPath.count() > 1) { _subPath.removeFirst(); QString basePath = ""; if (_subPath.count() == 1) { populateNodeData(nodeObject); basePath = getBaseUrl(nodeObject); } else basePath = getContentsUrl(nodeObject); processUrl(QUrl(basePath)); finished = false; } else { populateNodeData(nodeObject); finished = true; success = true; } } else if (json.value("data").isObject()) { nodeObject = json.value("data").toObject(); finished = interpretNode(nodeObject); success = true; } else { setError(true, "Online node data in unknown form."); finished = true; success = false; } } reply->deleteLater(); if (finished) endInit(success); }
bool HttpServer::initialize() { if(m_IsInitialized) { LOG_DEBUG("Already initialized"); return false; } QProcessEnvironment env = QProcessEnvironment::systemEnvironment(); if(env.contains(QTTP_HOME_ENV_VAR)) { QDir::setCurrent(env.value(QTTP_HOME_ENV_VAR)); LOG_DEBUG("Working directory from $" << QTTP_HOME_ENV_VAR << QDir::currentPath()); } else { // Just a quirk for mac, but I wonder if we can apply to all in general. #ifdef Q_OS_MAC QDir::setCurrent(qApp->applicationDirPath()); LOG_DEBUG("Working directory" << QDir::currentPath()); #else LOG_DEBUG("Working directory" << QDir::currentPath()); #endif } QCoreApplication* app = QCoreApplication::instance(); Q_ASSERT(app); m_CmdLineParser.addOptions({ {{"i", "ip"}, QCoreApplication::translate("main", "ip of the target interface"), QCoreApplication::translate("main", "ip")}, {{"p", "port"}, QCoreApplication::translate("main", "port to listen on"), QCoreApplication::translate("main", "port")}, {{"m", "meta"}, QCoreApplication::translate("main", "appends metadata to responses")}, {{"c", "config"}, QCoreApplication::translate("main", "absolute path to the global config file (json)"), QCoreApplication::translate("main", "config")}, {{"r", "routes"}, QCoreApplication::translate("main", "absolute path to the routes config file (json)"), QCoreApplication::translate("main", "routes")}, {{"d", "dir"}, QCoreApplication::translate("main", "absolute path to the config directory, don't combine with -c or -r args"), QCoreApplication::translate("main", "dir")}, {{"w", "www"}, QCoreApplication::translate("main", "absolute path to the www folder to serve http files"), QCoreApplication::translate("main", "www")}, {{"s", "swagger"}, QCoreApplication::translate("main", "exposes swagger-api json responses for the path /swagger/")}, }); m_CmdLineParser.addHelpOption(); m_CmdLineParser.process(*app); if(env.contains(CONFIG_DIRECTORY_ENV_VAR)) { QString var = env.value(CONFIG_DIRECTORY_ENV_VAR); if(!var.isNull() && !var.trimmed().isEmpty()) { LOG_INFO("Processing ENVIRONMENT VARIABLE [" << var << "]"); initConfigDirectory(var); } else { LOG_WARN("Invalid ENVIRONMENT VARIABLE [" << CONFIG_DIRECTORY_ENV_VAR << "]"); } } QJsonValue d = m_CmdLineParser.value("d"); if(d.isString() && !d.isNull() && !d.toString().trimmed().isEmpty()) { initConfigDirectory(d.toString()); } else { QJsonValue c = m_CmdLineParser.value("c"); if(c.isString() && !c.isNull() && !c.toString().trimmed().isEmpty()) { initGlobal(c.toString()); } else { initGlobal(GLOBAL_CONFIG_FILE_PATH); } QJsonValue r = m_CmdLineParser.value("r"); if(r.isString() && !r.isNull() && !r.toString().trimmed().isEmpty()) { initRoutes(r.toString()); } else { initRoutes(ROUTES_CONFIG_FILE_PATH); } } if(!m_SendRequestMetadata) { m_SendRequestMetadata = m_CmdLineParser.isSet("m"); LOG_DEBUG("CmdLine meta-data" << m_SendRequestMetadata); } if(!m_IsSwaggerEnabled) { initSwagger(m_CmdLineParser.isSet("s")); LOG_DEBUG("CmdLine swagger" << m_IsSwaggerEnabled); } QJsonValue i = m_CmdLineParser.value("i"); if((i.isString() || i.isDouble()) && !i.toString().trimmed().isEmpty()) { QString ip = i.toString(); m_GlobalConfig["bindIp"] = ip; LOG_DEBUG("CmdLine ip" << ip); } QJsonValue p = m_CmdLineParser.value("p"); if((p.isString() || p.isDouble()) && !p.toString().trimmed().isEmpty()) { qint32 port = p.toInt(); m_GlobalConfig["bindPort"] = port; LOG_DEBUG("CmdLine port" << port); } QJsonValue w = m_CmdLineParser.value("w"); if(w.isString() && !w.isNull() && !w.toString().trimmed().isEmpty()) { initHttpDirectory(w.toString()); LOG_DEBUG("CmdLine www/web/http-files" << w); } m_IsInitialized = true; return true; }
void q2d::json::toDocumentEntry(QJsonObject json, Document* document) { Q_ASSERT(json.contains(JSON_DOCENTRY_ID)); QString id = json.value(JSON_DOCENTRY_ID).toString(); QString typeString = json.value(JSON_DOCENTRY_TYPE).toString(); enums::DocumentEntryType type = enums::StringToDocumentEntryType(typeString); qDebug() << "Parsing document entry" << id << "of type" << typeString; // TODO reconstruct the schematics element QJsonObject schematicJson = json.value(JSON_DOCENTRY_SCHEMATIC_ELEMENT).toObject(); QString typeId = schematicJson.value(JSON_SCHEMATIC_SUB_TYPE).toString(); QPointF position = toPointF(schematicJson.value(JSON_SCHEMATIC_POSITION).toObject()); // reconstruct the parent QJsonValue parentValue = json.value(JSON_DOCENTRY_PARENT); DocumentEntry* parent; if (parentValue.isNull()) { parent = nullptr; } else { parent = document->entryForFullId(parentValue.toString()); } switch (type) { case enums::DocumentEntryType::COMPONENT : { metamodel::ComponentDescriptor* descriptor = document->componentFactory()->getTypeForHierarchyName(typeId); DocumentEntryFactory::instantiateComponent(document, descriptor, position, id, false); } break; case enums::DocumentEntryType::PORT : { Q_CHECK_PTR(parent); model::InterfacingME* interfacing = dynamic_cast<model::InterfacingME*>(parent->modelElement()); Q_CHECK_PTR(interfacing); QPoint position = interfacing->portPosition(id); QString directionString = schematicJson.value(JSON_SCHEMATIC_SUB_TYPE).toString(); DocumentEntryFactory::instantiatePort( document, parent, position, model::enums::StringToPortDirection(directionString), id); } break; case enums::DocumentEntryType::MODULE_INTERFACE: { QString directionString = schematicJson.value(JSON_SCHEMATIC_SUB_TYPE).toString(); model::enums::PortDirection direction = model::enums::StringToPortDirection(directionString); DocumentEntryFactory::instantiateModuleInterface(document, position, direction, id); } break; case enums::DocumentEntryType::WIRE : { QJsonObject additional = schematicJson.value(JSON_SCHEMATIC_ADDITIONAL).toObject(); Q_ASSERT(!additional.isEmpty()); DocumentEntry* sender = document->entryForFullId(additional.value(JSON_WIRE_START).toString()); Q_CHECK_PTR(sender); DocumentEntry* receiver = document->entryForFullId(additional.value(JSON_WIRE_END).toString()); Q_CHECK_PTR(receiver); DocumentEntryFactory::instantiateWire(document, sender, receiver, id); } break; default: qDebug() << "Unknown type of component entry"; // ignore everything else for now } }
QJsonObject cacic_hardware::coletaWin() { QJsonObject hardware; QStringList params; QJsonValue wmiResult; // Win32_ComputerSystem (Caption, Description, Domain, DNSHostName, Manufacturer, // Model, Name, PrimaryOwnerName, TotalPhysicalMemory, Workgroup) params << "Caption" << "Description" << "Domain" << "DNSHostName" << "Manufacturer" << "Model" << "Name" << "PrimaryOwnerName" << "TotalPhysicalMemory" << "Workgroup"; wmiResult = wmi::wmiSearch("Win32_ComputerSystem", params); if (!wmiResult.isNull()) hardware["ComputerSystem"] = wmiResult; //Win32_PortableBattery // (Verifica se é notebook) params.clear(); wmiResult = wmi::wmiSearch("Win32_PortableBattery", params); QJsonObject notebook; notebook["Value"] = QJsonValue::fromVariant(!wmiResult.isNull()); hardware["IsNotebook"] = notebook; delete notebook; if (!wmiResult.isNull()){ hardware["PortableBattery"] = wmiResult; } //Win32_Bios // (Manufacturer, SMBIOSBIOSVersion, BIOSVersion, Version, SerialNumber, ReleaseDate) params.clear(); params << "Manufacturer" << "SMBIOSBIOSVersion" << "BIOSVersion" << "Version" << "SerialNumber" << "ReleaseDate"; wmiResult = wmi::wmiSearch("Win32_Bios", params); if (!wmiResult.isNull()) hardware["Bios"] = wmiResult; //Win32_BaseBoard // (Manufacturer, Model, SerialNumber) params.clear(); params << "Manufacturer" << "Model" << "SerialNumber"; wmiResult = wmi::wmiSearch("Win32_Baseboard", params); if (!wmiResult.isNull()) hardware["BaseBoard"] = wmiResult; //Win32_SystemEnclosure // (Manufacturer, ChassisTypes, SerialNumber, SMBIOSAssetTag) params.clear(); params << "Manufacturer" << "ChassisTypes" << "SerialNumber" << "SMBIOSAssetTag"; wmiResult = wmi::wmiSearch("Win32_SystemEnclosure", params); if (!wmiResult.isNull()) hardware["SystemEnclosure"] = wmiResult; //Win32_FloppyDrive // (Manufacturer, Caption, Description, Name, MediaType, Size) params.clear(); params << "Manufacturer" << "Caption" << "Description" << "Name"; wmiResult = wmi::wmiSearch("Win32_FloppyDrive", params); if (!wmiResult.isNull()) hardware["FloppyDrive"] = wmiResult; //Win32_DiskDrive // (Manufacturer, Caption, Description, Name, MediaType, Size, SerialNumber, Model, FirmwareRevision) params.clear(); params << "Manufacturer" << "Caption" << "Description" << "Name" << "MediaType" << "Size" << "SerialNumber" << "Model" << "FirmwareRevision"; wmiResult = wmi::wmiSearch("Win32_DiskDrive", params); if (!wmiResult.isNull()) hardware["DiskDrive"] = wmiResult; //Win32_CDROMDrive // (Manufacturer, Caption, Description, Name, MediaType, Size) params.clear(); params << "Manufacturer" << "Caption" << "Description" << "MediaType" << "Name" << "Size"; wmiResult = wmi::wmiSearch("Win32_CDROMDrive", params); if (!wmiResult.isNull()) hardware["CDROMDrive"] = wmiResult; //Win32_FloppyController // (Manufacturer, Caption, Description, Name) params.clear(); params << "Manufacturer" << "Caption" << "Description" << "Name"; wmiResult = wmi::wmiSearch("Win32_FloppyController", params); if (!wmiResult.isNull()) hardware["FloppyController"] = wmiResult; //Win32_SCSIController // (Manufacturer, Caption, Description, Name, HardwareVersion) params.clear(); params << "Manufacturer" << "Caption" << "Description" << "Name" << "HardwareVersion"; wmiResult = wmi::wmiSearch("Win32_SCSIController", params); if (!wmiResult.isNull()) hardware["SCSIController"] = wmiResult; //Win32_InfraredDevice // (Manufacturer, Caption, Description, Name) params.clear(); params << "Manufacturer" << "Caption" << "Description" << "Name"; wmiResult = wmi::wmiSearch("Win32_InfraredDevice", params); if (!wmiResult.isNull()) hardware["InfraredDevice"] = wmiResult; //Win32_USBController // (Manufacturer, Caption, Description, Name) params.clear(); params << "Manufacturer" << "Caption" << "Description" << "Name"; wmiResult = wmi::wmiSearch("Win32_USBController", params); if (!wmiResult.isNull()) hardware["USBController"] = wmiResult; //Win32_PCMCIAController // (Manufacturer, Caption, Description, Name) params.clear(); params << "Manufacturer" << "Caption" << "Description" << "Name"; wmiResult = wmi::wmiSearch("Win32_PCMCIAController", params); if (!wmiResult.isNull()) hardware["PCMCIAController"] = wmiResult; //Win32_VideoController // (Description, VideoProcessor, AdapterRAM, CurrentHorizontalResolution, CurrentVerticalResolution, Caption, Name) params.clear(); params << "VideoProcessor" << "AdapterRAM" << "Description" << "Name" << "CurrentHorizontalResolution" << "CurrentVerticalResolution" << "Caption" << "AcceleratorCapabilities"; wmiResult = wmi::wmiSearch("Win32_VideoController", params); if (!wmiResult.isNull()) hardware["VideoController"] = wmiResult; //Win32_DesktopMonitor // (MonitorManufacturer, Caption, Description, MonitorType, Name) params.clear(); params << "MonitorManufacturer" << "Caption" << "Description" << "MonitorType" << "Name"; wmiResult = wmi::wmiSearch("Win32_DesktopMonitor", params); if (!wmiResult.isNull()) hardware["DesktopMonitor"] = wmiResult; //Win32_Printer // (Name, DriverName, PortName, ServerName, ShareName, HorizontalResolution, VerticalResolution, Comment, Shared, Network) params.clear(); params << "Name" << "DriverName" << "PortName" << "ServerName" << "ShareName" << "HorizontalResolution" << "VerticalResolution" << "Comment" << "Shared" << "Network"; wmiResult = wmi::wmiSearch("Win32_Printer", params); if (!wmiResult.isNull()) hardware["Printer"] = wmiResult; //Win32_PortConnector // (ExternalReferenceDesignator, PortType (verificar), ConnectorType (verificar), Manufacturer, Caption, Name) params.clear(); params << "ExternalReferenceDesignator" << "PortType" << "ConnectorType" << "Name" << "Caption" << "Manufacturer"; wmiResult = wmi::wmiSearch("Win32_PortConnector", params); if (!wmiResult.isNull()) hardware["PortConnector"] = wmiResult; //Win32_SerialPort // (Name, Caption, Description, StatusInfo) params.clear(); params << "Name" << "Caption" << "Description" << "StatusInfo"; wmiResult = wmi::wmiSearch("Win32_SerialPort", params); if (!wmiResult.isNull()) hardware["SerialPort"] = wmiResult; //Win32_Processor // (MaxClockSpeed, Name, Architecture, NumberOfCores, SocketDesignation, Manufacturer, Architecture, NumberOfCores // CurrentClockSpeed, MaxClockSpeed, L2CacheSize, AddressWidth, DataWidth, VoltageCaps, CpuStatus, // ProcessorId || UniqueId, AddressWidth) params.clear(); params << "MaxClockSpeed" << "Name" << "Architecture" << "NumberOfCores" << "SocketDesignation" << "Manufacturer" << "Architecture" << "NumberOfCores" << "CurrentClockSpeed" << "MaxClockSpeed" << "L2CacheSize" << "AddressWidth" << "DataWidth" << "VoltageCaps" << "CpuStatus" << "ProcessorId" << "UniqueId" << "AddressWidth"; wmiResult = wmi::wmiSearch("Win32_Processor", params); if (!wmiResult.isNull()) hardware["Processor"] = wmiResult; //Win32_OperatingSystem // (Name, Version, CSDVersion, Description, InstallDate, Organization, RegisteredUser, SerialNumber) params.clear(); params << "Name" << "Version" << "CSDVersion" << "Description" << "InstallDate" << "Organization" << "RegisteredUser" << "SerialNumber"; wmiResult = wmi::wmiSearch("Win32_OperatingSystem", params); if (!wmiResult.isNull()) hardware["OperatingSystem"] = wmiResult; //Win32_SystemSlot // (Name, Description, SlotDesignation, CurrentUsage, Status, Shared) params.clear(); params << "Name" << "Description" << "SlotDesignation" << "CurrentUsage" << "Status" << "Shared"; wmiResult = wmi::wmiSearch("Win32_SystemSlot", params); if (!wmiResult.isNull()) hardware["SystemSlot"] = wmiResult; //Win32_LogicalDisk // (Caption, DriveType, Filesystem, VolumeName, ProviderName, Filesystem, VolumeName, Size, FreeSpace) params.clear(); params << "Caption" << "DriveType" << "Filesystem" << "VolumeName" << "ProviderName" << "Filesystem" << "VolumeName" << "Size" << "FreeSpace"; wmiResult = wmi::wmiSearch("Win32_LogicalDisk", params); if (!wmiResult.isNull()) hardware["LogicalDisk"] = wmiResult; //Win32_PhysicalMemory // (Caption, Description, BankLabel, DeviceLocator, Capacity, Speed, MemoryType, SerialNumber) params.clear(); params << "Caption" << "Description" << "BankLabel" << "DeviceLocator" << "Capacity" << "Speed" << "MemoryType"; wmiResult = wmi::wmiSearch("Win32_PhysicalMemory", params); if (!wmiResult.isNull()) hardware["PhysicalMemory"] = wmiResult; //Win32_Keyboard // (Caption, Description, Name) params.clear(); params << "Caption" << "Description" << "Name" << "Layout"; wmiResult = wmi::wmiSearch("Win32_Keyboard", params); if (!wmiResult.isNull()) hardware["Keyboard"] = wmiResult; //Win32_PointingDevice // (Manufacturer, Caption, Description, PointingType, DeviceInterface) params.clear(); params << "Manufacturer" << "Caption" << "Description" << "PointingType" << "DeviceInterface"; wmiResult = wmi::wmiSearch("Win32_PointingDevice", params); if (!wmiResult.isNull()) hardware["PointingDevice"] = wmiResult; //Win32_PnPSignedDriver // (Manufacturer, DeviceName, Description, Location, DeviceClass) params.clear(); params << "Manufacturer" << "DeviceName" << "Description" << "Location" << "DeviceClass"; wmiResult = wmi::wmiSearch("Win32_PnPSignedDriver", params); if (!wmiResult.isNull()) hardware["PnPSignedDriver"] = wmiResult; return hardware; }
QJsonObject DomainServerSettingsManager::responseObjectForType(const QString& typeValue, bool isAuthenticated) { QJsonObject responseObject; if (!typeValue.isEmpty() || isAuthenticated) { // convert the string type value to a QJsonValue QJsonValue queryType = typeValue.isEmpty() ? QJsonValue() : QJsonValue(typeValue.toInt()); const QString AFFECTED_TYPES_JSON_KEY = "assignment-types"; // enumerate the groups in the description object to find which settings to pass foreach(const QJsonValue& groupValue, _descriptionArray) { QJsonObject groupObject = groupValue.toObject(); QString groupKey = groupObject[DESCRIPTION_NAME_KEY].toString(); QJsonArray groupSettingsArray = groupObject[DESCRIPTION_SETTINGS_KEY].toArray(); QJsonObject groupResponseObject; foreach(const QJsonValue& settingValue, groupSettingsArray) { const QString VALUE_HIDDEN_FLAG_KEY = "value-hidden"; QJsonObject settingObject = settingValue.toObject(); if (!settingObject[VALUE_HIDDEN_FLAG_KEY].toBool()) { QJsonArray affectedTypesArray = settingObject[AFFECTED_TYPES_JSON_KEY].toArray(); if (affectedTypesArray.isEmpty()) { affectedTypesArray = groupObject[AFFECTED_TYPES_JSON_KEY].toArray(); } if (affectedTypesArray.contains(queryType) || (queryType.isNull() && isAuthenticated)) { // this is a setting we should include in the responseObject QString settingName = settingObject[DESCRIPTION_NAME_KEY].toString(); // we need to check if the settings map has a value for this setting QVariant variantValue; QVariant settingsMapGroupValue = _settingsMap.value(groupObject[DESCRIPTION_NAME_KEY].toString()); if (!settingsMapGroupValue.isNull()) { variantValue = settingsMapGroupValue.toMap().value(settingName); } if (variantValue.isNull()) { // no value for this setting, pass the default if (settingObject.contains(SETTING_DEFAULT_KEY)) { groupResponseObject[settingName] = settingObject[SETTING_DEFAULT_KEY]; } else { // users are allowed not to provide a default for string values // if so we set to the empty string groupResponseObject[settingName] = QString(""); } } else { groupResponseObject[settingName] = QJsonValue::fromVariant(variantValue); } } } } if (!groupResponseObject.isEmpty()) { // set this group's object to the constructed object responseObject[groupKey] = groupResponseObject; } }