bool ChangeLog::checkChanges(const QString &previousVersion, const QString &currentVersion)
{
    QVersionNumber previous = QVersionNumber::fromString(previousVersion);
    QVersionNumber current = QVersionNumber::fromString(currentVersion);
    if (current <= previous) {
        qCInfo(CHANGELOG_CATEGORY) << "Current version isn't newer, than previous"
                                   << previousVersion << currentVersion;
        return false;
    }

    QFileSelector fileSelector;
    fileSelector.setExtraSelectors(QStringList() << QLocale::system().uiLanguages().constFirst().split('-').constFirst());
    const QString path = fileSelector.select(":/changelogs/changelog.json");

    QFile file(path);
    if (!file.open(QIODevice::ReadOnly)) {
        qCCritical(CHANGELOG_CATEGORY) << "Fail to open changelog file" << path << file.errorString();
        return false;
    }
    QByteArray data = file.readAll();

    QJsonParseError parseError;
    QJsonDocument document = QJsonDocument::fromJson(data, &parseError);
    if (parseError.error != QJsonParseError::NoError) {
        qCritical(CHANGELOG_CATEGORY) << "Fail to parse changelog data JSON:"
                                      << data << "error at offset"
                                      << parseError.offset
                                      << parseError.errorString() << parseError.error;
        return false;
    }
    QVariantList content = document.array().toVariantList();

    while (!content.isEmpty()) {
        if (QVersionNumber::fromString(content.constFirst().toMap().value("version").toString()) > current) {
            content.takeFirst();
        } else {
            break;
        }
    }
    QVariantList result;
    while (!content.isEmpty()) {
        if (QVersionNumber::fromString(content.constFirst().toMap().value("version").toString()) > previous) {
            result.append(content.takeFirst());
        } else {
            break;
        }
    }

    if (result.isEmpty()) {
        qCWarning(CHANGELOG_CATEGORY) << "Empty changelog" << previousVersion << currentVersion;
        return false;
    }

    emit changesAvailable(result);

    return true;
}
Example #2
0
Response *JsonParser::fromJson(const QByteArray &data)
{
    QJsonParseError parseError;
    QJsonDocument doc = QJsonDocument::fromJson(data, &parseError);

    if (parseError.error != QJsonParseError::NoError) {
        Error *errorResponse = new Error(parseError.errorString());
        return errorResponse;
    }

    QJsonObject obj = doc.object();

    QString type = obj.value("type").toString();
    if (type == "video") {
        Video* video = new Video();
        fillCommonValues(obj, video);

        video->setHtml(obj.value("html").toString());
        QString width = obj.value("width").toString();
        video->setWidth(width.toUInt());
        QString height = obj.value("height").toString();
        video->setHeight(height.toUInt());

        return video;
    } else if (type == "rich") {
        Rich* rich = new Rich();
        fillCommonValues(obj, rich);

        rich->setHtml(obj.value("html").toString());
        QString width = obj.value("width").toString();
        rich->setWidth(width.toUInt());
        QString height = obj.value("height").toString();
        rich->setHeight(height.toUInt());

        return rich;
    } else if (type == "photo") {
        Photo* photo = new Photo();
        fillCommonValues(obj, photo);

        photo->setUrl(obj.value("url").toString());
        QString width = obj.value("width").toString();
        photo->setWidth(width.toUInt());
        QString height = obj.value("height").toString();
        photo->setHeight(height.toUInt());

        return photo;
    } else if (type == "link") {
        Link* link = new Link();
        fillCommonValues(obj, link);
        return link;
    }

    Response *response = new Response();
    fillCommonValues(obj, response);
    return response;
}
Example #3
0
JsonObject::JsonObject(const QByteArray& json) {
    QJsonParseError pe;
    QJsonDocument doc = QJsonDocument::fromJson(json, &pe);
    if (pe.error != QJsonParseError::NoError)
        throw JsonException("cannot parse JSON: " + pe.errorString());
    if ( ! doc.isObject()) {
        throw JsonException("expected object");
    }
    o = doc.object();
}
Example #4
0
ConfigXML::ConfigXML(QObject *parent, ModuleConfig *conf) :
    QObject(parent), moduleConf(conf), configXMLDoc(0)
{
    // read classes from json
    QFile file(":/rc/classes.json");

    if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        QString content = file.readAll();
        QJsonParseError error;
        QJsonDocument jd = QJsonDocument::fromJson(
                    content.toUtf8(), &error);
        if (error.error == QJsonParseError::NoError) {
            classData = jd.object();
        } else {
            QMessageBox::warning(0, tr("Error"),
                error.errorString(), QMessageBox::Ok);
        }
        file.close();
    } else {
        QMessageBox::warning(0, tr("Error"), 
            tr("Cannot read json file"), QMessageBox::Ok);
    }

    // read events from json
    QFile file2(":/rc/events.json");

    if (file2.open(QIODevice::ReadOnly | QIODevice::Text)) {
        QString content = file2.readAll();
        QJsonParseError error;
        QJsonDocument jd = QJsonDocument::fromJson(
                    content.toUtf8(), &error);
        if (error.error == QJsonParseError::NoError) {
            eventData = jd.object();
        } else {
            QMessageBox::warning(0, tr("Error"),
                error.errorString(), QMessageBox::Ok);
        }
        file2.close();
    } else {
        QMessageBox::warning(0, tr("Error"),
            tr("Cannot read json file"), QMessageBox::Ok);
    }
}
Example #5
0
void ClassMapLoader::read(const QByteArray& jsonData) {
    emit mappingError(QStringLiteral("read() function not implemented"));
    QJsonParseError parseError;
    document.fromJson(jsonData, &parseError);
    if (parseError.error) {
        emit mappingError(parseError.errorString());
    } else {

    }
}
bool ClientHandler::OnProcessMessageReceived(CefRefPtr<CefBrowser> browser,
                                             CefProcessId source_process,
                                             CefRefPtr<CefProcessMessage> message) {
    // Check the message name.
    const std::string& message_name = message->GetName();

    if (message_name == "MethodCall") {
        const auto arguments = message->GetArgumentList();

        const auto methodName = arguments.get()->GetString(0).ToString();
        const auto json = arguments.get()->GetString(1).ToString();
        const auto callId = arguments.get()->GetInt(2);

        std::cout << "MethodCall id " << callId << " " << methodName << " " << json << std::endl;
        // Handle the message here...

        QJsonParseError parseError;
        QJsonDocument jsonDoc = QJsonDocument::fromJson(QByteArray::fromStdString(json), &parseError);
        if (parseError.error != QJsonParseError::NoError) {
            qDebug() << "JSON Error:" << parseError.errorString();
            return false;
        }
        const auto argsArray = jsonDoc.array();

        const auto bridge = static_cast<Shell*>(qApp)->bridge;

        std::vector<std::string> attempts;

        #include "cg/ClientSlot.cppf"

        if (!attempts.empty()) {
            const char* const delim = "\n";

            std::ostringstream imploded;
            std::copy(attempts.begin(), attempts.end(),
                      std::ostream_iterator<std::string>(imploded, delim));
            CefRefPtr<CefProcessMessage> msg = CefProcessMessage::Create("CallFailed");
            CefRefPtr<CefListValue> args = msg->GetArgumentList();

            args->SetInt(0, callId);

            // To keep the string version of the JSON value escaped
            // here to use the functionality provided by QDebug
            QString tmpStr;
            QDebug(&tmpStr) << QString::fromStdString(imploded.str()); // Have to cast to QString first, otherwise mojibake
            args->SetString(1, tmpStr.toStdString());

            browser->SendProcessMessage(PID_RENDERER, msg);
            return true;
        }

        return false;
    }
    return false;
}
Example #7
0
void VKApi::method(const QString &method,
        const QMap<QString, QString> params,
        std::function< void(const QJsonDocument*, QNetworkReply::NetworkError) > callback
)  {
    QUrl url( kApiBaseUrl + method );

    QUrlQuery q;

    if (!params.empty()) {
        for (const auto& key : params) {
            q.addQueryItem( key, params.value(key) );
        }
    }

    if (isLoggedIn())
        q.addQueryItem("access_token", accessToken);
    url.setQuery(q);

    QNetworkRequest req;
    req.setUrl(url);

    qDebug() << "Sending request to: " << req.url().toString() << "\n";
    auto reply = net.get(req);
    connect(reply, &QNetworkReply::finished, [reply, callback]() {
        QJsonDocument* json = 0;
        QJsonDocument jsonDoc;
        QNetworkReply::NetworkError error = reply->error();
        qDebug() << "Finished reply: " << reply << "\n";
        if (reply->error() != QNetworkReply::NetworkError::NoError) {
            qDebug() << "Network error: " << reply->errorString() << "\n";
        } else {
            QJsonParseError parseErr;
            auto data = reply->readAll();
            jsonDoc = QJsonDocument::fromJson(data , &parseErr );

            qDebug() << "got response <" << reply->url() << ">\n" << data << "\n\n\n";

            if (parseErr.error != QJsonParseError::NoError) {
                qDebug() << "failed to parse json: " << parseErr.errorString() << "\n";
                error = QNetworkReply::NetworkError::UnknownContentError;
            } else if (!jsonDoc.object().contains("response")) {
                qDebug() << "bad json.\n";
                error = QNetworkReply::NetworkError::UnknownContentError;
            } else {
                jsonDoc = QJsonDocument( jsonDoc.object().value( "response" ).toArray().at(0).toObject() );
                json = &jsonDoc;
            }
        }

        if (callback)
            callback(json, error);

        reply->deleteLater();
    });
}
void QSerienJunkiesReply::seriesSearchReplyFinished()
{
    QNetworkReply *reply = static_cast<QNetworkReply *>(sender());
    if(!reply)
        return;

    QJsonParseError jsonError;
    QJsonDocument jsonDocument = QJsonDocument::fromJson(reply->readAll(), &jsonError);
    reply->deleteLater();
    reply = nullptr;

    if(jsonError.error != QJsonParseError::NoError) {
        data->errorString = "The returned JSON was not valid: "+jsonError.errorString();
        emit error();
        return;
    }

    QVariant v = jsonDocument.toVariant();
    if(static_cast<QMetaType::Type>(v.type()) != QMetaType::QVariantList) {
        data->errorString = "The returned JSON is no list.";
        emit error();
        return;
    }

    QVariantList resultList = v.toList();
    data->seasonCount = resultList.size();

    if(data->seasonCount == 0) {
        emit finished();
        return;
    }

    // Get the given URLs, because the actual URL of a series is in the "Location" header of these URLs.
    foreach(QVariant result, resultList) {
        QVariantList list = result.toList();
        if(list.size() != 2)
            continue;
        Series r;
        r.id = list.at(0).toInt();
        r.name = list.at(1).toString();
        data->series.append(r);

        QUrl url(QString("http://serienjunkies.org/?cat=%1").arg(r.id));
        QNetworkReply *locationReply = QSerienJunkies::networkAccessManager()->get(QNetworkRequest(url));
        locationReply->setProperty("index", data->series.size() - 1);

        QObject::connect(locationReply, &QNetworkReply::finished,
                         this, &QSerienJunkiesReply::seriesLocationReplyFinished);

        QObject::connect(locationReply, SIGNAL(error(QNetworkReply::NetworkError)),
                         this, SLOT(onError()));

        QObject::connect(this, &QObject::destroyed,
                         locationReply, &QNetworkReply::deleteLater);
    }
Example #9
0
void SValue::setJson(const QByteArray &json)
{
	QJsonParseError err;
	QJsonDocument doc = QJsonDocument::fromJson(json, &err);
	QVariant v;
	if(err.error != QJsonParseError::NoError)
		qfError() << "SValue::setValueJson ERROR\n" << err.errorString();
	else
		v = doc.toVariant();
	setVariant(v);
}
Example #10
0
QVariant RequestManager::processMessage(QString buffered_message)
{
    // Parse function method and parameters
    buffered_message.chop(1);
    buffered_message.remove(0,1);
    // First turn string into QJSonDocument
    QJsonParseError error;
    QJsonDocument document( QJsonDocument::fromJson(buffered_message.toLocal8Bit(),&error));
    // Check if there was an error
    if(error.error != QJsonParseError::NoError)
    {
        qDebug() << "Error Parsing incoming Json Message:" << error.errorString() << "\nMessage Recieved: " << buffered_message;
        return QVariant();
    }

    // Begin Parsing Arguments
    QJsonArray request_array (document.array());
    QVariant parameter;
    QJsonObject func = request_array.first().toObject();
    int param_count = request_array.size()-1;
    if(param_count > 1)
    {
        QVariantList params;
        for(int i = 1; i < param_count+1; ++i)
        {
            params.append(request_array.at(i).toObject());
        }
        parameter.setValue(params);
    }
    else if( param_count == 1)
    {
        parameter = QVariant::fromValue(request_array.at(param_count).toObject());
    }
    else
    {
        parameter = QVariant();
    }
    QString functionname(func["FuncName"].toString());
    QTcpSocket * caller(qobject_cast<QTcpSocket*>(sender()));
    QVariant return_val = processRequest(functionname,caller,parameter);
    if(!return_val.isNull())
    {
        QJsonObject obj = return_val.value<QJsonObject>();
        QJsonDocument doc;
        doc.setObject(obj);
        QByteArray message(doc.toJson());
        return_val = QVariant::fromValue(doc);
        message.push_front("\001");
        message.push_back("\004");
        emit returnMessageReady(caller,message);
    }

    return return_val;
}
QMap<MarkupHighlighter::MarkupToken, const StyleProxy*> MarkupHighlighter::formatting()
{
    Q_INIT_RESOURCE(plotline);
    QMap<MarkupHighlighter::MarkupToken, const StyleProxy *> formatting;
    QFile *f = new QFile(DEFAULT_STYLE_FILE);

    if (!f->open(QFile::ReadOnly)){
        qWarning() << "Could not open" << DEFAULT_STYLE_FILE;
        return formatting;
    }

    QByteArray raw = f->readAll();
    QJsonParseError *error = new QJsonParseError;
    QJsonDocument jDoc = QJsonDocument::fromJson(raw, error);
    f->close();

    if (error->error != QJsonParseError::NoError){
        QPair<int, int> offset = multilineOffset(QString(raw), error->offset);
        qWarning("Error: %s\nat %s line %d, column %d\n%s\n%s",
                 error->errorString().toStdString().data(),
                 DEFAULT_STYLE_FILE.toStdString().data(),
                 offset.first, offset.second,
                 QString(raw).split('\n').at(offset.first).toStdString().data(),
                 QString("^").rightJustified(offset.second).toStdString().data());
        return formatting;
    }

    QJsonObject obj = jDoc.object();
    QJsonObject meta = obj["META"].toObject();
    QJsonObject style = obj["style"].toObject();

    qDebug() << "Opened style" << meta["name"].toString();

    StyleProxyParser parser = StyleProxyParser(style);

    formatting[HtmlEscape] = parser.parse("HtmlEscape");
    formatting[Header]  = parser.parse("Header");
    formatting[BlockQuote] = parser.parse("BlockQuote");
    formatting[List] = parser.parse("List");
    formatting[CodeBlock] = parser.parse("CodeBlock");
    formatting[HorizontalRule] = parser.parse("HorizontalRule");
    formatting[InlineLink] = parser.parse("InlineLink");
    formatting[LinkSource] = parser.parse("LinkSource");
    formatting[LinkTarget] = parser.parse("LinkTarget");
    formatting[Emphasis] = parser.parse("Emphasis");
    formatting[Strong] = parser.parse("Strong");
    formatting[InlineCode] = parser.parse("InlineCode");
    formatting[Image] = parser.parse("Image");
    formatting[AutomaticLink] = parser.parse("AutomaticLink");
    formatting[BackslashEscape] = parser.parse("BackslashEscape");

    return formatting;
}
Example #12
0
    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"];

        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;
    }
	QJsonDocument SyntaxHighlighter::_LoadJson(const QString& path) {
		QFile file;
		file.setFileName(path);
		if(!file.open(QFile::ReadOnly))
			throw std::runtime_error("can't read file");

		QJsonParseError err;
		QJsonDocument doc = QJsonDocument::fromJson(file.readAll(), &err);
		if(err.error != QJsonParseError::NoError)
			throw std::runtime_error(err.errorString().toStdString());
		return std::move(doc);
	}
