예제 #1
0
static bool readGpuFeatures(const QOpenGLConfig::Gpu &gpu,
                            const QString &osName,
                            const QVersionNumber &kernelVersion,
                            const QJsonDocument &doc,
                            QSet<QString> *result,
                            QString *errorMessage)
{
    result->clear();
    errorMessage->clear();
    const QJsonValue entriesV = doc.object().value(QStringLiteral("entries"));
    if (!entriesV.isArray()) {
        *errorMessage = QLatin1String("No entries read.");
        return false;
    }

    const QJsonArray entriesA = entriesV.toArray();
    for (JsonArrayConstIt eit = entriesA.constBegin(), ecend = entriesA.constEnd(); eit != ecend; ++eit) {
        if (eit->isObject()) {
            const QJsonObject object = eit->toObject();
            if (matches(object, osName, kernelVersion, gpu)) {
                const QJsonValue featuresListV = object.value(featuresKey());
                if (featuresListV.isArray()) {
                    const QJsonArray featuresListA = featuresListV.toArray();
                    for (JsonArrayConstIt fit = featuresListA.constBegin(), fcend = featuresListA.constEnd(); fit != fcend; ++fit)
                        result->insert(fit->toString());
                }
            }
        }
    }
    return true;
}
예제 #2
0
void CodeGenerator::generateMap()
{
    QFile codeFile(":code.json");
    if (!codeFile.open(QIODevice::ReadOnly))
    {
        qWarning("Could not open code file");
        return;
    }
    QByteArray codeData = codeFile.readAll();

    QJsonDocument JDoc(QJsonDocument::fromJson(codeData));
    if (!JDoc.isObject())
    {
        qWarning("Code file: invalid file format");
        return;
    }

    QJsonObject Main = JDoc.object();
    QJsonArray Snippets = Main["snippets"].toArray();
    QJsonArray Events = Main["events"].toArray();
    QJsonArray Commands = Main["commands"].toArray();
    QJsonArray Controls = Main["controls"].toArray();
    QJsonArray Expressions = Main["expressions"].toArray();

    for (QJsonArray::const_iterator it = Snippets.constBegin(); it != Snippets.constEnd(); it++)
    {
        QJsonObject Snippet = it->toObject();
        _snippets[Snippet["name"].toString()] = processCodeField(Snippet["code"].toArray());
    }

    for (QJsonArray::const_iterator it = Events.constBegin(); it != Events.constEnd(); it++)
    {
        QJsonObject Event = it->toObject();
        CodeGenerator::Event tmp = {processCodeField(Event["code"].toArray()), Event["register"].toString()};
        _events[Event["name"].toString()] = tmp;
    }

    for (QJsonArray::const_iterator it = Commands.constBegin(); it != Commands.constEnd(); it++)
    {
        QJsonObject Command = it->toObject();
        _commands[Command["name"].toString()] = processCodeField(Command["code"].toArray());
    }

    for (QJsonArray::const_iterator it = Controls.constBegin(); it != Controls.constEnd(); it++)
    {
        QJsonObject Control = it->toObject();
        _controls[Control["name"].toString()] = processCodeField(Control["code"].toArray());
    }

    for (QJsonArray::const_iterator it = Expressions.constBegin(); it != Expressions.constEnd(); it++)
    {
        QJsonObject Expression = it->toObject();
        _expressions[Expression["name"].toString()] = Expression["code"].toString();
    }
}
예제 #3
0
    Q_FOREACH (const QString &plugindir, libraryPaths) {
        const QString &_ixfile = plugindir + QStringLiteral("kpluginindex.json");
        QFile indexFile(_ixfile);
        if (indexFile.exists()) {
            indexFile.open(QIODevice::ReadOnly);
            QJsonDocument jdoc = QJsonDocument::fromBinaryData(indexFile.readAll());
            indexFile.close();


            QJsonArray plugins = jdoc.array();

            for (QJsonArray::const_iterator iter = plugins.constBegin(); iter != plugins.constEnd(); ++iter) {
                const QJsonObject &obj = QJsonValue(*iter).toObject();
                const QString &candidate = obj.value(QStringLiteral("FileName")).toString();
                const KPluginMetaData m(obj, candidate);
                if (m.pluginId() == packageFormat) {
                    pluginFileName = candidate;
                    break;
                }
            }
        } else {
            QVector<KPluginMetaData> plugins = KPluginLoader::findPlugins(plugindir);
            QVectorIterator<KPluginMetaData> iter(plugins);
            while (iter.hasNext()) {
                auto md = iter.next();
                if (md.pluginId() == packageFormat) {
                    pluginFileName = md.fileName();
                    break;
                }
            }
        }
    }
