Ejemplo n.º 1
0
void MainWindow::m_updateMessages(QJsonArray messages)
{
    qDebug("MainWindow::m_updateMessages");

    unsigned int count = messages.count();
    m_messagesReceived += count;

    qDebug("MainWindow::m_updateMessages count: %d", count);

    QJsonArray::iterator iter = messages.end();
    for ( ; iter >= messages.begin(); --iter)
    {
        qDebug("m_updateMessages isObject: %d", (*iter).isObject());

        qDebug("m_updateMessages type: 0x%x", (*iter).type());

        QJsonObject jMessage = (*iter).toObject();

        QJsonDocument doc(jMessage);
        qDebug("m_updateMessages doc: %s", doc.toJson().toStdString().c_str());

        QJsonValue message = jMessage["message"];
        qDebug("MainWindow::m_updateMessages message: %s", message.toString().toStdString().c_str());

        QString prevText = ui->messageView->toPlainText();
        prevText += message.toString() + "\r\n";
        ui->messageView->setPlainText(prevText);
    }

}
Ejemplo n.º 2
0
static Nuria::JsonMetaObjectReader::Error parseMethodArgumentList (const QJsonArray &names, const QJsonArray &types,
								   QVector< QByteArray > &outNames,
								   QVector< QByteArray > &outTypes) {
	if (names.size () != types.size ()) {
		return Nuria::JsonMetaObjectReader::MethodArgumentsHaveDifferentLengths;
	}
	
	// 
	for (int i = 0; i < names.size (); i++) {
		QJsonValue curName = names.at (i);
		QJsonValue curType = types.at (i);
		
		if (!curName.isString ()) return Nuria::JsonMetaObjectReader::MethodArgumentNamesContainsNonString;
		if (!curType.isString ()) return Nuria::JsonMetaObjectReader::MethodArgumentTypesContainsNonString;
		
		// 
		outNames.append (curName.toString ().toLatin1 ());
		outTypes.append (curType.toString ().toLatin1 ());
		
	}
	
	// 
	return Nuria::JsonMetaObjectReader::NoError;
	
}
Ejemplo n.º 3
0
void CRootTreeItem::receiveListing()
{
    DEBUG << "receiveListing(): path:" << m_path;

    QNetworkReply *reply = static_cast<QNetworkReply*>(sender());

    QByteArray data = reply->readAll();

    QJsonParseError error;
    QJsonDocument doc = QJsonDocument:: fromJson(data, &error);

    QJsonObject obj = doc.object();

    QJsonArray arr = obj.value("user_node_paths").toArray();

    for(int i=0, count=arr.size(); i<count; i++) {
        QJsonValue v = arr.at(i);
        CTreeItem *item = new CTreeItem(v.toString(), v.toString(), this);
        item->setIsFile(false);
        item->setHasChildren(true);
        //item->refresh();
        appendChild(item);
    }

    emit refreshed();
}
Ejemplo n.º 4
0
bool LinkedDB::isValidCredentials(const Username& u) const{
    std::string _user = u.getLogin();
    std::string _pass = u.getPassword();

    QString val;
    QFile file;
    file.setFileName("db.json");
    if (!file.exists()) {
        throw MyExc(database, "DB file does not exists!");
    }
    if (!file.open(QIODevice::ReadOnly)) {
        throw MyExc(database, "an error as occurred while reading the DB!");
    }
    else{
//QTextStream(stdout)<<"loading file!\n";                 //solo x debug
    }
    val = file.readAll();
    file.close();

    QJsonDocument doc = QJsonDocument::fromJson(val.toUtf8());
    QJsonObject all_json = doc.object();
    QJsonValue all_users = all_json["users"];
    QJsonArray users_array = all_users.toArray();
    for(QJsonArray::const_iterator it = users_array.begin(); it!=users_array.end(); ++it){
        QJsonValue test = *it;
        QJsonObject obj = test.toObject();
        QJsonValue user = obj["username"];
        QJsonValue pass = obj["password"];

        if(_user == user.toString().toStdString() && _pass == pass.toString().toStdString()){
            return true;
        }
    }
    return false;
}
Ejemplo n.º 5
0
    void EtherIPC::handleGetNetVersion() {
        QJsonValue jv;
        if ( !readReply(jv) ) {
            return bail();
        }

        bool ok = false;
        fNetVersion = jv.toString().toInt(&ok);

        if ( !ok ) {
            setError("Unable to parse net version string: " + jv.toString());
            return bail(true);
        }

        emit netVersionChanged(fNetVersion);
        done();

        fTimer.start(); // should happen after filter creation, might need to move into last filter response handler
        // if we connected to external geth, put that info in geth log

        emit startingChanged(fStarting);
        emit connectToServerDone();
        emit connectionStateChanged();
        emit hardForkReadyChanged(getHardForkReady());
    }
