예제 #1
0
파일: remdev.cpp 프로젝트: 2BTech/DDX
QJsonObject RemDev::newError(QJsonValue id, int code, const QString &msg, const QJsonValue &data) const {
	QJsonObject e;
	e.insert("code", code);
	e.insert("message", msg);
	if (data.type() != QJsonValue::Undefined) e.insert("data", data);
	QJsonObject o(rpc_seed);
	o.insert("error", e);
	if (id.type() == QJsonValue::Undefined) id = QJsonValue::Null;
	o.insert("id", id);
	return o;
}
예제 #2
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;
    }
예제 #3
0
void MainWindow::on_treeWidget_currentItemChanged(QTreeWidgetItem *current, QTreeWidgetItem *previous)
{
    QJsonValue jsonObj = current->data(0, Qt::UserRole).toJsonValue();

    QJsonValue::Type jsonType = jsonObj.type();

    switch(jsonType)
    {
    case QJsonValue::Bool:
        ui->boolButton->setChecked(jsonObj.toBool());
        break;
    case QJsonValue::Double:
        ui->doubleValue->setValue(jsonObj.toDouble());
        break;
    case QJsonValue::String:
        ui->stringEdit->document()->setPlainText(jsonObj.toString());
        break;
    case QJsonValue::Array:
        {
            QJsonArray arr = jsonObj.toArray();
            int count = arr.count();

            ui->arrayList->clear();

            for(int i = 0; i < count; ++i)
            {
                QString label = renderJsonValue(arr.at(i));
                ui->arrayList->addItem(label);
            }
        }
        break;
    case QJsonValue::Object:
        {
            QJsonObject obj = jsonObj.toObject();
            ui->objectTable->setRowCount(obj.count());
            int row = 0;
            for(QJsonObject::ConstIterator i = obj.begin(); i != obj.end(); ++i, ++row)
            {
                QTableWidgetItem *keyItem = new QTableWidgetItem(i.key());
                QJsonValue val = i.value();
                QTableWidgetItem *valItem = new QTableWidgetItem(renderJsonValue(val));
                ui->objectTable->setItem(row, 0, keyItem);
                ui->objectTable->setItem(row, 1, valItem);
            }
        }
        break;
    default:
        break;
    }

    ui->typeSelector->setCurrentIndex(jsonObj.type() - 1);
}
예제 #4
0
JsonTreeItem* JsonTreeItem::load(const QJsonValue& value,
                                 JsonTreeItem* parent) {
    JsonTreeItem * rootItem = new JsonTreeItem(parent);
    rootItem->setKey("root");
    if ( value.isObject()) {

        //Get all QJsonValue childs
        for (QString key : value.toObject().keys()){
            QJsonValue v = value.toObject().value(key);
            JsonTreeItem * child = load(v,rootItem);
            child->setKey(key);
            child->setType(v.type());
            rootItem->appendChild(child);

        }

    } else if ( value.isArray()) {
        //Get all QJsonValue childs
        int index = 0;
        for (QJsonValue v : value.toArray()){

            JsonTreeItem * child = load(v,rootItem);
            child->setKey(QString::number(index));
            child->setType(v.type());
            rootItem->appendChild(child);
            ++index;
        }
    } else {
        rootItem->setValue(value.toVariant().toString());
        rootItem->setType(value.type());
    }

    return rootItem;
}
예제 #5
0
QString MainWindow::renderJsonValue(QJsonValue obj)
{
    QString type = "unknown";
    QString value = "unknown";

    switch(obj.type())
    {
    case QJsonValue::Bool:
        type = "Bool";
        value = obj.toBool() ? "True" : "False";
        break;
    case QJsonValue::Double:
        type = "Double";
        value = QString::number(obj.toDouble());
        break;
    case QJsonValue::String:
        type = "String";
        value = "\""+obj.toString()+"\"";
        break;
    case QJsonValue::Array:
        type = "Array";
        value = "["+QString::number(obj.toArray().count())+"]";
        break;
    case QJsonValue::Object:
        type = "Object";
        value = "{"+QString::number(obj.toObject().count())+"}";
        break;
    default:
        break;
    }

    return value + " : " + type;
}
예제 #6
0
/*!
  */
