Example #1
0
int HueBridgeConnection::post(const QString &path, const QVariantMap &params, QObject *sender, const QString &slot)
{
    if (m_baseApiUrl.isEmpty()) {
        qWarning() << "Not authenticated to bridge, cannot post" << path;
        return -1;
    }

    QUrl url(m_baseApiUrl + path);
    QNetworkRequest request;
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
    request.setUrl(url);

#if QT_VERSION >= 0x050000
    QJsonDocument jsonDoc = QJsonDocument::fromVariant(params);
    QByteArray data = jsonDoc.toJson(QJsonDocument::Compact);
#else
    QJson::Serializer serializer;
    QByteArray data = serializer.serialize(params);
#endif

    qDebug() << "posting" << jsonDoc.toJson()<< "\nto" << request.url() << "\n" << data;
    QNetworkReply *reply = m_nam->post(request, data);
    connect(reply, SIGNAL(finished()), this, SLOT(slotOpFinished()));
    m_requestIdMap.insert(reply, m_requestCounter);
    m_writeOperationList.append(reply);
    CallbackObject co(sender, slot);
    m_requestSenderMap.insert(m_requestCounter, co);
    return m_requestCounter++;
}
Example #2
0
void QRestClient::asyncJsonCall(
        QByteArray method,
        QByteArray uri,
        QJsonDocument body,
        jsonPayloadFn successCb,
        jsonPayloadFn errCb)
{
    QNetworkReply *rep = call(method, uri, body.toJson(), Json);
    connect(rep, &QNetworkReply::finished,
            this, [this, successCb, errCb](){

                QNetworkReply *rep = dynamic_cast<QNetworkReply*>(sender());
                if(!rep) return;

                QJsonDocument body = QJsonDocument::fromJson(QString(rep->readAll()).toUtf8());
#ifdef QRESTCLIENT_DEBUG
                qDebug() << __PRETTY_FUNCTION__ << body.toJson();
#endif
                if(rep->error() == QNetworkReply::NoError && successCb){
                    successCb(body);
                }else if(errCb){
                    errCb(buildJsonError(rep->errorString(), body.toJson()));
                }
                rep->deleteLater();
    });
}
void QPushbulletHandler::requestPush(Push &push, QString deviceID, QString email)
{
    /* [x] Note
     * [x] Link
     * [x] Address
     * [x] List
     * [] File
     */
    QJsonDocument jsonDocument;
    QJsonObject jsonObject;
    if (push.type == PUSH_TYPE::ADDRESS)
        jsonObject["type"] = "address";
    else if (push.type == PUSH_TYPE::FILE)
        jsonObject["type"] = "file";
    else if (push.type == PUSH_TYPE::LINK)
        jsonObject["type"] = "link";
    else if (push.type == PUSH_TYPE::LIST)
        jsonObject["type"] = "list";
    else if (push.type == PUSH_TYPE::NOTE)
        jsonObject["type"] = "note";

    if (!deviceID.isEmpty())
        jsonObject["device_iden"] = deviceID;
    else if (!email.isEmpty())
        jsonObject["email"] = email;
    if (push.type == PUSH_TYPE::NOTE) {
        jsonObject["title"] = push.title;
        jsonObject["body"] = push.body;
    }
    else if (push.type == PUSH_TYPE::LINK) {
        jsonObject["url"] = push.url;
        jsonObject["title"] = push.title;
        jsonObject["body"] = push.body;
    }
    else if (push.type == PUSH_TYPE::ADDRESS) {
        jsonObject["name"] = push.addressName;
        jsonObject["address"] = push.address;
    }
    else if (push.type == PUSH_TYPE::LIST) {
        jsonObject["type"] = "list";
        jsonObject["title"] = push.title;
        QJsonArray jsonArray;
        for (QString item : push.listItems) {
            jsonArray.append(QJsonValue(item));
        }
        jsonObject["items"] = jsonArray;
    }
    else if (push.type == PUSH_TYPE::FILE) {
        jsonObject["file_name"] = push.fileName;
        jsonObject["file_type"] = push.fileType;
        jsonObject["file_url"] = push.fileURL;
        jsonObject["body"] = push.body;
    }
    m_CurrentOperation = CURRENT_OPERATION::PUSH;

    jsonDocument.setObject(jsonObject);
    qDebug() << QString(jsonDocument.toJson());
    postRequest(m_URLPushes, jsonDocument.toJson());
}
Example #4
0
void QJsonRpcSocketPrivate::writeData(const QJsonRpcMessage &message)
{
    Q_Q(QJsonRpcSocket);
    QJsonDocument doc = QJsonDocument(message.toObject());
#if QT_VERSION >= 0x050100 || QT_VERSION <= 0x050000
    QByteArray data = doc.toJson(QJsonDocument::Compact);
#else
    QByteArray data = doc.toJson();
#endif

    device.data()->write(data);
    qJsonRpcDebug() << "sending(" << q << "): " << data;
}
Example #5
0
void DeviceAccess::processSales()
{
    //QVector<QHash<QString, QString> >group;
    if(transactiongroup.isEmpty())
        return;
    QByteArray data;
    QNetworkAccessManager *manager = new QNetworkAccessManager(this);
    for (int i = 0; i < transactiongroup.size(); i++)
    {
        currentTransactiongroupindex = i;
        QVector<QHash<QString, QString> >group = transactiongroup.at(i);
        QJsonArray jsonarray;
        QString total;
        QString receiptno;
        QString time;
        for (int j = 0; j < group.size(); j++)
        {
           QJsonObject jsonobject;
           total = group.at(j).value("total");
           receiptno = group.at(j).value("receiptno");
           time = group.at(j).value("time");
           jsonobject["item_id"] = QJsonValue(group.at(j).value("id"));
           jsonobject["price"] = QJsonValue(group.at(j).value("price"));
           jsonobject["quantity"] = QJsonValue(group.at(j).value("qty"));
           jsonarray.append(QJsonValue(jsonobject));

        }
        qDebug() << "Json Array:" << jsonarray;
        QNetworkRequest request;
        QJsonDocument jdoc = QJsonDocument(jsonarray);
        request.setUrl(QUrl("http://vergeapp.com/api/v2/addsales.json"));
        request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
        QUrlQuery params;
        params.addQueryItem("appid", appid);
        params.addQueryItem("locid", locid);
        params.addQueryItem("consumerkey", consumerkey);
        params.addQueryItem("paid", total);
        params.addQueryItem("payment_type", "cash");
        params.addQueryItem("receipt", receiptno);
        params.addQueryItem("trans_date", time);
        params.addQueryItem("products", jdoc.toJson());
        qDebug() << "json::" << jdoc.toJson();
        qDebug() << "url---->"  << params.toString();
        QEventLoop loop;
        QNetworkReply *reply = manager->post(request, data.append(params.toString()));
        connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
        loop.exec();
        replypushsalescomplete(reply);
    }

}
Example #6
0
bool MySqlStorage::addItemsToPrivacyList(QString jid, QString privacyListName, QList<PrivacyListItem> items)
{
    int user_id = getUserId(jid);

    m_database.transaction();

    QJsonDocument document;
    QJsonObject object;
    foreach (PrivacyListItem item, items)
    {
        object.insert("childs", QJsonArray::fromStringList(QStringList::fromSet(item.getChildsElement())));
        document.setObject(object);

        QSqlQuery query;
        query.prepare("INSERT INTO qjabberd_privacylist(user_id, ptype, pvalue, action, iorder, child, privacyListName)"
                      " VALUES(:user_id, :ptype, :pvalue, :action, :iorder, :child, :privacyListName)");
        query.bindValue(":user_id", user_id);
        query.bindValue(":ptype", item.getType());
        query.bindValue(":pvalue", item.getValue());
        query.bindValue(":action", item.getAction());
        query.bindValue(":iorder", item.getOrder());
        query.bindValue(":child", document.toJson());
        query.bindValue(":privacyListName", privacyListName);
        query.exec();
    }
bool AssignmentClientMonitor::handleHTTPRequest(HTTPConnection* connection, const QUrl& url, bool skipSubHandler) {
    if (url.path() == "/status") {
        QByteArray response;

        QJsonObject status;
        QJsonObject servers;
        for (auto& ac : _childProcesses) {
            QJsonObject server;

            server["pid"] = ac.process->processId();
            server["logStdout"] = ac.logStdoutPath;
            server["logStderr"] = ac.logStderrPath;

            servers[QString::number(ac.process->processId())] = server;
        }

        status["servers"] = servers;

        QJsonDocument document { status };

        connection->respond(HTTPConnection::StatusCode200, document.toJson());
    } else {
        connection->respond(HTTPConnection::StatusCode404);
    }


    return true;
}
Example #8
0
bool MySqlStorage::addContactToRoster(QString jid, Contact contact)
{
    if (contactExists(jid, contact.getJid()))
    {
        updateNameToContact(jid, contact.getJid(), contact.getName());
        updateGroupToContact(jid, contact.getJid(), contact.getGroups());
        return true;
    }
    else
    {
        if (userExists(contact.getJid()))
        {
            QJsonDocument document;
            QJsonObject object;
            object.insert("groups", QJsonArray::fromStringList(QStringList::fromSet(contact.getGroups())));
            document.setObject(object);

            QSqlQuery query;
            query.prepare("INSERT INTO qjabberd_contact(user_id, approved, ask, groups, jid, name, subscription, version)"
                          " VALUES(:user_id, :approved, :ask, :groups, :jid, :name, :subscription, :version)");
            query.bindValue(":user_id", getUserId(jid));
            query.bindValue(":version", contact.getVersion());
            query.bindValue(":approved", (int)contact.getApproved());
            query.bindValue(":ask", contact.getAsk());
            query.bindValue(":jid", contact.getJid());
            query.bindValue(":name", contact.getName());
            query.bindValue(":subscription", contact.getSubscription());
            query.bindValue(":groups", document.toJson());
            return query.exec();
        }
    }
    return false;
}
Example #9
0
void ATPAssetMigrator::saveEntityServerFile() {
    // show a dialog to ask the user where they want to save the file
    QString saveName = QFileDialog::getSaveFileName(_dialogParent, "Save Migrated Entities File");
    
    QFile saveFile { saveName };
    
    if (saveFile.open(QIODevice::WriteOnly)) {
        QJsonObject rootObject;
        rootObject[ENTITIES_OBJECT_KEY] = _entitiesArray;
        
        QJsonDocument newDocument { rootObject };
        QByteArray jsonDataForFile;
        
        if (gzip(newDocument.toJson(), jsonDataForFile, -1)) {
            
            saveFile.write(jsonDataForFile);
            saveFile.close();
            
            QMessageBox::information(_dialogParent, "Success",
                                     QString("Your new entities file has been saved at %1").arg(saveName));
        } else {
            QMessageBox::warning(_dialogParent, "Error", "Could not gzip JSON data for new entities file.");
        }
    
    } else {
        QMessageBox::warning(_dialogParent, "Error",
                             QString("Could not open file at %1 to write new entities file to.").arg(saveName));
    }
}
Example #10
0
void collectmailsesb::handleMailInfo()
{
    cleanupFiles("esb_*");

    QJsonDocument doc;

    QJsonObject data;
    QJsonObject datacontent;

    QMapIterator<QString, QJsonArray*> iMailsInfos(mailInfos);
    int _iMailsInfos = 0;
    while (iMailsInfos.hasNext())
    {
        //_iMailsInfos++;
        iMailsInfos.next();
        QString sSubject = iMailsInfos.key();
        QJsonArray* lMails = iMailsInfos.value();
        datacontent.insert(sSubject, QJsonValue(*lMails));
        _iMailsInfos += lMails->size();
    }

    data.insert("data", QJsonValue(datacontent));
    doc.setObject(data);

    QFile file(QString(getFN("esb_", "maildata")+".json"));
    file.open(QFile::WriteOnly | QFile::Text | QFile::Truncate);
    file.write(doc.toJson(QJsonDocument::Compact));
    file.close();

    //TODO: delete QJsonArray*'s

    helpers::log("cmesb:handleMailInfo(esb): FINISH -> "+QString::number(_iMailsInfos), LOG_INF, qApp, 0);
}
Example #11
0
bool Option::saveOption()
{
    QJsonDocument jsonDocument;

    QJsonObject jsonSingleValue;
    jsonSingleValue.insert("fullscreen",QJsonValue(this->isFullscreen()));
    jsonSingleValue.insert("volume",QJsonValue(this->getVolume()));
    jsonSingleValue.insert("mute",QJsonValue(this->isMute()));

    if(this->language==Option::french)
        jsonSingleValue.insert("language",QJsonValue(QString("french")));
    else if(this->getLanguage()==Option::english)
        jsonSingleValue.insert("language",QJsonValue(QString("english")));
    else
        jsonSingleValue.insert("language",QJsonValue(QString("english")));


    jsonDocument.setObject(jsonSingleValue);

    fileOption = new QFile(this->jsonFilename);
    if(fileOption->open(QIODevice::WriteOnly))
    {
        QTextStream fileStream(fileOption);
        fileStream << jsonDocument.toJson();

        fileOption->close();
        return true;
    }
    else
    {
        fileOption->close();

        return false;
    }
}
Example #12
0
QString Database::json_convert(Kind *kind){
    QJsonDocument *jdoc = new QJsonDocument;
    QJsonObject *root = new QJsonObject;
    root->insert(NAME, QJsonValue(kind->getName()));
    root->insert(SURNAME, QJsonValue(kind->getSurName()));
    root->insert(DATE, QJsonValue(kind->getDate().toString(DATESAVEFORMAT)));
    root->insert(STREET, QJsonValue(kind->getStreet()));
    root->insert(CITY, QJsonValue(kind->getCity()));
    root->insert(GROUP, QJsonValue(kind->getGroup()));
    root->insert(MAIL, QJsonValue(kind->getMail()));
    root->insert(NUMBER, QJsonValue(kind->getNumber()));
    QJsonObject *jtable = new QJsonObject;
    QJsonArray *keys = new QJsonArray;
    QJsonArray *tables = new QJsonArray;
    QJsonObject *values = new QJsonObject;
    std::map<QString, QString> *kt = kind->getTable();
    std::map<QString, QString>::iterator it;
    int i = 0;
    for(it = kt->begin(); it != kt->end(); it++){
        keys->insert(i, QJsonValue(it->first));
        values->insert(it->first, it->second);
        i++;
    }
    jtable->insert(KEY, QJsonValue(*keys));
    jtable->insert(VALUE, QJsonValue(*values));
    jtable->insert(NAME, QJsonValue(QString::fromStdString(TNAME)));
    tables->insert(0, QJsonValue(*jtable));
    root->insert(TABLE, QJsonValue(*tables));
    jdoc->setObject(*root);
    QString datefile = QString::fromUtf8(jdoc->toJson(QJsonDocument::Compact)) + QString::fromStdString(ENDL);
    return datefile;
}
Example #13
0
void MainDialog::on_receiveBtn_clicked()
{
    int index = ui->listWidget->currentIndex().row();
    if(index==-1)
    {
        QMessageBox::about(NULL,"提示","没有选择内容");
    }
    else
    {
        QString info = ui->listWidget->item(index)->text();
        ui->listWidget->takeItem(index);
        if(itemTypeList.at(index)==0)
        {
            QJsonObject object;
            object.insert("info",info.left(10));
            object.insert("type",2);
            QJsonDocument document;
            document.setObject(object);
            QString msg(document.toJson());
            tcpSocket->write(msg.toLocal8Bit());
        }
        itemTypeList.remove(index);
        if(ui->listWidget->count()==0)
        {
            player->stop();
        }
    }
}
Example #14
0
StatusCode fetchJson(const QString &specFileName)
{
    QEventLoop eventLoop;
    QNetworkAccessManager mgr;
    QObject::connect(&mgr, &QNetworkAccessManager::finished, &eventLoop, &QEventLoop::quit);

    QNetworkRequest req(QUrl(QLatin1String("https://core.telegram.org/schema/json")));
    QNetworkReply *reply = mgr.get(req);

    eventLoop.exec();

    if (reply->error() != QNetworkReply::NoError) {
        delete reply;
        return NetworkError;
    }

    QByteArray data = reply->readAll();
    delete reply;

    if (data.isEmpty()) {
        return ServerError;
    }

    QFile specsOutFile(specFileName);
    if (!specsOutFile.open(QIODevice::WriteOnly)) {
        return FileAccessError;
    }

    QJsonDocument document = QJsonDocument::fromJson(data);
    specsOutFile.write(document.toJson());
    specsOutFile.close();

    printf("Spec file successfully downloaded (and formatted).\n");
    return NoError; // Not implemented
}
Example #15
0
bool SaveToJSON(QVariantMap &data, QIODevice &f, const char *magicIdentifier, uint32_t magicVersion)
{
  // marker that this data is valid
  data[magicIdentifier] = magicVersion;

  QJsonDocument doc = QJsonDocument::fromVariant(data);

  if(doc.isEmpty() || doc.isNull())
  {
    qCritical() << "Failed to convert data to JSON document";
    return false;
  }

  QByteArray jsontext = doc.toJson(QJsonDocument::Indented);

  qint64 ret = f.write(jsontext);

  if(ret != jsontext.size())
  {
    qCritical() << "Failed to write JSON data: " << ret << " " << f.errorString();
    return false;
  }

  return true;
}
void DashcoinWallet::on_btn_send_confirm_clicked()
{
    if(ui->txt_send_amount->value() <= 0){
        messageLabel->setText("Invalid amount");
        return;
    }
    QString address = ui->txt_send_address->text();
    QString paymentid = ui->txt_send_paymentid->text();
    QString amount = fix_amount(ui->txt_send_amount->cleanText());
    QString fee = fix_amount(ui->txt_send_fee->cleanText());
    QString mixin = ui->txt_send_mixin->cleanText();
    ui->txt_send_address->clear();
    ui->txt_send_paymentid->clear();
    ui->txt_send_amount->setValue(0);
    ui->txt_send_fee->setValue(15);
    ui->txt_send_mixin->setValue(0);
    ui->btn_send_confirm->setText("Sending...");
    loader_send = new QNetworkAccessManager(this);
    connect(loader_send, SIGNAL(finished(QNetworkReply*)),this, SLOT(rpcReply(QNetworkReply*)));
    QString dataStr = "{ \"jsonrpc\":\"2.0\", \"method\":\"transfer\", \"id\":\"send\", \"params\":{ \"destinations\":[ { \"amount\":"+amount+", \"address\":\""+address+"\" } ], \"payment_id\":\""+paymentid+"\", \"fee\":"+fee+", \"mixin\":"+mixin+", \"unlock_time\":0 } }";
    QJsonDocument jsonData = QJsonDocument::fromJson(dataStr.toUtf8());
    QByteArray data = jsonData.toJson();
    QNetworkRequest request = QNetworkRequest(QUrl("http://127.0.0.1:49253/json_rpc"));
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/octet-stream");
    loader_send->post(request, data);
    qDebug() << "Sent send request " << dataStr ;
}
Example #17
0
QString CurrencyPane::SaveCurrencyHistoryPoint()
{
    QJsonObject point;
    double time = (double)QDateTime(QDate::currentDate()).toTime_t();
    point.insert("value", totalValue);
    point.insert("time", time);

    QByteArray data = QByteArray::fromStdString(app_->data_manager().Get("currency_history"));
    QJsonDocument doc = QJsonDocument::fromJson(data);
    QJsonArray array;
    if (!doc.isNull() && doc.isArray()) {
        array = doc.array();
    }
    bool insert = true;
    for (QJsonValue val : array) {
        if (val.isObject() && val.toObject().value("time").toDouble() == time) {
            insert = false;
            break;
        }
    }
    if (insert) array.append(point);
    doc.setArray(array);

    QString newData = doc.toJson(QJsonDocument::Compact);
    app_->data_manager().Set("currency_history", newData.toStdString());
    LoadCurrencyHistory(newData);
    return newData;
}
void DiLambda::data_available()
{
    while (current_port.canReadLine()) {
        QByteArray line = current_port.readLine();
        qDebug() << "read:" + line;

        if (line.startsWith("J: ")) {
            qDebug("looks like json");
            QJsonDocument json = QJsonDocument::fromJson(line.mid(3)); // Skip the first 3 characters

            qDebug() << "Jason: " << json.toJson();

            QJsonObject jo = json.object();
            QJsonArray bg = jo["bg"].toArray();
            QJsonArray sample = jo["signal"].toArray();

            QList<int> data_list;

            for (int i = 0; i < 3; i++) {
                data_list.append(sample[i].toInt() - bg[i].toInt());
            }

            emit new_sample(data_list);
        }
    }
}
Example #19
0
bool FileManager::saveToFile( QString path, QString categoryPath, QList<TrackModel*> trackModels )
{
    QJsonObject jsonObject;
    QJsonArray  trackArray;

    for ( int i = 0; i < trackModels.size(); i++ )
        trackArray.append( trackModels[i]->serializeToJson() );

    // Put into json document
    jsonObject["categoryPath"] = categoryPath;
    jsonObject["tracks"] = trackArray;
    QJsonDocument jsonDoc = QJsonDocument( jsonObject );

    // Prep file
    QFile file;
    file.setFileName( path );

    // Open
    if ( !file.open( QIODevice::WriteOnly | QIODevice::Text ) )
        return false;

    // Write
    int result = file.write( jsonDoc.toJson() );
    qDebug() << "...wrote" << result << "bytes to" << path;

    return result != -1;
}
void QDiscordWsComponent::login(const QString& token,
								QDiscordTokenType tokenType)
{
	if(_reconnectTimer.isActive())
		_reconnectTimer.stop();
	QJsonDocument document;
	QJsonObject mainObject;
	mainObject["op"] = 2;
	QJsonObject dataObject;
	dataObject["token"] =
			QDiscordUtilities::convertTokenToType(token, tokenType);
	dataObject["v"] = 5;
	dataObject["properties"] =
			QJsonObject({
							{"$os", QSysInfo::kernelType()},
							{"$browser", QDiscordUtilities::libName},
							{"$device", QDiscordUtilities::libName},
							{"$referrer", "https://discordapp.com/@me"},
							{"$referring_domain", "discordapp.com"}
						});
	dataObject["large_threshold"] = 100;
	dataObject["compress"] = false;
	mainObject["d"] = dataObject;
	document.setObject(mainObject);
	_socket.sendTextMessage(document.toJson(QJsonDocument::Compact));
}
Example #21
0
void NewWakuSettingsWindow::savePresets()
{
  QStringList dir = QStandardPaths::standardLocations(QStandardPaths::DataLocation);
  if (dir.empty()) {
    mwin->insLog("save directory is not available");
    QMessageBox::information(this, "Viqo", "保存領域がないので保存できません");
    return;
  }

  QJsonArray pages;

  for (int i = 0; i < ui->presetes->count(); ++i) {
    QJsonObject page;
    page["title"] = ui->presetes->itemText(i);
    page["data"] = ui->presetes->itemData(i).toJsonObject();
    pages << page;
  }

  QJsonDocument jsd;
  jsd.setArray(pages);

  QFile file(dir[0] + "/newWakuSettings.json");
  if (!file.open(QIODevice::WriteOnly)) {
    file.close();
    mwin->insLog("opening settings file failed");
    QMessageBox::information(this, "Viqo", "設定ファイルに書き込めません");
    return;
  }
  QTextStream out(&file);
  out << jsd.toJson(QJsonDocument::Compact);
  file.close();
}
Example #22
0
void collectmailsesb::__testjson()
{
    QJsonDocument doc;
    QJsonObject data;
    data.insert("data", QJsonValue(QJsonObject()));
    {
        //QJsonObject esb;
        //esb.insert("[ESB]", QJsonValue(QJsonArray()));

        QJsonArray a;
        a.append(QJsonValue(QString("ae")));
        data.insert("data2", QJsonValue(a));

        QJsonArray aa = data.value("data2").toArray();
        aa.append(QJsonValue(QString("aee")));
        data.remove("data2");
        data.insert("data2", QJsonValue(aa));

        //doc.object().value("data").toObject().insert("[ESB]", QJsonValue(a));
        //QJsonObject data2;
        //data2.insert("data2", QJsonValue(QJsonObject()));

        //data.insert("data2", QJsonValue(QString("val2")));
    }
    doc.setObject(data);

    QMessageBox::warning(0, "__testjson", doc.toJson());

    /*
    QFile file("c:/temp/test.json");
    file.open(QFile::WriteOnly | QFile::Text | QFile::Truncate);
    file.write(doc.toJson());
    file.close();
    */
}
Example #23
0
bool TradeTable::SaveColumnJson()
{
	int count = m_ColumnMap.count();
	QJsonArray jsonArray;
	for(int i=0;i<count;i++)
	{
		QJsonObject jsonObject;
		jsonObject.insert("columnText",m_ColumnMap[i].GetColumnText());
		jsonObject.insert("isShow",m_ColumnMap[i].IsShow());
		jsonObject.insert("isForbidHide",m_ColumnMap[i].IsForbidHide());
		jsonObject.insert("isPicture",m_ColumnMap[i].IsPicture());
		jsonArray.append(jsonObject);
	}
	QJsonObject root;
	root.insert("columnSetting",jsonArray);
	QFile file(m_ColumnJsonFile);
	if(!file.open(QIODevice::WriteOnly|QIODevice::Text))
		return false;
	QTextStream stream(&file);
	QJsonDocument jsonDoc;
	jsonDoc.setObject(root);
	stream << jsonDoc.toJson();
	file.close();

	return true;
}
Example #24
0
void JSONDataSource::save()
{
    if(!isLoaded)
    {
        return;
    }
    
    QJsonDocument doc;
    QJsonArray pupilArray;
    
    for(int i = 0; i < pupils->length();i++)
    {
        pupilArray.append(encodePupil(pupils->at(i)));
    }
    
    doc.setArray(pupilArray);
    
    QFile file(QDir::toNativeSeparators(QDir::homePath())  + "/" + FILENAME);
    if (!file.open(QIODevice::WriteOnly))
    {
        return;
    }
    else
    {        
        file.write(doc.toJson());
        file.close();
    }
}
Example #25
0
QJsonObject SeleniumServerHub::post(QString url, QJsonObject rawBody)
{
    QJsonDocument doc;
    doc.setObject(rawBody);

    return exec(url, doc.toJson(), POST);
}
Example #26
0
void LoginWorker::doWork(HcaThread *t)
{
    QElapsedTimer totalTime;
    totalTime.start();

    m_id = t->id();
    DbManager* dbm = t->dbManager();
    emit(t->setThreadStatus(m_id, false)); //this must always be the first

    QScopedPointer<Client> c(new Client(this));

    if(!dbm->findUserByUuid(uuid, c.data())){
        qWarning() << "User not found, creating...";
        dbm->createUser(c.data());
    }

    c->setStatus(ONLINE);
    dbm->updateClient(c.data());

    QJsonObject response = c->toFullJsonObject();
    response[REQUEST] = LOGIN;
    QJsonDocument doc;
    doc.setObject(response);
    qWarning() << "Emitting login from " << QThread::currentThreadId();
    emit loginResult(doc.toJson(QJsonDocument::Compact), socket, c->id());
    emit(t->setThreadStatus(m_id, true)); //this must always be the last
    qWarning() << "loginRequest evaded in " << totalTime.elapsed() << "ms";
}
void QDiscordWsComponent::setStatus(bool idle, QDiscordGame game)
{
	if(_token == "")
		return;
	if(_gateway == "")
		return;
	QJsonDocument document;
	QJsonObject object;
	object["op"] = 3;
	QJsonObject presenceObject;
	presenceObject["idle_since"] = idle ?
				QDateTime::currentMSecsSinceEpoch() : QJsonValue();
	if(game.name() != "")
	{
		QJsonObject gameObject;
		gameObject["name"] = game.name();
		gameObject["url"] = game.url()==""?QJsonValue():game.url();
		gameObject["type"] = static_cast<int>(game.type());
		presenceObject["game"] = gameObject;
	}
	else
		presenceObject["game"] = QJsonValue();
	object["d"] = presenceObject;
	document.setObject(object);
	_socket.sendTextMessage(document.toJson(QJsonDocument::Compact));
}
Example #28
0
QByteArray
toJson( const QVariant &variant, bool* ok )
{
#if QT_VERSION >= QT_VERSION_CHECK( 5, 0, 0 )
    QVariant _variant = variant;
    if ( variant.type() == QVariant::Hash )
    {
        // QJsonDocument cannot deal with QVariantHash, so convert.
        const QVariantHash hash = variant.toHash();
        QVariantMap map;
        QHashIterator<QString, QVariant> it(hash);
        while ( it.hasNext() )
        {
            it.next();
            map.insert( it.key(), it.value() );
        }
        _variant = map;
    }

    QJsonDocument doc = QJsonDocument::fromVariant( _variant );
    if ( ok != NULL )
    {
        *ok = !doc.isNull();
    }
    return doc.toJson( QJsonDocument::Compact );
#else
    QJson::Serializer serializer;
    return serializer.serialize( variant, ok );
#endif
}
Example #29
0
QString PutPolicy::token(QString ak, QString sk, QString scope)
{

	QJsonDocument doc;

	QJsonObject obj;

	// 	指定上传的目标资源空间(Bucket) 和资源键(Key) 。
	// 		有两种格式:
	// 		● <bucket>,表示允许用户上传文件到指定的 bucket。在这种格式下文件只能“新增”,若已存在同名资源上传则会失败。
	// 		● <bucket> : <key>,表示只允许用户上传指定key的文件。在这种格式下文件默认允许“修改”,
	// 若已存在同名资源则会被覆盖。如果只希望上传指定key的文件,并且不允许修改,那么可以将下面的 insertOnly 属性值设为1	
	obj["scope"] = scope;

	// 文件在多少天后被删除,七牛将文件上传时间与指定的deleteAfterDays天数相加,
	// 得到的时间入到后一天的午夜(CST, 中国标准时间),从而得到文件删除开始时间。
	//例如文件在2015年1月1日上午10:00 CST上传,指定deleteAfterDays为3天,那么会在2015年1月5日00 : 00 CST之后当天内删除文件。
	obj["deleteAfterDays"] = 7;

	// 限定为“新增”语意。
	// 如果设置为非0值,则无论scope设置为什么形式,仅能以“新增”模式上传文件。
	obj["insertOnly"] = 0;

	// 上传凭证有效截止时间。
	// Unix时间戳,单位:秒。该截止时间为上传完成后,在七牛空间生成文件的校验时间,而非上传的开始时间,
	// 一般建议设置为“上传开始时间 + 3600s”,用户可根据具体的业务场景对凭证截止时间进行调整。
	int deadline = QDateTime::currentDateTimeUtc().toTime_t() + 3600;
	obj["deadline"] = deadline;

	doc.setObject(obj);


	return Auth::genUploadToken(ak, sk, doc.toJson(QJsonDocument::Compact));
}
void ApiClient::putResponse(QUrl url, QString headerName, QString headerValue) {
    // Request and get from manager
    qDebug() << "getResponse" << url.toString();
    QNetworkRequest req(url);
    req.setRawHeader("Content-Type", "application/json");

    QByteArray hName;
    hName.append(headerName);
    QByteArray hValue;
    hValue.append(headerValue);
    req.setRawHeader(hName, hValue);

    QJsonDocument wrap;
    QJsonObject object;

    QString b64SignalingKey(this->conf->getSignalingKey().toBase64());
    object["signalingKey"] = b64SignalingKey;
    object["supportsSms"] = false;
    object["registrationId"] = QString::number(this->conf->getRegistrationId());

    wrap.setObject(object);

    QNetworkReply *reply = this->mgr.put(req, wrap.toJson());

    // XXX: This is where the ssl must be ignored for it to work
    // but we haven't told the user yet what is ignored o_O
    // Potentially nasty
    reply->ignoreSslErrors();
    QObject::connect(reply, &QNetworkReply::sslErrors, this, &ApiClient::printSslErrors);

    // signal handler picks up from here
}