Ejemplo n.º 6
0
void Repository::requestedDataReceived(const QByteArray& data) noexcept {
  QJsonDocument doc = QJsonDocument::fromJson(data);
  if (doc.isNull() || doc.isEmpty() || (!doc.isObject())) {
    emit errorWhileFetchingLibraryList(
        tr("Received JSON object is not valid."));
    return;
  }
  QJsonValue nextResultsLink = doc.object().value("next");
  if (nextResultsLink.isString()) {
    QUrl url = QUrl(nextResultsLink.toString());
    if (url.isValid()) {
      qDebug() << "Request more results from repository:" << url.toString();
      requestLibraryList(url);
    } else {
      qWarning() << "Invalid URL in received JSON object:"
                 << nextResultsLink.toString();
    }
  }
  QJsonValue reposVal = doc.object().value("results");
  if ((reposVal.isNull()) || (!reposVal.isArray())) {
    emit errorWhileFetchingLibraryList(
        tr("Received JSON object does not contain "
           "any results."));
    return;
  }
  emit libraryListReceived(reposVal.toArray());
}
bool TestClusterModel::loadFromFile(const QString& fileName) {
    QFile file(fileName);
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        return false;
    }
    QByteArray bytes = file.readAll();
    file.close();
    QJsonParseError parseError;
    QJsonDocument doc = QJsonDocument::fromJson(bytes, &parseError);
    if (parseError.error != QJsonParseError::NoError) {
        return false;
    }
    if (!doc.isArray()) {
        return false;
    }
    QList<HostInfo> newHosts;
    QJsonArray array = doc.array();
    for (const QJsonValue& value : array) {
        HostInfo info;
        QJsonObject object = value.toObject();
        QJsonValue typeVal = object["type"];
        if (!typeVal.isString()) {
            return false;
        }
        int type = findHostTypeByInternalName(typeVal.toString().toUtf8().data());
        if (type < 0) {
            return false;
        }
        info.type = (HostType)type;
        QJsonValue portVal = object["port"];
        if (!portVal.isDouble()) {
            return false;
        }
        info.port = static_cast<int>(portVal.toDouble());
        QJsonValue dbPathVal = object["dbPath"];
        if (dbPathVal.isString()) {
            info.dbPath = dbPathVal.toString();
        }
        QJsonValue replicaSetVal = object["replicaSet"];
        if (replicaSetVal.isString()) {
            info.replicaSet = replicaSetVal.toString();
        }
        QJsonValue configDBVal = object["configDB"];
        if (configDBVal.isString()) {
            info.configDB = configDBVal.toString();
        }
        newHosts.append(info);
    }
    for (HostInfo& info : newHosts) {
        info.process = new QProcess(this);
        info.state = QProcess::NotRunning;
    }
    beginInsertRows(QModelIndex(), 0, newHosts.size() - 1);
    _hosts = newHosts;
    endInsertRows();
    _fileName = fileName;
    _dirty = false;
    return true;
}
Ejemplo n.º 8
0
static inline QString jsonToString(const QJsonValue &value, 
                                   const QMap<QString, QJsonValue> &defines)
{
    QString valueString = value.toString();
    if (defines.contains(valueString)) {
        return defines.value(valueString).toString();
    }
    return value.toString();
}
Ejemplo n.º 9
0
void NetworkManager::processJson(QString json)
{
    //log("Json received : " + json);

    // Parse main parts of the message (type and body)

    QJsonDocument doc; doc = doc.fromJson(json.toUtf8());
    QString type = doc.object().take("type").toString();
    QJsonValue body = doc.object().take("body");

    // Routing messages by type

    if ( type == "hbAck" ){

        emit hearthbeatReceived(body.toString());
    }
    else if ( type == "setVariable" ){

        QString variable = body.toObject().take("variable").toString();
        QString option = body.toObject().take("option").toString();
        QString json = QJsonDocument( body.toObject().take("value").toObject() ).toJson();

        emit systemVariableChanged(variable, option, json);
    }
    else if ( type == "call" ){

            QString module = body.toObject().take("module").toString();
            QString function = body.toObject().take("function").toString();
            if (function == "")
                function = body.toObject().take("fct").toString();
            QString params = QJsonDocument( body.toObject().take("param").toArray() ).toJson();

            emit callRequest(module, function, params);
    }
    else if ( type == "ssid" ){

        setssid(body.toString());

        setLoggedState(true);
    }
    else if ( type == "login-error" ){

        log("Login error : " + body.toString());
        setLoggedState(false);
    }
    else if ( type == "error"){

        log("Server error : " + body.toString());
    }
    else{

        emit jsonReceived(type, body);
        emit jsonStringReceived(json);
    }
}
bool feedBackMessage::loadfromJson(QByteArray textJson)
{
    QJsonParseError jsonParseError;
    QJsonDocument jsonDocument = QJsonDocument::fromJson(textJson, &jsonParseError);
    if(jsonParseError.error == QJsonParseError::NoError)
    {
        if(jsonDocument.isObject())
        {

            QJsonObject jsonObject = jsonDocument.object();
            if(jsonObject.contains("username"))
            {
                QJsonValue jsonValue = jsonObject.take("username");
                if(jsonValue.isString())
                {
                    user = jsonValue.toString();
                }
                else
                {
                    return false;
                }
            }
            else
            {
                return false;
            }
            if(jsonObject.contains("status"))
            {
                QJsonValue jsonValue = jsonObject.take("status");
                if(jsonValue.isString())
                {
                    stat = jsonValue.toString();
                }
                else
                {
                    return false;
                }
            }
            else
            {
                return false;
            }
        }
        else
        {
            return false;
        }
    }
    else
    {
        return false;
    }
    return true;
}
Ejemplo n.º 11
0
void GameUpQtPrivate::doUpdateGamerData() {
    if (lasterror == QNetworkReply::NoError && lastData.size() > 0) {
        QJsonDocument jsdoc = QJsonDocument::fromJson(lastData);
        QJsonObject jobj = jsdoc.object();
        QJsonValue nickvalue = jobj.value(QString("nickname"));
        QJsonValue namevalue = jobj.value(QString("name"));
        QJsonValue createdvalue = jobj.value(QString("created_at"));
        m_gamer.setNickname(nickvalue.toString());
        m_gamer.setName(namevalue.toString());
        m_gamer.setCreatedAt(QDateTime::fromMSecsSinceEpoch(static_cast<qint64>(createdvalue.toDouble())));
    }
}
Ejemplo n.º 12
0
Goods *Parser::ParseGoods(const QJsonObject &jGoods) {
    QJsonValue jValue;

    // barcode
    jValue = jGoods.value("barcode");
    if (jValue.isUndefined() || !jValue.isString()) {
        return NULL;
    }
    QString strBarcode = jValue.toString();

    // name
    jValue = jGoods.value("name");
    if (jValue.isUndefined() || !jValue.isString()) {
        return NULL;
    }
    QString strName = jValue.toString();

    // unit
    jValue = jGoods.value("unit");
    if (jValue.isUndefined() || !jValue.isString()) {
        return NULL;
    }
    QString strUnit = jValue.toString();

    // category
    jValue = jGoods.value("category");
    if (jValue.isUndefined() || !jValue.isString()) {
        return NULL;
    }
    QString strCategory = jValue.toString();

    // subCategory
    jValue = jGoods.value("subCategory");
    if (jValue.isUndefined() || !jValue.isString()) {
        return NULL;
    }
    QString strSubCategory = jValue.toString();

    // price
    jValue = jGoods.value("price");
    if (jValue.isUndefined() || !jValue.isDouble()) {
        return NULL;
    }
    float fPrice = (float)jValue.toDouble();

    // new a goods object
    Goods *pGoods = new Goods(strBarcode, strName);
    pGoods->SetCategory(strCategory, strSubCategory);
    pGoods->SetQuantUnit(strUnit);
    pGoods->SetUnitPrice(fPrice);

    return pGoods;
}
Ejemplo n.º 13
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);
            }
        }
    }