Example #14
0
void ArchiveOrg::slotShowResults(KJob* job)
{
    if (job->error() != 0 ) return;
    m_listWidget->blockSignals(true);
    KIO::StoredTransferJob* storedQueryJob = static_cast<KIO::StoredTransferJob*>( job );
    QJsonParseError jsonError;
    QJsonDocument doc = QJsonDocument::fromJson(storedQueryJob->data(), &jsonError);
    if (jsonError.error != QJsonParseError::NoError) {
        // There was an error parsing data
        KMessageBox::sorry(m_listWidget, jsonError.errorString(), i18n("Error Loading Data"));
    }
    QVariant data = doc.toVariant();
    
    QVariant sounds;
    if (data.canConvert(QVariant::Map)) {
        QMap <QString, QVariant> map = data.toMap();
        QMap<QString, QVariant>::const_iterator i = map.constBegin();
        while (i != map.constEnd()) {
            if (i.key() == QLatin1String("response")) {
                sounds = i.value();
                if (sounds.canConvert(QVariant::Map)) {
                    QMap <QString, QVariant> soundsList = sounds.toMap();
                    if (soundsList.contains(QStringLiteral("numFound"))) emit searchInfo(i18np("Found %1 result", "Found %1 results", soundsList.value("numFound").toInt()));
                    QList <QVariant> resultsList;
                    if (soundsList.contains(QStringLiteral("docs"))) {
                        resultsList = soundsList.value(QStringLiteral("docs")).toList();
                    }
                    
                    for (int j = 0; j < resultsList.count(); ++j) {
                        if (resultsList.at(j).canConvert(QVariant::Map)) {
                            QMap <QString, QVariant> soundmap = resultsList.at(j).toMap();
                            if (soundmap.contains(QStringLiteral("title"))) {
                                QListWidgetItem *item = new   QListWidgetItem(soundmap.value(QStringLiteral("title")).toString(), m_listWidget);
                                item->setData(descriptionRole, soundmap.value(QStringLiteral("description")).toString());
                                item->setData(idRole, soundmap.value(QStringLiteral("identifier")).toString());
                                QString author = soundmap.value(QStringLiteral("creator")).toString();
                                item->setData(authorRole, author);
                                if (author.startsWith(QLatin1String("http"))) item->setData(authorUrl, author);
                                item->setData(infoUrl, "http://archive.org/details/" + soundmap.value(QStringLiteral("identifier")).toString());
                                item->setData(downloadRole, "http://archive.org/download/" + soundmap.value(QStringLiteral("identifier")).toString());
                                item->setData(licenseRole, soundmap.value(QStringLiteral("licenseurl")).toString());                        
                            }
                        }
                    }
                }
            }
            ++i;
        }
    }
    m_listWidget->blockSignals(false);
    m_listWidget->setCurrentRow(0);
    emit searchDone();
}
Example #15
0
void StatusChecker::statusDownloadFinished()
{
	QLOG_DEBUG() << "Finished loading status JSON.";

	QByteArray data;
	{
		ByteArrayDownloadPtr dl = std::dynamic_pointer_cast<ByteArrayDownload>(m_statusNetJob->first());
		data = dl->m_data;
		m_statusNetJob.reset();
	}

	QJsonParseError jsonError;
	QJsonDocument jsonDoc = QJsonDocument::fromJson(data, &jsonError);

	if (jsonError.error != QJsonParseError::NoError)
	{
		fail("Error parsing status JSON:" + jsonError.errorString());
		return;
	}

	if (!jsonDoc.isArray())
	{
		fail("Error parsing status JSON: JSON root is not an array");
		return;
	}

	QJsonArray root = jsonDoc.array();

	for(auto status = root.begin(); status != root.end(); ++status)
	{
		QVariantMap map = (*status).toObject().toVariantMap();

		for (QVariantMap::const_iterator iter = map.begin(); iter != map.end(); ++iter)
		{
			QString key = iter.key();
			QVariant value = iter.value();

			if(value.type() == QVariant::Type::String)
			{
				m_statusEntries.insert(key, value.toString());
				//QLOG_DEBUG() << "Status JSON object: " << key << m_statusEntries[key];
			}
			else
			{
				fail("Malformed status JSON: expected status type to be a string.");
				return;
			}
		}
	}

	succeed();
}
Example #16
0
void ignnetwork::setProxy(const QVariant &config){
    /* json parsing */
    QJsonParseError *err = new QJsonParseError();
    QJsonDocument json = QJsonDocument::fromVariant(config);

    if (err->error != 0) {
      qDebug() << err->errorString();
      exit (1);
    }

    QJsonObject jObject = json.object();
    QVariantMap set_proxy = jObject.toVariantMap();
    if(set_proxy["type"].toString() != ""){
        QNetworkProxy proxy;
        QString proxy_type = set_proxy["type"].toString();
        if(proxy_type == "http"){
            proxy.setType(QNetworkProxy::HttpProxy);
        }
        else if(proxy_type == "socks5"){
            proxy.setType(QNetworkProxy::Socks5Proxy);
        }
        else if(proxy_type == "ftp"){
            proxy.setType(QNetworkProxy::FtpCachingProxy);
        }
        else if(proxy_type == "httpCaching"){
            proxy.setType(QNetworkProxy::HttpCachingProxy);
        }
        else{
            qDebug()<<"Please input your type proxy (http,socks5,ftp,httpCaching)!";
        }

        if(set_proxy["url"].toString() != ""){
            QString url = set_proxy["url"].toString();
            QStringList url_proxy = url.split(":");
            proxy.setHostName(url_proxy.at(0));
            proxy.setPort(url_proxy.at(1).toInt());
        }
        else{
            qDebug()<<"Please input your hostname:port Ex: 127.0.0.1:8080!";
        }

        if(set_proxy["username"].toString() != ""){
            proxy.setUser(set_proxy["username"].toString());
        }

        if(set_proxy["password"].toString() != ""){
            proxy.setPassword(set_proxy["password"].toString());
        }

        QNetworkProxy::setApplicationProxy(proxy);
    }
}
ReceiptsPrinterOptions ReceiptsPrinterOptions::fromJson(const QByteArray &json)
{
	if(!json.isEmpty()) {
		QJsonParseError err;
		QJsonDocument jsd = QJsonDocument::fromJson(json, &err);
		if(err.error == QJsonParseError::NoError) {
			QVariantMap m = jsd.object().toVariantMap();
			return ReceiptsPrinterOptions(m);
		}
		qfError() << "Error parsing ReceiptsPrinterSettings JSON:" << err.errorString();
	}
	return ReceiptsPrinterOptions();
}
void QProcessResultThread::ParseSpResult( QByteArray& byJson, bool& bSuccess, QString& strUUID )
{
    strUUID = "";
    bSuccess = false;
    QJsonParseError jsonError;
    QJsonDocument jsonDoc = QJsonDocument::fromJson( byJson, &jsonError );

    if ( QJsonParseError::NoError != jsonError.error ) {
        qDebug( ) << jsonError.errorString( ) << endl;
        return;
    }

    if ( jsonDoc.isNull( ) || jsonDoc.isEmpty( ) ) {
        return;
    }

    QJsonObject jsonObj = jsonDoc.object( );
    if ( jsonObj.isEmpty( ) ) {
        return;
    }

    QJsonValue jsonVal = jsonObj.value( "Flag" );
    if ( jsonVal.isDouble( ) ) {
        bSuccess = jsonVal.toInt( );
    }

    GetStringValue( strUUID, "UUID",  jsonObj );

    if ( !bSuccess ) {
        return;
    }

    QString strDateTime = "";
    GetStringValue( strDateTime, "DateTime",  jsonObj );

    QString strPlate = "";
    GetStringValue( strPlate, "Plate",  jsonObj );

    QString strMobile = "";
    GetStringValue( strMobile, "MobilePhone",  jsonObj );

    QString strName = "";
    GetStringValue( strName, "Name",  jsonObj );

    if ( strMobile.isEmpty( ) ) {
        return;
    }

    SendShortMessage( strPlate, strDateTime, strName, strMobile );
}
QVariantMap JsonRestListModel::getVariantMap(QByteArray bytes)
{
    QString str = QString::fromUtf8(bytes.data(), bytes.size());

    QJsonParseError parseError;
    QJsonDocument document = QJsonDocument::fromJson(bytes, &parseError);
    QJsonObject obj = document.object();

    if (parseError.error != QJsonParseError::NoError) {
        qDebug() << parseError.errorString();
    }

    return obj.toVariantMap();
}
QVariantList JsonRestListModel::getVariantList(QByteArray bytes)
{
    QString str = QString::fromUtf8(bytes.data(), bytes.size());

    QJsonParseError parseError;
    QJsonDocument document = QJsonDocument::fromJson(bytes, &parseError);
    QJsonArray jsonArray = document.array();

    if (parseError.error != QJsonParseError::NoError) {
        qDebug() << parseError.errorString();
    }

    return jsonArray.toVariantList();
}
Example #21
0
void TcpClient::forwardIncomingMessage(void)
{
  Q_D(TcpClient);
  QByteArray msg = d->tcpSocket->readAll();
  QJsonParseError parseError;
  QJsonDocument json = QJsonDocument::fromJson(msg, &parseError);
  if (parseError.error != QJsonParseError::NoError) {
    QVariantMap map;
    map["status"] = "error";
    map["message"] = parseError.errorString();
    json = QJsonDocument::fromVariant(map);
  }
  emit receivedMessage(json);
}
bool AbstractTweetListQueryHandler::treatReply(RequestType requestType, const QByteArray &data,
                                           std::vector<Tweet> &items, QString &errorMessage,
                                           IListQueryHandler::Placement &placement)
{
    QJsonParseError error {-1, QJsonParseError::NoError};
    QJsonDocument document {QJsonDocument::fromJson(data, &error)};
    if (error.error != QJsonParseError::NoError) {
        errorMessage = error.errorString();
        placement = Discard;
        return false;
    }

    return treatReply(requestType, document.array(), items, placement);
}
QJsonDocument MainWindow::jsonFromReply(QNetworkReply *reply)
{
    QJsonParseError parseError;
    QJsonDocument json = QJsonDocument::fromJson(reply->readAll(), &parseError);
    if (parseError.error != QJsonParseError::NoError)
    {
        logMessage(tr("Response parse error: %1").arg(parseError.errorString()));
        return json;
    }

    QString prettyJSON = json.toJson(QJsonDocument::Indented);
    logMessage(tr("Response:\n%1").arg(prettyJSON));
    return json;
}
Example #24
0
QJsonObject parse(const std::string& data)
{
    const auto input = QByteArray::fromRawData(data.c_str(), data.size());
    QJsonParseError error;
    const auto doc = QJsonDocument::fromJson(input, &error);

    if (doc.isNull() || !doc.isObject())
    {
        print_log(LOG_ERROR, LOG_REST, "Error parsing JSON string '%s' '%s'",
                  data.c_str(), error.errorString().toLocal8Bit().constData());
        return QJsonObject{};
    }
    return doc.object();
}
Example #25
0
QJsonObject Playlist::openJsonFile(QFile& sourceFile) {
    QJsonParseError parseError;
    QString rawJson = QString::fromUtf8(sourceFile.readAll());

    QJsonDocument json = QJsonDocument::fromJson(rawJson.toUtf8(), &parseError);
    if (parseError.error != QJsonParseError::NoError) {
        qWarning() << "Failed to parse JSON";
        qWarning() << "\t" << parseError.errorString();
        return QJsonObject();
    }

    QJsonObject rootObject = json.object();
    return rootObject;
}
Example #26
0
/**
 * @brief DBusPebble::insertTimelinePin
 * @param jsonPin
 * Example usage:
 * dbus-send --session --dest=org.rockwork --type=method_call --print-reply
 *  /org/rockwork/XX_XX_XX_XX_XX_XX org.rockwork.Pebble.insertTimelinePin
 *  string:"$(cat pin.json)"
 * where pin.json is file with raw pin json object
 */