QMap<QString, QMap<QString, QString>> Info::getServiceServerAddressMeta()
{
   QString filename = getAddressMetaFilename();
   QByteArray json("[]");
   if(Filesystem::fileExist(filename)){
      json = Filesystem::fileGetContents(filename);
   }
   QJsonParseError parserError;
   QJsonDocument doc = QJsonDocument::fromJson(json, &parserError);
   QMap<QString, QMap<QString, QString>> ret;
   if(parserError.error == QJsonParseError::NoError){
      QJsonArray array = doc.array();
      QJsonArray::const_iterator ait = array.constBegin();
      QJsonArray::const_iterator aendmarker = array.constEnd();
      while(ait != aendmarker){
         QJsonValue v = *ait;
         if(v.isObject()){
            QJsonObject item = v.toObject();
            QJsonObject::const_iterator oit = item.constBegin();
            QJsonObject::const_iterator oendmarker = item.constEnd();
            QMap<QString, QString> dataItem;
            while(oit != oendmarker){
               dataItem.insert(oit.key(), oit.value().toString());
               oit++;
            }
            ret.insert(dataItem.value("key"), dataItem);
         }
         ait++;
      }
   }
   return ret;
}
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;
}
예제 #6
0
	bool RestGetOrders::ReceiveJson(const QJsonDocument& json, int nCode)
	{
		qDebug() << json;

		QList<OrdersData> listOrdersData;

		OrdersData od;

		QJsonArray jaOrders = json.array();
		for (QJsonArray::const_iterator citor = jaOrders.constBegin();
			citor != jaOrders.constEnd(); ++citor)
		{
			QJsonObject joOrder = citor->toObject();

			od.nId = joOrder[szElemText[ET_ID]].toInt();
			od.eType = static_cast<OrderType>(joOrder[szElemText[ET_TYPE]].toInt());
			od.dOrderPrice = joOrder[szElemText[ET_ORDER_PRICE]].toVariant().toDouble();
			od.dOrderAmount = joOrder[szElemText[ET_ORDER_AMOUNT]].toVariant().toDouble();
			od.dProcessedAmount = joOrder[szElemText[ET_PROCESSED_AMOUNT]].toVariant().toDouble();
			od.dtOrderTime = QDateTime::fromTime_t(joOrder[szElemText[ET_ORDER_TIME]].toInt());

			listOrdersData.append(od);
		}

		emit signal_Receive(listOrdersData);

		return true;
	}