BlockOption BlockOption_fromJson(QJsonValue node, bool *ok) {
    bool success = true;
    bool callSuccess;
    QJsonObject nodeObj = node.toObject();
    QJsonValue displayNameVal = nodeObj["displayName"];
    if (!displayNameVal.isString()) {
        success = false;
    }
    QString displayName = displayNameVal.toString();
    QJsonValue defaultValueVal = nodeObj["defaultValue"];
    if (!defaultValueVal.isString()) {
        success = false;
    }
    QString defaultValue = defaultValueVal.toString();
    BlockOptionType type = BlockOptionType_fromJson(nodeObj["type"], &callSuccess);
    if (!callSuccess) {
        success = false;
    }
    BlockOption result;
    QMap<QString, QString> choices;
    QJsonValue minimumVal;
    int minimum;
    QJsonValue maximumVal;
    int maximum;
    switch (type) {
    case BLOCK_OPTION_TYPE_COMBOBOX:
        choices = QMap_QString_QString_fromJson(nodeObj["choices"], &callSuccess);
        if (!callSuccess) {
            success = false;
        }
        result = BlockOption::makeComboBox(displayName, defaultValue, choices);
        break;
    case BLOCK_OPTION_TYPE_INTEGER:
        minimumVal = nodeObj["minimum"];
        if (!minimumVal.isDouble() || (minimumVal.toInt() != minimumVal.toDouble())) {
            success = false;
        }
        minimum = minimumVal.toInt();
        maximumVal = nodeObj["maximum"];
        if (!maximumVal.isDouble() || (maximumVal.toInt() != maximumVal.toDouble())) {
            success = false;
        }
        maximum = maximumVal.toInt();
        result = BlockOption::makeInteger(displayName, defaultValue, minimum, maximum);
        break;
    }
    if (ok) {
        *ok = success;
    }
    return result;
}
Ejemplo n.º 15
0
bool MedNUSStoryManager::loadStoryFile(QString storyFile)
{
    QString dir = QDir::homePath();
    dir.append(storyFile);

    QFile file(dir);
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        qWarning() << "Unable to open file.";
        return false;
    }

    QJsonDocument doc = QJsonDocument::fromJson(file.readAll());
    QJsonObject obj = doc.object();
    QJsonValue jsonValue = obj.value(QString("videoFile"));
    videoFileName = jsonValue.toString();

    jsonValue = obj.value(QString("3DFile"));
    modelFileName = jsonValue.toString();

    jsonValue = obj.value(QString("PDFFile"));
    pdfFileName = jsonValue.toString();

    jsonValue = obj.value(QString("timeline"));
    QJsonArray timelineDetails = jsonValue.toArray();

    for(int i = 0; i < timelineDetails.size(); i++)
    {
        obj = timelineDetails[i].toObject();

        StoryPoint temp;
        temp.timestamp = qint64(obj.value(QString("timestamp")).toString().toLongLong());
        temp.slideNum = obj.value(QString("slide")).toInt();

        QJsonArray posArray = obj.value(QString("cameraPosition")).toArray();
        QJsonArray focArray = obj.value(QString("cameraFocalPoint")).toArray();
        QJsonArray vupArray = obj.value(QString("cameraViewUp")).toArray();
        for(int i = 0; i<3; i++)
        {
            temp.cameraPosition[i] =  posArray[i].toDouble();
            temp.cameraFocalPoint[i] = focArray[i].toDouble();
            temp.cameraViewUp[i] = vupArray[i].toDouble();
        }

        temp.cameraViewAngle = obj.value(QString("cameraViewAngle")).toInt();
        storyPointList->push_back(temp);
    }

    return true;
}
Ejemplo n.º 16
0
void QPubNub::onSubscribeReadyRead() {
  QNetworkReply * reply = qobject_cast<QNetworkReply*>(sender());
  QJsonArray response;
  if (handleResponse(reply, response)) {
    return;
  }
  QJsonValue firstElement(response.at(0));
  if (!firstElement.isArray()) {
    emit error("First element of response is not an JSON array", 0);
    subscribe();
  }
  
  QJsonValue timeTokenElement = response.at(1);
  if (!timeTokenElement.isString()) {
    emit error("Second element of response is not a string", 0);
    subscribe();
  }
  m_timeToken = timeTokenElement.toString();
  QJsonValue channelListString = response.at(2);
  QStringList channels;
  QJsonArray messages = firstElement.toArray();
  if (channelListString.isString()) {
    channels = channelListString.toString().split(',');
  } else {
    int len = messages.isEmpty() ? 0 : messages.size();
    for (int i = 0; i < len; i++)
    {
        channels << m_channelUrlPart;
    }
  }
  if (messages.isEmpty()) {
    emit connected();
  } else {
#ifdef Q_PUBNUB_CRYPT
    if (m_cipherKey.isEmpty()) {
      for (int i=0,len=messages.size();i<len;++i) {
        emit message(messages[i], m_timeToken, channels[i]);
      }
    } else {
      decrypt(messages, channels);
    }
  #else
    for (int i=0,len=messages.size();i<len;++i) {
      emit message(messages[i], m_timeToken, channels[i]);
    }
#endif // Q_PUBNUB_CRYPT
  }
  subscribe();
}
Ejemplo n.º 17
0
bool MessageFacade::obtainRaidAndDataStructure(QJsonObject *root, QString *pRaid, QString *pDataStructure)
{
    QJsonValue jsonValue = root->value(RAID_TYPE);
    bool success = false;
    if (!jsonValue.isUndefined() && jsonValue.isString()){
        *pRaid = jsonValue.toString();
        success = StorageblockFacade::getInstance()->isValidRaid(*pRaid);
    }
    jsonValue = root->value(DATASTRUCTURE_TYPE);
    if (!jsonValue.isUndefined() && jsonValue.isString()){
        *pDataStructure=jsonValue.toString();
        success = success&&StorageblockFacade::getInstance()->isValidDataStructure(*pDataStructure);
    }
    return success;
}
Ejemplo n.º 18
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;
}
void EnginioBackendConnection::onEnginioFinished(EnginioReply *reply)
{
    struct ReplyScope {
        EnginioReply *_reply;
        ReplyScope(EnginioReply *r) : _reply(r) { }
        ~ReplyScope() { _reply->deleteLater(); }
    } scope(reply);

    if (reply->isError()) {
        qDebug() << "\n\n### EnginioBackendConnection ERROR";
        qDebug() << reply->errorString();
        reply->dumpDebugInfo();
        qDebug() << "\n###\n";
        return;
    }

    QJsonValue urlValue = reply->data()[EnginioString::expiringUrl];

    if (!urlValue.isString()) {
        qDebug() << "## Retrieving connection url failed.";
        return;
    }

    qDebug() << "## Initiating WebSocket connection.";

    _socketUrl = QUrl(urlValue.toString());
    _tcpSocket->connectToHost(_socketUrl.host(), _socketUrl.port(8080));
}
Ejemplo n.º 20
0
AnimNode::Pointer AnimNodeLoader::load(const QByteArray& contents, const QUrl& jsonUrl) {

    // convert string into a json doc
    QJsonParseError error;
    auto doc = QJsonDocument::fromJson(contents, &error);
    if (error.error != QJsonParseError::NoError) {
        qCCritical(animation) << "AnimNodeLoader, failed to parse json, error =" << error.errorString();
        return nullptr;
    }
    QJsonObject obj = doc.object();

    // version
    QJsonValue versionVal = obj.value("version");
    if (!versionVal.isString()) {
        qCCritical(animation) << "AnimNodeLoader, bad string \"version\"";
        return nullptr;
    }
    QString version = versionVal.toString();

    // check version
    // AJT: TODO version check
    if (version != "1.0" && version != "1.1") {
        qCCritical(animation) << "AnimNodeLoader, bad version number" << version << "expected \"1.0\"";
        return nullptr;
    }

    // root
    QJsonValue rootVal = obj.value("root");
    if (!rootVal.isObject()) {
        qCCritical(animation) << "AnimNodeLoader, bad object \"root\"";
        return nullptr;
    }

    return loadNode(rootVal.toObject(), jsonUrl);
}
Ejemplo n.º 21
0
/*!
    \internal
 */