QVariant SceneDocument::toVariant(const QJsonValue& value) noexcept
{
  QVariant node;
  switch (value.type()) {
   case QJsonValue::Null: {
    zisc::raiseError("The json value is null.");
    break;
   }
   case QJsonValue::Bool:
   case QJsonValue::Double:
   case QJsonValue::String: {
    node = value.toVariant();
    break;
   }
   case QJsonValue::Array: {
    node = toVariant(value.toArray());
    break;
   }
   case QJsonValue::Object: {
    node = toVariant(value.toObject());
    break;
   }
   case QJsonValue::Undefined: {
    zisc::raiseError("The json value is undefined.");
    break;
   }
   default: {
    zisc::raiseError("Undefined json value type is specified.");
    break;
   }
  }
  return node;
}
예제 #7
0
QJsonValue::Type QJsonValueProto::type() const
{
  QJsonValue *item = qscriptvalue_cast<QJsonValue*>(thisObject());
  if (item)
    return item->type();
  return QJsonValue::Undefined;
}
예제 #8
0
QJsonObject _getPropertySchema(const QString& name, const QJsonValue& value)
{
    switch (value.type())
    {
    case QJsonValue::Bool:
    case QJsonValue::Double:
    case QJsonValue::String:
        return _getValueSchema(value.type());
    case QJsonValue::Array:
        return _getArraySchema(name, value.toArray());
    case QJsonValue::Object:
        return _getObjectSchema(name, value.toObject());
    case QJsonValue::Null:
    case QJsonValue::Undefined:
    default:
        return {};
    }
}
예제 #9
0
void MainWindow::buildJsonTree(QTreeWidgetItem *parent, QJsonValue &obj, QString key = "")
{
    QTreeWidgetItem *toAdd = NULL;
    switch(obj.type())
    {
    case QJsonValue::Bool:
    case QJsonValue::Double:
    case QJsonValue::String:
    case QJsonValue::Undefined:
    case QJsonValue::Null:
        toAdd = createJsonTreeLeaf(parent, obj, key);
        break;
    case QJsonValue::Array:
    {
        toAdd = new QTreeWidgetItem(parent);
        QJsonArray array = obj.toArray();
        int count = array.count();
        toAdd->setText(0, key+"["+QString::number(count)+"]");

        for(int i = 0; i < count; ++i)
        {
            QJsonValue val = array.at(i);
            buildJsonTree(toAdd, val, QString::number(i)+" : ");
        }
        break;
    }
    case QJsonValue::Object:
    {
        toAdd = new QTreeWidgetItem(parent);
        QJsonObject object = obj.toObject();
        int count = object.count();
        toAdd->setText(0, key+"{"+QString::number(count)+"}");

        for(QJsonObject::ConstIterator i = object.begin(); i != object.end(); ++i)
        {
            QJsonValue val = i.value();
            buildJsonTree(toAdd, val, i.key()+" : ");
        }
        break;
    }
    default:
        break;
    }

    toAdd->setData(0, Qt::UserRole, QVariant(obj));
    parent->addChild(toAdd);
}
예제 #10
0
QString WebServer::JsonValueToString(QJsonValue val){
  //Note: Do not use this on arrays - only use this on single-value values
  QString out;
  switch(val.type()){
    case QJsonValue::Bool:
	out = (val.toBool() ? "true": "false"); break;
    case QJsonValue::Double:
	out = QString::number(val.toDouble()); break;
    case QJsonValue::String:
	out = val.toString(); break;
    case QJsonValue::Array:
	out = "\""+JsonArrayToStringList(val.toArray()).join("\" \"")+"\"";
    default:
	out.clear();
  }
  return out;
}
QString jsonParser::valueToString(QJsonValue value, QString defaultValue)
{
    switch (value.type())
    {
    case QJsonValue::Bool:
        if (value.toBool() == true)
            return "true";
        else return "false";
        break;
    case QJsonValue::Double:
        return QString::number(value.toDouble());
        break;
    case QJsonValue::String:
        return value.toString(defaultValue);
    default:
        return defaultValue;
    }
}
예제 #12
0
Nuria::Internal::JsonRpcRequest Nuria::Internal::JsonRpcUtil::dissectRequestObject (const QJsonObject &object) {
	static const QString jsonrpc2_0 = QStringLiteral("2.0");
	static const QString jsonrpcField = QStringLiteral("jsonrpc");
	static const QString methodField = QStringLiteral("method");
	static const QString paramsField = QStringLiteral("params");
	static const QString idField = QStringLiteral("id");
	static const QString pathField = QStringLiteral("path"); // Resource extension
	
	// Get values
	JsonRpcRequest result;
	QJsonValue jsonrpcValue = object.value (jsonrpcField);
	QJsonValue methodValue = object.value (methodField);
	QJsonValue paramsValue = object.value (paramsField);
	QJsonValue idValue = object.value (idField);
	QJsonValue pathValue = object.value (pathField);
	
	// Json-Rpc 2.0 sanity check of the "id" field
	if (idValue.type () == QJsonValue::Bool ||
	    idValue.type () == QJsonValue::Array ||
	    idValue.type () == QJsonValue::Object) {
		result.version = InvalidRequest;
	        return result;
		
	}
	
	// Store id now so we can reply with more precise error messages if needed.
	result.id = idValue;
	
	// Check other fields
	if (jsonrpcValue.type () != QJsonValue::String ||
	    methodValue.type () != QJsonValue::String ||
	    jsonrpcValue.toString () != jsonrpc2_0) {
		result.version = InvalidRequest;
		return result;
	}
	
	// This implementation needs the "params" field to be an object (if it exists)
	if (!paramsValue.isUndefined () && paramsValue.type () != QJsonValue::Object) {
		result.version = InvalidParams;
		return result;
	}
	
	// The request is at least a 2.0 request.
	result.version = JsonRpc2_0;
	
	// Check that if "path" exists it's a string. In this case, it's a
	// request with the Resource extension.
	if (!pathValue.isUndefined ()) {
		if (pathValue.isString ()) {
			result.version = JsonRpc2_0_Resource;
			result.path = pathValue.toString (); // Store 'path'
		} else {
			result.version = InvalidRequest;
			return result;
		}
		
	}
	
	// Fill 'result'
	result.method = methodValue.toString ();
	result.params = paramsValue.toObject ().toVariantMap ();
	return result;
}
void RawPacketDecoder::_asyncWorkerProc()
{
    while(true){
        std::pair<std::shared_ptr<PGENETLL_Session>, std::string> nextPacketPart = m_incomingPackets->pop();
        if(m_incomingPackets->shouldExit())
            return;

        // Load the json content
        QJsonParseError possibleError;

        QJsonDocument data = QJsonDocument::fromJson(QByteArray(nextPacketPart.second.c_str(), nextPacketPart.second.size()), &possibleError);
        if(possibleError.error != QJsonParseError::NoError){
            gThreadedLogger->logWarning("Failed to parse JSON packet: " + possibleError.errorString());
            continue;
        }

        QJsonValue headerValue = data.object().value("header");
        if(headerValue.type() != QJsonValue::Object){
            gThreadedLogger->logWarning("JSON Error: header doesn't exist or has wrong type! The header value is type-id: " + (int)headerValue.type());
            continue;
        }
        QJsonObject headerObject = headerValue.toObject();

        QJsonValue packetValue = data.object().value("packet");
        if(packetValue .type() != QJsonValue::Object){
            gThreadedLogger->logWarning("JSON Error: packet doesn't exist or has wrong type! The header value is type-id: " + (int)packetValue.type());
            continue;
        }
        QJsonObject packetObject = packetValue.toObject();

        // QDataStream packetStream(QByteArray(nextPacketPart.second.c_str(), nextPacketPart.second.size()));

        int packetID;
        QString username;
        int sessionID;

        if(!headerObject.contains("packetID")){
            gThreadedLogger->logWarning("JSON Error: header does not have key \"packetID\"");
            continue;
        }
        if(!headerObject.value("packetID").isDouble()){
            gThreadedLogger->logWarning("JSON Error: header does not have key \"packetID\" with value double. Instead the type is: " + (int)headerObject.value("packetID").type());
            continue;
        }


        if(!headerObject.contains("username")){
            gThreadedLogger->logWarning("JSON Error: header does not have key \"username\"");
            continue;
        }
        if(!headerObject.value("username").isString()){
            gThreadedLogger->logWarning("JSON Error: header does not have key \"username\" with value string. Instead the type is: " + (int)headerObject.value("username").type());
            continue;
        }


        if(!headerObject.contains("sessionID")){
            gThreadedLogger->logWarning("JSON Error: header does not have key \"sessionID\"");
            continue;
        }
        if(!headerObject.value("sessionID").isDouble()){
            gThreadedLogger->logWarning("JSON Error: header does not have key \"sessionID\" with value double. Instead the type is: " + (int)headerObject.value("sessionID").type());
            continue;
        }

        packetID = (int)headerObject.value("packetID").toDouble();
        username = headerObject.value("username").toString();
        sessionID = (int)headerObject.value("sessionID").toDouble();

        std::cout << "Incoming Packet (with valid header): " << std::endl;
        std::cout << "packetID: " << packetID << std::endl;
        std::cout << "username: "******"sessionID: " << sessionID << std::endl;
        std::cout << std::endl;


        Packet* newPacket = m_packetRegister->createPacketById(static_cast<PacketID>(packetID));
        if(newPacket == nullptr){
            std::cout << "Invalid Packet!" << std::endl;
            continue;
        }
        newPacket->setUser(m_userManager->getUserByName(username));
        newPacket->setSessionID(sessionID);
        newPacket->decode(packetObject);

        if(username.isEmpty()){
            m_fullPacketsUnindentified->push(make_pair(nextPacketPart.first, newPacket));
        }else{
            m_fullPackets->push(newPacket);
        }

    }
}
예제 #14
0
//------------------------------------------------------------------------------
// Name: toJson
//------------------------------------------------------------------------------
QString QJsonDocument::toJson(const QJsonValue &v, JsonFormat format) const {

	QString b;
	QTextStream ss(&b, QIODevice::WriteOnly | QIODevice::Text);

	switch(v.type()) {
	case QJsonValue::Null:
		ss << "null";
		break;
	case QJsonValue::Bool:
		ss << (v.toBool() ? "true" : "false");
		break;
	case QJsonValue::Double:
		ss << v.toDouble();
		break;
	case QJsonValue::String:
		ss << '"' << escapeString(v.toString()) << '"';
		break;
	case QJsonValue::Array:
		{
			const QJsonArray a = v.toArray();
			ss << "[";
			if(!a.empty()) {
				QJsonArray::const_iterator it = a.begin();
				QJsonArray::const_iterator e  = a.end();

				ss << toJson(*it++, format);

				for(;it != e; ++it) {
					ss << ',';
					ss << toJson(*it, format);
				}
			}
			ss << "]";
		}
		break;
	case QJsonValue::Object:
		{
			const QJsonObject o = v.toObject();
			ss << "{";
			if(!o.empty()) {
				QJsonObject::const_iterator it = o.begin();
				QJsonObject::const_iterator e  = o.end();

				ss << '"' << escapeString(it.key()) << "\": " << toJson(it.value(), format);
				++it;
				for(;it != e; ++it) {
					ss << ',';
					ss << '"' << escapeString(it.key()) << "\": " << toJson(it.value(), format);
				}
			}
			ss  << "}";
		}
		break;
	case QJsonValue::Undefined:
		Q_ASSERT(0);
		break;
	}

	return b;
}
예제 #15
0
static bool matches(const QJsonObject &object,
                    const QString &osName,
                    const QVersionNumber &kernelVersion,
                    const QOpenGLConfig::Gpu &gpu)
{
    const OsTypeTerm os = OsTypeTerm::fromJson(object.value(osKey()));
    if (!os.isNull() && !os.matches(osName, kernelVersion))
        return false;

    const QJsonValue exceptionsV = object.value(exceptionsKey());
    if (exceptionsV.isArray()) {
        const QJsonArray exceptionsA = exceptionsV.toArray();
        for (JsonArrayConstIt it = exceptionsA.constBegin(), cend = exceptionsA.constEnd(); it != cend; ++it) {
            if (matches(it->toObject(), osName, kernelVersion, gpu))
                return false;
        }
    }

    const QJsonValue vendorV = object.value(vendorIdKey());
    if (vendorV.isString()) {
        if (gpu.vendorId != vendorV.toString().toUInt(Q_NULLPTR, /* base */ 0))
            return false;
    } else {
        if (object.contains(glVendorKey())) {
            const QByteArray glVendorV = object.value(glVendorKey()).toString().toUtf8();
            if (!gpu.glVendor.contains(glVendorV))
                return false;
        }
    }

    if (gpu.deviceId) {
        const QJsonValue deviceIdV = object.value(deviceIdKey());
        switch (deviceIdV.type()) {
        case QJsonValue::Array:
            if (!contains(deviceIdV.toArray(), gpu.deviceId))
                return false;
            break;
        case QJsonValue::Undefined:
        case QJsonValue::Null:
            break;
        default:
            qWarning().noquote()
                << msgSyntaxWarning(object,
                                    QLatin1String("Device ID must be of type array."));
        }
    }
    if (!gpu.driverVersion.isNull()) {
        const QJsonValue driverVersionV = object.value(driverVersionKey());
        switch (driverVersionV.type()) {
        case QJsonValue::Object:
            if (!VersionTerm::fromJson(driverVersionV).matches(gpu.driverVersion))
                return false;
            break;
        case QJsonValue::Undefined:
        case QJsonValue::Null:
            break;
        default:
            qWarning().noquote()
                << msgSyntaxWarning(object,
                                    QLatin1String("Driver version must be of type object."));
        }
    }
    return true;
}
예제 #16
0
AppInfo AppInfo::fromPath(const QString &path)
{
    AppInfo info(Bundle::fromPath(path));

    if (!static_cast<Bundle>(info).isValid()) {
        qCWarning(l) << "bundle" << path << "is not valid";
        return AppInfo();
    }

    QScopedPointer<QIODevice> appInfoJSON(info.openFile(AppInfo::INFO, QIODevice::Text));
    if (!appInfoJSON) {
        qCWarning(l) << "cannot find app" << path << "info json";
        return AppInfo();
    }

    QJsonParseError parseError;
    QJsonDocument doc = QJsonDocument::fromJson(appInfoJSON->readAll(), &parseError);
    if (parseError.error != QJsonParseError::NoError) {
        qCWarning(l) << "cannot parse app" << path << "info json" << parseError.errorString();
        return AppInfo();
    }
    appInfoJSON->close();

    const QJsonObject root = doc.object();
    info.d->uuid = QUuid(root["uuid"].toString());
    info.d->shortName = root["shortName"].toString();
    info.d->longName = root["longName"].toString();
    info.d->companyName = root["companyName"].toString();
    info.d->versionCode = root["versionCode"].toInt();
    info.d->versionLabel = root["versionLabel"].toString();

    const QJsonObject watchapp = root["watchapp"].toObject();
    info.d->watchface = watchapp["watchface"].toBool();

    info.d->jskit = info.fileExists(AppInfo::APPJS);

    if (root.contains("capabilities")) {
        const QJsonArray capabilities = root["capabilities"].toArray();
        AppInfo::Capabilities caps = 0;
        for (auto it = capabilities.constBegin(); it != capabilities.constEnd(); ++it) {
            QString cap = (*it).toString();
            if (cap == "location") caps |= AppInfo::Location;
            if (cap == "configurable") caps |= AppInfo::Configurable;
        }
        info.d->capabilities = caps;
    }

    if (root.contains("appKeys")) {
        const QJsonObject appkeys = root["appKeys"].toObject();
        for (auto it = appkeys.constBegin(); it != appkeys.constEnd(); ++it) {
            info.addAppKey(it.key(), it.value().toInt());
        }
    }

    if (root.contains("resources")) {
        const QJsonObject resources = root["resources"].toObject();
        const QJsonArray media = resources["media"].toArray();
        int index = 0;

        for (auto it = media.constBegin(); it != media.constEnd(); ++it) {
            const QJsonObject res = (*it).toObject();
            const QJsonValue menuIcon = res["menuIcon"];

            switch (menuIcon.type()) {
            case QJsonValue::Bool:
                info.d->menuIcon = menuIcon.toBool();
                info.d->menuIconResource = index;
                break;
            case QJsonValue::String:
                info.d->menuIcon = !menuIcon.toString().isEmpty();
                info.d->menuIconResource = index;
                break;
            default:
                break;
            }

            index++;
        }
    }

    if (info.uuid().isNull() || info.shortName().isEmpty()) {
        qCWarning(l) << "invalid or empty uuid/name in json of" << path;
        return AppInfo();
    }

    return info;
}