예제 #7
0
static inline bool contains(const QJsonArray &a, unsigned needle)
{
    for (JsonArrayConstIt it = a.constBegin(), cend = a.constEnd(); it != cend; ++it) {
        if (needle == it->toString().toUInt(Q_NULLPTR, /* base */ 0))
            return true;
    }
    return false;
}
예제 #8
0
QStringList CodeGenerator::processCodeField(const QJsonArray &Code)
{
    QStringList list;
    for (QJsonArray::const_iterator it = Code.constBegin(); it != Code.constEnd(); it++)
    {
        list += it->toString();
    }
    return list;
}
void PAAlternativeLauncher::streamsFinished()
{
	QNetworkReply *reply = dynamic_cast<QNetworkReply *>(sender());
	if(reply)
	{
		if(reply->error() == QNetworkReply::NoError)
		{
			info.log("Streams", "Streams received.", true);
			setState(download_state);

			QSettings settings;
			// Curly braces for signal blocker
			{
				const QSignalBlocker blocker(mStreamsComboBox);
				mStreamsComboBox->clear();
				settings.beginGroup("streams");
				info.log("Streams", "Decoding data.", true);
				QJsonDocument authjson = QJsonDocument::fromJson(reply->readAll());
				QJsonArray streams = authjson.object()["Streams"].toArray();
				info.log("Streams", "Processing streams.", true);
				for(QJsonArray::const_iterator stream = streams.constBegin(); stream != streams.constEnd(); ++stream)
				{
					QJsonObject object = (*stream).toObject();
					QString download_url = object["DownloadUrl"].toString();
					QString title_folder = object["TitleFolder"].toString();
					QString manifest_name = object["ManifestName"].toString();
					QString auth_suffix = object["AuthSuffix"].toString();
					QString stream_name = object["StreamName"].toString();

					info.log("Streams", QString("Adding %1.").arg(stream_name), true);
					mStreamsComboBox->addItem(stream_name, object.toVariantMap());
					settings.setValue(stream_name + "/name", stream_name);

					info.log("Streams", "Retrieving news", true);
					// Get the news
					QNetworkRequest request(QUrl("https://uberent.com/Launcher/StreamNews?StreamName=" + stream_name + "&ticket=" + mSessionTicket));
					request.setRawHeader("X-Authorization", mSessionTicket.toUtf8());
					request.setRawHeader("X-Clacks-Overhead", "GNU Terry Pratchett");
					request.setRawHeader("User-Agent", QString("PAAlternativeLauncher/%1").arg(VERSION).toUtf8());
					request.setAttribute(QNetworkRequest::User, stream_name);
					QNetworkReply *stream_news_reply = mNetworkAccessManager->get(request);
					connect(stream_news_reply, SIGNAL(finished()), SLOT(streamNewsReplyFinished()));
				}
				settings.endGroup();
			}
			mStreamsComboBox->setCurrentText(settings.value("streams/defaultstream").toString());
		}
		else
		{
			info.critical(tr("Streams"), tr("Error while getting streams.\n%1").arg(reply->errorString()));
			setState(login_state);
		}

		reply->deleteLater();
	}
}
예제 #10
0
QList<State> buildStateList(QJsonArray const &array)
{
  QList<State> stateList;
  auto it = array.constBegin();
  while (it != array.constEnd()) {
    stateList.append (buildState((*it).toObject()));
    ++it;
  }
  return stateList;
}
예제 #11
0
QList<Transition> buildTransitionList(QJsonArray const &array)
{
  QList<Transition> transitionList;
  auto it = array.constBegin();
  while (it != array.constEnd()) {
    transitionList.append (buildTransition((*it).toObject()));
    ++it;
  }
  return transitionList;
}
bool DatabaseBackup::readContents(const QString &filename) {
    qDebug() << "Read contents from " + filename;
    QFile file(filename);
    QSqlQueryModel query;
    bool res = false;

    if (file.open(QIODevice::ReadOnly)) {
        QJsonDocument doc = QJsonDocument::fromJson(file.readAll());
        if (doc.isObject()) {
            res = true;
            QJsonArray tables = doc.object().take("database").toObject().take("tables").toArray();
            QJsonArray::const_iterator i = tables.constBegin();
            while (i != tables.constEnd()) {
                QString tableName = (*i).toObject().take("name").toString();
                qDebug() << tableName;
                QJsonArray records = (*i).toObject().take("records").toArray();
                QJsonArray::const_iterator recordIterator = records.constBegin();
                while (recordIterator != records.constEnd()) {
                    QVariantMap record = (*recordIterator).toObject().toVariantMap();
                    QStringList fields = record.keys();
                    QStringList values;
                    QStringList::const_iterator fieldIterator = fields.constBegin();
                    while (fieldIterator != fields.constEnd()) {
                        values << record.take(*fieldIterator).toString();
                        ++fieldIterator;
                    }
                    qDebug() << "INSERT INTO " + tableName + " (" + fields.join(',') + ")" + " VALUES ('" + values.join("','") + "')";
                    query.setQuery( QSqlQuery("INSERT INTO " + tableName + " (" + fields.join(',') + ")" + " VALUES ('" + values.join("','") + "')") );
                    qDebug() << "Errors?" << query.lastError();
                    ++ recordIterator;
                }
                ++i;
            }
        }
        query.submit();
    }
    file.close();
    return res;
}
예제 #13
0
static MetaDataResult::Tag tryReadPluginMetaDataFromCacheFile(const QString& canonicalPluginPath, RawPluginMetaData& result)
{
    QJsonDocument jsonDocument;
    if (readMetaDataFromCacheFile(jsonDocument) != ReadResult::Success)
        return MetaDataResult::NotAvailable;

    QJsonArray array = jsonDocument.array();
    QDateTime pluginLastModified = QFileInfo(canonicalPluginPath).lastModified();
    for (QJsonArray::const_iterator i = array.constBegin(); i != array.constEnd(); ++i) {
        QJsonValue item = *i;
        if (!item.isObject()) {
            cacheFile()->remove();
            return MetaDataResult::NotAvailable;
        }

        QJsonObject object = item.toObject();
        if (object.value(QStringLiteral("path")).toString() == canonicalPluginPath) {
            QString timestampString = object.value(QStringLiteral("timestamp")).toString();
            if (timestampString.isEmpty()) {
                cacheFile()->remove();
                return MetaDataResult::NotAvailable;
            }
            QDateTime timestamp = QDateTime::fromString(timestampString);
            if (timestamp < pluginLastModified) {
                // Out of date data for this plugin => remove it from the file.
                array.removeAt(i.i);
                writeToCacheFile(array);
                return MetaDataResult::NotAvailable;
            }

            if (object.contains(QLatin1String("unloadable")))
                return MetaDataResult::Unloadable;

            // Match.
            result.name = object.value(QStringLiteral("name")).toString();
            result.description = object.value(QStringLiteral("description")).toString();
            result.mimeDescription = object.value(QStringLiteral("mimeDescription")).toString();
            if (result.mimeDescription.isEmpty()) {
                // Only the mime description is mandatory.
                // Don't trust in the cache file if it is empty.
                cacheFile()->remove();
                return MetaDataResult::NotAvailable;
            }

            return MetaDataResult::Available;
        }
    }

    return MetaDataResult::NotAvailable;
}
예제 #14
0
파일: jsonmodel.cpp 프로젝트: NanoSim/Porto
bool JSONModel :: getInt32Array    (const char *key, std::vector<int32_t> &value) const
{
    auto it = d->jsonObject.find(key);
  if (it == d->jsonObject.end()) return false;
  if (!(*it).isArray()) return false;
  QJsonArray array = (*it).toArray();
  value.resize(array.size());

  auto array_it = array.constBegin();
  auto value_it = value.begin();
  while (array_it !=array.constEnd() && value_it != value.end()) {
    (*value_it++) = (*array_it++).toInt();
  }

  return true;
}
예제 #15
0
void CryptocoinChartsMDP::getCurrenciesList(QList<Currency>& list) {
    QJsonDocument doc = sendRequest("http://www.cryptocoincharts.info/v2/api/listCoins");
    QJsonArray array = doc.array();
    //qDebug() << "-- json: " << doc;
    for(QJsonArray::const_iterator i=array.constBegin(); i != array.constEnd(); ++i) {
        const QJsonValue &val = *i;
        QJsonObject obj = val.toObject();
        //qDebug() << ":::: volume:::" << obj["volume_btc"];
        double volume = obj["volume_btc"].toString().toDouble();
        if(volume > 1.0) { // let's filter out low volume alt coins
          Currency c; c.code = obj["id"].toString().toUpper(); c.name = obj["name"].toString();
          list.append(c);
          //qDebug() << "-- value: " << c << list.length();
        }
    }
}
예제 #16
0
파일: toolbars.cpp 프로젝트: jeyboy/playo3
void ToolBars::load(const QJsonArray & bars) {
    if (bars.count() > 0) {
        QList<QString> barsList;
        barsList
            << TOOLBAR_MEDIA_KEY
            << TOOLBAR_MEDIA_PLUS_KEY
            << TOOLBAR_MEDIA_POS_KEY
            << TOOLBAR_MEDIA_PAN_KEY
            << TOOLBAR_MEDIA_TEMPO_KEY
            << TOOLBAR_SEARCH_KEY
            << TOOLBAR_MEDIA_TIME_KEY
            << TOOLBAR_MEDIA_VOLUME_KEY
            << TOOLBAR_PL_ITEM_FEATURES_KEY
            << TOOLBAR_SL_ITEM_FEATURES_KEY
            << TOOLBAR_CONTROLS_KEY
            << TOOLBAR_SETTINGS_KEY
            << TOOLBAR_SPECTRUM_KEY
            << TOOLBAR_EQUALIZER_KEY
            << TOOLBAR_EQUALIZER_BUTTON_KEY;

        QJsonObject obj, actionObj;
        QString barName;
        QToolBar * curr_bar;

        for(QJsonArray::ConstIterator bar = bars.constBegin(); bar != bars.constEnd(); bar++) {
            obj = (*bar).toObject();
            barName = obj.value(Keys::title).toString();
            barsList.removeOne(barName);
            curr_bar = linkNameToToolbar(barName);
            curr_bar -> setObjectName(obj.value(Keys::name).toString(curr_bar -> objectName()));
            curr_bar -> setMovable(obj.value(Keys::movable).toBool());

            container -> addToolBar(Qt::BottomToolBarArea, curr_bar);

            if (obj.contains(Keys::actions)) {
                QJsonArray actions = obj.value(Keys::actions).toArray();

                foreach(QJsonValue act, actions) { // rewrite on for
                    actionObj = act.toObject();
                    addPanelButton(actionObj.value(Keys::name).toString(), actionObj.value(Keys::path).toString(), curr_bar);
                }
            }
예제 #17
0
/*
// normal result
{
    "from": "en",
    "to": "zh",
    "trans_result": [
        {
            "src": "today",
            "dst": "今天"
        },
        {
            "src": "tomorrow",
            "dst": "明天"
        }
    ]
}

// curr error
{
    "error_code": "52001",
    "error_msg": "TIMEOUT",
    "from": "auto",
    "to": "auto",
    "query": "he's"
}

if decode successfully return hash table containing <src, dst>
else return hash table containing <error_msg, error_msg>
*/
CBaiduTranslateResult CBaiduTranslater::decodeJsonData(const QByteArray &json)
{
    CBaiduTranslateResult result;
    QJsonDocument jsonDoc = QJsonDocument::fromJson(json);
    QJsonObject jsonObj = jsonDoc.object();
    if (jsonObj.contains(tr("error_msg")))
    {
//        vector.append(qMakePair(QString("error_code"), jsonObj["error_code"].toString()));
//        vector.append(qMakePair(QString("error_msg"), jsonObj["error_msg"].toString()));
//        vector.append(qMakePair(QString("from"), jsonObj["from"].toString()));
//        vector.append(qMakePair(QString("to"), jsonObj["to"].toString()));
//        vector.append(qMakePair(QString("query"), jsonObj["query"].toString()));
        result.m_error_code = static_cast<CBaiduTranslateResult::ErrorCode>(jsonObj["error_code"].toInt());
        result.m_error_msg = jsonObj["error_msg"].toString();
        result.m_from = jsonObj["from"].toString();
        result.m_to = jsonObj["to"].toString();
        result.m_query = jsonObj["query"].toString();
    }
    else if (jsonObj.contains(tr("trans_result")))
    {
        result.m_from = jsonObj["from"].toString();
        result.m_to = jsonObj["to"].toString();
//        vector.append(qMakePair(QString("from"), jsonObj["from"].toString()));
//        vector.append(qMakePair(QString("to"), jsonObj["to"].toString()));
        QJsonArray jsonArray = jsonObj["trans_result"].toArray();
        for (auto iter = jsonArray.constBegin(); iter != jsonArray.constEnd(); ++iter)
        {
            QJsonObject jsonObjTmp = static_cast<QJsonValue>(*iter).toObject();
            if (!jsonObjTmp.isEmpty())
                result.m_trans_result.append(qMakePair(jsonObjTmp["src"].toString(), jsonObjTmp["dst"].toString()));
        }
    }
    else
    {
        // unkonwn
    }

    return result;
}
예제 #18
0
void ContactDetails::loadDetailsFromDocument()
{
    if(!document->array().at(rowIndex).isObject())
    {
        //qDebug() << "error! Item at rowIndex" << m_rowIndex << "is not an object!";
        return;
    }

    QJsonObject object = document->array().at(rowIndex).toObject();

    ui->nameLbl->setText(object.value("name").toString());
    ui->nameLineEdit->setText(object.value("name").toString());

    contactDetailList.clear();

    while(QLayoutItem* item = ui->detailGroupLayout->takeAt(0))
    {
        delete item->widget();
        delete item;
    }

    if(object.contains("detailGroups"))
    {
        QJsonArray array = object.value("detailGroups").toArray();

        QJsonArray::const_iterator begin = array.constBegin();

        while(begin != array.end())
        {
            on_addGroupBtn_clicked();

            contactDetailList.last()->setJsonObject((*begin).toObject());

            begin++;
        }
    }    
}
void CashPointInRadius::fetchIds(ServerApiPtr api, quint32 leftAttempts)
{
    if (data.isEmpty()) {
        return;
    }

    mId = api->sendRequest("/nearby/cashpoints", data,
    [this, api, leftAttempts](ServerApi::RequestStatusCode reqCode, ServerApi::HttpStatusCode httpCode, const QByteArray &data) {
        if (!isRunning()) {
            if (isDisposing()) {
                deleteLater();
            }
            return;
        }
        const int step = 0;

        if (reqCode == ServerApi::RSC_Timeout) {
            emitUpdate(leftAttempts - 1, step);
            return;
        }

        const QString errText = trUtf8("Cannot receive list of nearby cashpoints");
        if (reqCode != ServerApi::RSC_Ok) {
            emitError(ServerApi::requestStatusCodeText(reqCode));
            emitStepFinished(*api, step, false, errText);
            return;
        }

        if (httpCode != ServerApi::HSC_Ok) {
            qWarning() << "Server request http code: " << httpCode;
            emitUpdate(leftAttempts - 1, step);
            return;
        }

        QJsonParseError err;
        const QJsonDocument json = QJsonDocument::fromJson(data, &err);
        if (err.error != QJsonParseError::NoError) {
            emitError("CashPointInRadius: server response json parse error: " + err.errorString());
            emitStepFinished(*api, step, false, errText);
            return;
        }

        if (!json.isArray()) {
            emitError("CashPointInRadius: response is not an array!");
            emitStepFinished(*api, step, false, errText);
            return;
        }

        mCashpointsToProcess.clear();
        mResponse = new CashPointResponse;
        mResponse->type = CashPointResponse::CashpointData;

        const QJsonArray arr = json.array();
        const auto end = arr.constEnd();
        for (auto it = arr.constBegin(); it != end; it++) {
            const QJsonValue &val = *it;
            const int id = val.toInt();
            if (id > 0) {
                mCashpointsToProcess.append(id);
//                qDebug() << id;
            }
        }

        // no cashpoints in radius => send response now
        if (mCashpointsToProcess.empty()) {
            emitResponseReady(true);
            emitStepFinished(*api, getStepHandlers().count() - 1, true, trUtf8("There is no nearby cashpoints"));
        }

        const int timestamp = QDateTime::currentDateTime().toMSecsSinceEpoch() / 1000;
        const int outdateTimestamp = timestamp - 300;

        const QMap<quint32, int> cachedCashpoints = getModel()->getCachedCashpoints();
        const auto cacheEnd = cachedCashpoints.end();

        auto it = mCashpointsToProcess.begin();
        while (it != mCashpointsToProcess.end()) {
            const quint32 id = *it;
            mResponse->addVisiableCashpoint(id);

            const auto cit = cachedCashpoints.find(id);
            if (cit != cacheEnd) {
                const int cachedTimestamp = cit.value();

                // cache is uptodate, so we do not need to fetch this id
                if (outdateTimestamp < cachedTimestamp) {
                    QJsonObject obj = getModel()->getCachedCashpointData(id);
                    if (!obj.isEmpty()) {
                        it = mCashpointsToProcess.erase(it);
                        mResponse->addCashPointData(obj);
                        continue;
                    }
                }
            }
            it++;
        }

        /// TODO: We have not to clear model but may be only remove invisiable points
//        getModel()->clear();
        emitStepFinished(*api, step, true, trUtf8("List of nearby cashpoints received"));
    });
}
예제 #20
0
void Order::loadFromJson(const QJsonObject &json)
{
    if (json.isEmpty()) {
        return;
    }

    Q_D(Order);

    QScopedPointer<const PPEnumsMap> em(new PPEnumsMap);

    d->setId(json.value(QStringLiteral("id")).toString());

    d->setReferenceId(json.value(QStringLiteral("reference_id")).toString());

    const QJsonObject ao = json.value(QStringLiteral("amount")).toObject();
    PaymentAmount *oldAo = amount();
    if (!ao.isEmpty()) {
        if (oldAo) {
            oldAo->loadFromJson(ao);
        } else {
            setAmount(new PaymentAmount(ao, this));
        }
    } else {
        setAmount(nullptr);
        delete oldAo;
    }


    d->setPaymentMode(em->paymentModeTypeTokenToEnum(json.value(QStringLiteral("payment_mode")).toString()));

    d->setState(em->stateTypeTokenToEnum(json.value(QStringLiteral("state")).toString()));

    d->setReasonCode(em->reasonCodeTokenToEnum(json.value(QStringLiteral("reason_code")).toString()));

    d->setProtectionEligibility(em->protectionEligibilityTokenToEnum(json.value(QStringLiteral("protection_eligibility")).toString()));

    const QString pets = json.value(QStringLiteral("protection_eligibility_type")).toString();
    if (!pets.isEmpty()) {
        QList<Geltan::PP::PayPal::ProtectionEligibilityType> petList;
        const QStringList petsList = pets.split(QChar(','));
        petList.reserve(petsList.size());
        for (const QString &pet : petsList) {
            petList.append(em->protectionEligibilityTypeTokenToEnum(pet));
        }
        d->setProtectionEligibilityType(petList);
    } else {
        d->setProtectionEligibilityType(QList<Geltan::PP::PayPal::ProtectionEligibilityType>());
    }

    d->setParentPayment(json.value(QStringLiteral("parent_payment")).toString());

    const QJsonObject fmfo = json.value(QStringLiteral("fmf_details")).toObject();
    FMFDetails *oldFmf = fmfDetails();
    if (!fmfo.isEmpty()) {
        if (oldFmf) {
            oldFmf->loadFromJson(fmfo);
        } else {
            d->setFmfDetails(new FMFDetails(fmfo, this));
        }
    } else {
        d->setFmfDetails(nullptr);
        delete oldFmf;
    }

    const QString ct = json.value(QStringLiteral("create_time")).toString();
    if (!ct.isEmpty()) {
        d->setCreateTime(QDateTime::fromString(ct, Qt::ISODate));
    } else {
        d->setCreateTime(QDateTime());
    }

    const QString ut = json.value(QStringLiteral("update_time")).toString();
    if (!ut.isEmpty()) {
        d->setUpdateTime(QDateTime::fromString(ut, Qt::ISODate));
    } else {
        d->setUpdateTime(QDateTime());
    }

    const QJsonArray la = json.value(QStringLiteral("links")).toArray();
    d->clearLinks();
    Q_EMIT linksChanged(links());
    if (!la.isEmpty()) {
        QList<Link*> linksToAdd;
        QJsonArray::const_iterator i = la.constBegin();
        while (i != la.constEnd()) {
            linksToAdd.append(new Link(i->toObject()));
            ++i;
        }
        d->setLinks(linksToAdd);
    }
}
예제 #21
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;
}
예제 #22
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;
}