void Value::copyData(const QJsonValue &v, char *dest, bool compressed)
{
    switch (v.t) {
    case QJsonValue::Double:
        if (!compressed) {
            qToLittleEndian(v.ui, (uchar *)dest);
        }
        break;
    case QJsonValue::String: {
        QString str = v.toString();
        QJsonPrivate::copyString(dest, str, compressed);
        break;
    }
    case QJsonValue::Array:
    case QJsonValue::Object: {
        const QJsonPrivate::Base *b = v.base;
        if (!b)
            b = (v.t == QJsonValue::Array ? &emptyArray : &emptyObject);
        memcpy(dest, b, b->size);
        break;
    }
    default:
        break;
    }
}
Ejemplo n.º 22
0
/*!
    \internal
 */
int Value::requiredStorage(const QJsonValue &v, bool *compressed)
{
    *compressed = false;
    switch (v.t) {
    case QJsonValue::Double:
        if (QJsonPrivate::compressedNumber(v.dbl) != INT_MAX) {
            *compressed = true;
            return 0;
        }
        return sizeof(double);
    case QJsonValue::String: {
        QString s = v.toString();
        *compressed = QJsonPrivate::useCompressed(s);
        return QJsonPrivate::qStringSize(s, *compressed);
    }
    case QJsonValue::Array:
    case QJsonValue::Object:
        return v.base ? v.base->size : sizeof(QJsonPrivate::Base);
    case QJsonValue::Undefined:
    case QJsonValue::Null:
    case QJsonValue::Bool:
        break;
    }
    return 0;
}
Ejemplo n.º 23
0
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;
}
Ejemplo n.º 24
0
QString JsonObject::string(const QString& key) const {
    checkContains(key);
    QJsonValue value = o.value(key);
    if ( ! value.isString())
        wrongType("string", key);
    return value.toString();
}
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;
}
Ejemplo n.º 26
0
ActionsManager::ActionEntryDefinition ToolBarsManager::decodeEntry(const QJsonValue &value)
{
	ActionsManager::ActionEntryDefinition definition;

	if (value.isString())
	{
		definition.action = value.toString();

		return definition;
	}

	const QJsonObject object(value.toObject());

	definition.action = object.value(QLatin1String("identifier")).toString();
	definition.options = object.value(QLatin1String("options")).toObject().toVariantMap();

	if (object.contains(QLatin1String("actions")))
	{
		const QJsonArray actions(object.value(QLatin1String("actions")).toArray());

		for (int i = 0; i < actions.count(); ++i)
		{
			definition.entries.append(decodeEntry(actions.at(i)));
		}
	}

	return definition;
}
Ejemplo n.º 27
0
void MessageFacade::interpretMessage(QString pMessage, ControllerNode *pControllerNode)
{
    mut.lock();
    QJsonObject root;
    // se llama al decifrador
    pMessage = decrypt(pMessage);
    QString messageType;
    //se veridica si cumple con el formato JSON
    if (isValidJsonSyntax(pMessage,&root)){
        //Verifica el tipo de mensaje
        QJsonValue jsonValue = root.value(MESSAGE_TYPE);
        if (!jsonValue.isUndefined() && jsonValue.isString()) {
            messageType = jsonValue.toString();
            //para mensajes de tipo storage block
            if (messageType.compare(MESSAGE_TYPE_STORAGE_BLOCK) == 0){
                interpretStorageBlockMessage(&root,pControllerNode);
            }
            //para mensajes que operen sobre los registros
            else if (messageType.compare(MESSAGE_TYPE_REGISTER) == 0){
                interpretRegisterkMessage(&root,pControllerNode);
            }
            //para mensajes que operen sobre los usarios
            else if (messageType.compare(MESSAGE_TYPE_USER) == 0){
                interpretUserMessage(&root,pControllerNode);
            }
        }
    }
    mut.unlock();

}
Ejemplo n.º 28
0
/*!
    \internal
 */