void DBusPebble::insertTimelinePin(const QString &jsonPin)
{
    QJsonParseError jpe;
    QJsonDocument json = QJsonDocument::fromJson(jsonPin.toUtf8(),&jpe);
    if(jpe.error != QJsonParseError::NoError) {
        qWarning() << "Cannot parse JSON Pin:" << jpe.errorString() << jsonPin;
        return;
    }
    if(json.isEmpty() || !json.isObject()) {
        qWarning() << "Empty or flat JSON Pin constructed, ignoring" << jsonPin;
        return;
    }
    m_pebble->insertPin(json.object());
}
Example #27
0
static std::vector<MSVCInstallInfo> retrieveInstancesFromVSWhere(ProductType productType)
{
    std::vector<MSVCInstallInfo> result;
    const QString cmd = vswhereFilePath();
    if (cmd.isEmpty())
        return result;
    QProcess vsWhere;
    QStringList args = productType == ProductType::VisualStudio
            ? QStringList({QStringLiteral("-all"), QStringLiteral("-legacy"),
                           QStringLiteral("-prerelease")})
            : QStringList({QStringLiteral("-products"),
                           QStringLiteral("Microsoft.VisualStudio.Product.BuildTools")});
    args << QStringLiteral("-format") << QStringLiteral("json") << QStringLiteral("-utf8");
    vsWhere.start(cmd, args);
    if (!vsWhere.waitForStarted(-1))
        return result;
    if (!vsWhere.waitForFinished(-1)) {
        qbsWarning() << Tr::tr("The vswhere tool failed to run: %1").arg(vsWhere.errorString());
        return result;
    }
    if (vsWhere.exitCode() != 0) {
        qbsWarning() << Tr::tr("The vswhere tool failed to run: %1")
                        .arg(QString::fromLocal8Bit(vsWhere.readAllStandardError()));
        return result;
    }
    QJsonParseError parseError;
    QJsonDocument jsonOutput = QJsonDocument::fromJson(vsWhere.readAllStandardOutput(),
                                                       &parseError);
    if (parseError.error != QJsonParseError::NoError) {
        qbsWarning() << Tr::tr("The vswhere tool produced invalid JSON output: %1")
                        .arg(parseError.errorString());
        return result;
    }
    const auto jsonArray = jsonOutput.array();
    for (const QJsonValue &v : jsonArray) {
        const QJsonObject o = v.toObject();
        MSVCInstallInfo info;
        info.version = o.value(QStringLiteral("installationVersion")).toString();
        if (productType == ProductType::BuildTools) {
            // For build tools, the version is e.g. "15.8.28010.2036", rather than "15.0".
            const int dotIndex = info.version.indexOf(QLatin1Char('.'));
            if (dotIndex != -1)
                info.version = info.version.left(dotIndex);
        }
        info.installDir = o.value(QStringLiteral("installationPath")).toString();
        if (!info.version.isEmpty() && !info.installDir.isEmpty())
            result.push_back(info);
    }
    return result;
}
Example #28
0
/*!
    Deserialize the stringified JSON messageData and emit messageReceived.
*/
void WebSocketTransport::textMessageReceived(const QString &messageData)
{
    QJsonParseError error;
    QJsonDocument message = QJsonDocument::fromJson(messageData.toUtf8(), &error);
    if (error.error) {
        qWarning() << "Failed to parse text message as JSON object:" << messageData
                   << "Error is:" << error.errorString();
        return;
    } else if (!message.isObject()) {
        qWarning() << "Received JSON message that is not an object: " << messageData;
        return;
    }
    emit messageReceived(message.object(), this);
}
Example #29
0
void VK::requestFinished(QNetworkReply* reply) {
    if (reply->error() == QNetworkReply::NoError) {

        m_isOnline = true;
        auto handler = m_manager.getHandlerByReply(reply);
        if (handler) {
            QString data = reply->readAll();
            qDebug()<<"VK::requestFinished:\n"<<data;

            QJsonParseError err;
            QJsonDocument document = QJsonDocument::fromJson(data.toUtf8(), &err);
            if (err.error != QJsonParseError::NoError) {
                qFatal("%s",err.errorString().toUtf8().data());
                Q_ASSERT(0);
            }
            QJsonObject object = document.object();
            if (object.value("error").type() != QJsonValue::Undefined) {
                errorHandler(object.value("error").toObject(), handler);
            } else {
                if (object.contains("response")) {
                    QJsonValue response = object.value("response");

                    handler->processReply(&response);

                } else {
                    qCritical()<<"no response";
                    Q_ASSERT(0);
                }
            }
        } else {
            qCritical()<<"error";
            Q_ASSERT(0);
        }
    } else {
        qCritical()<<"Reply error"<<reply->errorString();
        if (m_isOnline) {
            displayError("Connection error", ERROR_HANDLER_INFORM);
        }
        auto handler = m_manager.getHandlerByReply(reply);
        if (handler) {
            qDebug()<<"Network error, trying to reconnect";

            m_manager.remove(reply);
            sendNetworkRequest(handler);

        }
        m_isOnline = false;
    }
}
void GlosbeDic::processData(const QByteArray& _buff, const QString& _word, void* _resultStorage)
{
    QJsonParseError Error;
    QStringList* Storage = (QStringList*)_resultStorage;

    QJsonDocument JSonDoc = QJsonDocument::fromJson(_buff, &Error);
    if (Error.error != QJsonParseError::NoError)
        throw ("[Glosbe] Json Parse Error" + Error.errorString() + QString::number(Error.offset));

    if (JSonDoc.isObject()){
        QJsonObject JsonObject = JSonDoc.object();

        for(auto ObjectIter = JsonObject.constBegin();
            ObjectIter != JsonObject.constEnd();
            ObjectIter++)
        {
            if(ObjectIter.key().toLower().startsWith("tuc")) {
                for (QJsonValue ArrayIterValue : ObjectIter.value().toArray())
                {
                    QJsonObject JsonObject = ArrayIterValue.toObject();

                    for(auto ObjectIter = JsonObject.constBegin();
                        ObjectIter != JsonObject.constEnd();
                        ObjectIter++)
                    {
                        if(ObjectIter.key().toLower().startsWith("phrase")) {
                            if (ObjectIter.value().toObject().value("language").toString() == this->SecondLangID)
                            {
                                QString Translation =
                                        ObjectIter.value().toObject().value("text").toString().trimmed().toLower();
                                Storage->append(Translation);
                                this->add2Cache(_word.trimmed().toLower(), Translation);
                            }
                        }else if(ObjectIter.key().toLower() == "authors") {
                        }else if(ObjectIter.key().toLower() == "meaningid") {
                        }else if(ObjectIter.key().toLower() == "meanings") {
                        }else
                            wmaDebug<<"[Glosbe] Unkwon JSON Tag2: "<<wmaPrintable(ObjectIter.key())<<std::endl;
                    }
                }
            }else if(ObjectIter.key().toLower() == "result") {
            }else if(ObjectIter.key().toLower() == "dest") {
            }else if(ObjectIter.key().toLower() == "from") {
            }else if(ObjectIter.key().toLower() == "phrase") {
            }else
                wmaDebug<<"[Glosbe] Unkwon JSON Tag1: "<<wmaPrintable(ObjectIter.key())<<std::endl;
        }
    }
}