int Value::requiredStorage(QJsonValue &v, bool *compressed)
{
    *compressed = false;
    switch (v.t) {
    case QJsonValue::Double:
        if (QJsonPrivate::compressedNumber(v.dbl) != INT_MAX) {
            *compressed = true;
            return 0;
        }
        return sizeof(double);
    case QJsonValue::String: {
        QString s = v.toString();
        *compressed = QJsonPrivate::useCompressed(s);
        return QJsonPrivate::qStringSize(s, *compressed);
    }
    case QJsonValue::Array:
    case QJsonValue::Object:
        if (v.d && v.d->compactionCounter) {
            v.detach();
            v.d->compact();
            v.base = static_cast<QJsonPrivate::Base *>(v.d->header->root());
        }
        return v.base ? v.base->size : sizeof(QJsonPrivate::Base);
    case QJsonValue::Undefined:
    case QJsonValue::Null:
    case QJsonValue::Bool:
        break;
    }
    return 0;
}
Ejemplo n.º 29
0
QDebug operator<<(QDebug dbg, const QJsonValue &o)
{
    switch (o.t) {
    case QJsonValue::Undefined:
        dbg.nospace() << "QJsonValue(undefined)";
        break;
    case QJsonValue::Null:
        dbg.nospace() << "QJsonValue(null)";
        break;
    case QJsonValue::Bool:
        dbg.nospace() << "QJsonValue(bool, " << o.toBool() << ")";
        break;
    case QJsonValue::Double:
        dbg.nospace() << "QJsonValue(double, " << o.toDouble() << ")";
        break;
    case QJsonValue::String:
        dbg.nospace() << "QJsonValue(string, " << o.toString() << ")";
        break;
    case QJsonValue::Array:
        dbg.nospace() << "QJsonValue(array, ";
        dbg.nospace() << o.toArray();
        dbg.nospace() << ")";
        break;
    case QJsonValue::Object:
        dbg.nospace() << "QJsonValue(object, ";
        dbg.nospace() << o.toObject();
        dbg.nospace() << ")";
        break;
    }
    return dbg.space();
}
Ejemplo n.º 30
0
void MainWindow::getLastQuote(const QString& _symbol)
{
    QTcpSocket* _tcpMainSocket = new QTcpSocket(this);
    QByteArray byte = _symbol.toUtf8();
    _tcpMainSocket->connectToHost("finance.google.com", 80);

    connect(_tcpMainSocket, &QTcpSocket::connected, [_tcpMainSocket,byte,this]()
    {
        /* Submit HTTP GET request */
         _tcpMainSocket->write("GET /finance/info?client=ig&q="+byte+" \r\n\r\n");//HTTP/1.1
    });

    connect(_tcpMainSocket, &QIODevice::readyRead, [=]()
    {
        //Parse google json file:
        QByteArray qbyte(_tcpMainSocket->readAll());
        _tcpMainSocket->disconnectFromHost();
        int qbytepos = qbyte.indexOf("{");
        qbyte.remove(0, qbytepos - 1);
        QJsonParseError jsonError;
        QJsonDocument jsonDoc = QJsonDocument::fromJson(qbyte, &jsonError);
        QJsonObject jsonObject = jsonDoc.object();
        QJsonValue jsonVal = jsonObject.value(QStringLiteral("l_fix"));
        double lastPrice = QString(jsonVal.toString()).toDouble();
        qDebug() << byte << lastPrice;
        mainIntPricesMapOpen.replace(_symbol, lastPrice);
        emit updateLastPrice(_symbol, lastPrice);

    });

    connect(_tcpMainSocket, &QTcpSocket::disconnected, [_tcpMainSocket,this]()
    {
        _tcpMainSocket->deleteLater();
    });
}