Exemplo n.º 1
1
bool configreader::deserialize(const QString &acsfilename)
{
    QFile file(acsfilename);
    if (file.open(QIODevice::ReadOnly|QIODevice::Text) == false) return false;
    QTextStream in(&file);
    QString str;
    while (!in.atEnd())
    {
        str += in.readLine();
    }
    QTextCodec *codec = QTextCodec::codecForName("UTF-8");
    QByteArray doc = codec->fromUnicode(str);
    QJsonParseError jerror;
    QJsonDocument jDocument = QJsonDocument::fromJson(doc, &jerror);
    if (jerror.error != QJsonParseError::NoError) return false;
    QJsonObject jRoot = jDocument.object();
    if (jRoot["exams"] == QJsonValue::Undefined) return false;
    QJsonArray examarray = jRoot["exams"].toArray();
    QJsonObject examobj;
    for (int i = 0; i < examarray.size(); ++i)
    {
        exam currexam;
        examobj = examarray[i].toObject();
        if (examobj["title"] == QJsonValue::Undefined) return false;
        currexam.title = examobj["title"].toString();
        if (examobj["points"] == QJsonValue::Undefined) return false;
        QJsonArray pointsarray = examobj["points"].toArray();
        QJsonObject pointobj;
        for (int j = 0; j < pointsarray.size(); ++j)
        {
            currexam.point.push_back(pointsarray[j].toInt());
        }
        _cexam.push_back(currexam);
    }

    return true;
}
Exemplo n.º 2
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++;
        }
    }    
}
Exemplo n.º 3
0
void ShellUI::reloadConfig()
{
    m_properties.clear();
    qDeleteAll(m_bindings);
    m_bindings.clear();

    QJsonObject object;
    if (m_config.contains("Shell")) {
        object = m_config["Shell"].toObject();
    } else {
        QJsonDocument doc = QJsonDocument::fromJson(defaultShell);
        object = doc.object();
    }
    QJsonObject properties = object["properties"].toObject();
    for (auto i = properties.constBegin(); i != properties.constEnd(); ++i) {
        setProperty(qPrintable(i.key()), i.value().toVariant());
        m_properties << i.key();
    }

    QJsonArray bindings = object["bindings"].toArray();
    for (auto i = bindings.begin(); i != bindings.end(); ++i) {
        QJsonObject binding = (*i).toObject();
        int key = binding["key"].toInt(-1);
        QString exec = binding["exec"].toString();
        if (key < 0 || exec.isEmpty()) {
            qDebug() << "Cannot parse binding" << binding;
            continue;
        }
        Binding *b = m_client->addKeyBinding(key, 0);
        m_bindings << b;
        connect(b, &Binding::triggered, [exec]() { QProcess::startDetached(exec); });
    }

    for (UiScreen *screen: m_screens) {
        loadScreen(screen);
    }
}
void GeocodeDataManager::replyFinished(QNetworkReply* reply)
{
    QByteArray json = reply->readAll();
    qDebug() << "Reply = " << json;
    qDebug() << "URL = " << reply->url();
    QString strUrl = reply->url().toString();

    // json is a QString containing the data to convert
    QJsonDocument doc = QJsonDocument::fromJson(json);
    if( doc.isEmpty() )
    {
        emit errorOccured(QString("Cannot convert to QJson object: %1").arg(QString(json)));
        return;
    }

    QJsonObject root = doc.object();

    int code = root["Status"].toObject()["code"].toInt();
    if(code != 200)
    {
        emit errorOccured(QString("Code of request is: %1").arg(code));
        return;
    }

    QJsonArray placeMarks = root["Placemark"].toArray();
    if(placeMarks.count() == 0)
    {
        emit errorOccured(QString("Cannot find any locations"));
        return;
    }

    double east  = placeMarks[0].toObject()["Point"].toObject()["coordinates"].toArray()[0].toDouble();
    double north = placeMarks[0].toObject()["Point"].toObject()["coordinates"].toArray()[1].toDouble();

    emit coordinatesReady(east, north);

}
Exemplo n.º 5
0
QMap<QString, TLType> GeneratorNG::readTypes(const QJsonDocument &document)
{
    const QJsonArray constructors = document.object().value("constructors").toArray();

    QMap<QString, TLType> types;

    for (int i = 0; i < constructors.count(); ++i) {
        const QJsonObject obj = constructors.at(i).toObject();

        const QString predicateName = formatName1stCapital(obj.value("predicate").toString());
        const quint32 predicateId = obj.value("id").toString().toInt();
        const QString typeName = formatType(obj.value("type").toString());

        TLType tlType = types.value(typeName);
        tlType.name = typeName;

        TLSubType tlSubType;
        tlSubType.name = predicateName;
        tlSubType.id = predicateId;

        const QJsonArray params = obj.value("params").toArray();

        foreach (const QJsonValue &paramValue, params) {
            const QJsonObject &paramObj = paramValue.toObject();
            const QString paramName = formatMember(paramObj.value("name").toString());

            const QString paramType = paramObj.value("type").toString();

            tlSubType.members.append(TLParam(paramName, formatType(paramType)));
        }

        tlType.subTypes.append(tlSubType);
        types.insert(typeName, tlType);
    }

    return types;
}
Exemplo n.º 6
0
void Config::loadLayouts()
{
    QFile layoutsFile(resourcesPath() + "/layouts.ltf");
    if( layoutsFile.open(QIODevice::ReadOnly) )
    {
        QJsonDocument jsonDoc = QJsonDocument::fromJson(layoutsFile.readAll());
        QJsonArray jsonArray = jsonDoc.array();
        for( int i = 0; i < jsonArray.count(); i++ )
        {
            Layout *layout = new Layout;
            layout->name = jsonArray.at(i).toObject().value("layout").toString();
            layout->title = jsonArray.at(i).toObject().value("title").toString();
            layout->symbols = jsonArray.at(i).toObject().value("symbols").toString();
            m_layouts.append(layout);
            if( layout->name == m_lastLayout )
            {
                m_currentLayout = layout;
            }
        }
        if( m_layouts.count() < 1 )
        {
            qDebug()<<"No layouts loaded!";
            exit(EXIT_FAILURE);
        }
        if( !m_currentLayout )
        {
            m_currentLayout = m_layouts.at(0);
        }
        loadLessons();
        loadGeneratedLessons();
    }
    else
    {
        qDebug()<<"Can't open layouts file!";
        exit(EXIT_FAILURE);
    }
}
Exemplo n.º 7
0
void Serializable::Message::read (const QJsonObject &json)
{
   timestamp  = json["timestamp" ].toInt                (                           );
   authorSha1 = json["authorSha1"].toString             (                           );
   isRead     = json["isRead"    ].toBool               (                           );
   direction  = static_cast<Media::Media::Direction>    ( json["direction"].toInt() );
   type       = static_cast<Serializable::Message::Type>( json["type"     ].toInt() );
   id         = json["id"        ].toVariant().value<uint64_t>(                     );
   deliveryStatus = static_cast<Media::TextRecording::Status>(json["deliveryStatus"].toInt());

   QJsonArray a = json["payloads"].toArray();
   for (int i = 0; i < a.size(); ++i) {
      QJsonObject o = a[i].toObject();
      Payload* p = new Payload();
      p->read(o);
      payloads << p;

      if (p->mimeType == "text/plain") {
         m_PlainText = p->payload;
         m_HasText   = true;
      }
      else if (p->mimeType == "text/html") {
         m_HTML    = p->payload;
         m_HasText = true;
      }
   }

   //Load older conversation from a time when only 1 mime/payload pair was supported
   if (!json["payload"   ].toString().isEmpty()) {
      Payload* p  = new Payload();
      p->payload  = json["payload"  ].toString();
      p->mimeType = json["mimeType" ].toString();
      payloads << p;
      m_PlainText = p->payload;
      m_HasText   = true;
   }
}
QVariant SQLExtDatabase::executeSql(const QString &q) const
{
    QSqlDatabase db = QSqlDatabase::database(m_connectionName);
    QSqlQuery query = db.exec(q);
    bool error = query.lastError().type() != QSqlError::NoError;
    QJsonObject res;

    res.insert("error", error);

    if (error)
    {
        res.insert("errorStr", query.lastError().text());
        return res;
    }

    if (query.isSelect())
    {
        QJsonArray rows;
        int size = 0;
        int fields = query.record().count();
        while (query.next())
        {
            QJsonObject value;
            for (int i = 0; i < fields; ++i)
                value.insert(query.record().fieldName(i), query.value(i).toString());
            rows.append(value);
            ++size;
        }
        res.insert("length", size);
        res.insert("items", rows);
        return res;
    }

    res.insert("rowsAffected", query.numRowsAffected());
    res.insert("insertId", query.lastInsertId().toString());
    return res;
}
Exemplo n.º 9
0
/*!
 * \brief JsonParser::addObject
 * Dodaje obiekt do pliku json
 * \param type typ obiektu
 * \param speed prędkość obiektu
 * \param model model tabeli ze wskazanymi punktami
 */
void JsonParser::addObject(QString type, double speed, QStandardItemModel *model)
{
    QJsonValue type_ = type;
    QJsonObject object;
    object.insert("TypeObject", type_);

    object.insert("Speed", speed);

    QJsonArray array;
    QJsonObject point;
    QJsonValue value;

    for (int i = 0; i <model->rowCount(); i++) {
        value = model->takeItem(i,0)->data(Qt::DisplayRole).toDouble();
        point.insert("CoordX", value);
        value = model->takeItem(i,1)->data(Qt::DisplayRole).toDouble();
        point.insert("CoordY", value);
        array.insert(i,point);
    }
    value = array;
    object.insert("Points", value);
    objects.push_back(object);

    QJsonDocument d;
    QJsonObject obj;
    obj.insert("Objects", static_cast<QJsonValue>(objects));
    d.setObject(obj);
    d.toJson();


    QFile file;
    file.setFileName(fileName);
    file.open(QIODevice::WriteOnly | QIODevice::Text);

    file.write(d.toJson());
    file.close();
}
Exemplo n.º 10
0
void JSONExporter::Export(ResourceController *resources, QString filename)
{
    //get the data
    QList<Image*> images = resources->GetAllImages();
    QList<TileLayer*> layers = resources->GetAllLayers();
    LevelProperties *levelProps = resources->GetLevelProperties();

    //set up the JSON document
    QJsonObject documentObject;
    QJsonArray imageArray;
    QJsonArray layerArray;
    QJsonObject levelPropsObject;

    levelPropsObject["properties"] = ResourcePropertiesToJSON(levelProps);
    levelPropsObject["Tileset ID"] = levelProps->GetTilesetID();

    Image *currentImage;
    foreach(currentImage, images)
    {
        QJsonObject imageObject;
        imageObject["properties"] = ResourcePropertiesToJSON(currentImage);

        imageArray.append(imageObject);
    }
Exemplo n.º 11
0
    /**
     * @brief ClassMethod::toJson
     * @return
     */
    QJsonObject ClassMethod::toJson() const
    {
        QJsonObject result = BasicElement::toJson();

        result.insert(sectionMark, m_Section);
        result.insert(typeMark, m_Type);
        result.insert(csMark, m_ConstStatus);
        result.insert(slotMark, m_SlotStatus);
        result.insert(signalMark, m_SignalStatus);
        result.insert(rtMark, m_ReturnTypeId.toJson());
        result.insert(rhsiMark, int(m_RhsIdentificator));

        QJsonArray parameters;
        for (auto &&value : m_Parameters)
            parameters.append(value->toJson());
        result.insert(paramsMark, parameters);

        QJsonArray lhsIdentificators;
        for (auto &&id : m_LhsIdentificators)
            lhsIdentificators.append(int(id));
        result.insert(lhsMark, lhsIdentificators);

        return result;
    }
Exemplo n.º 12
0
void QEGLPlatformCursor::initCursorAtlas()
{
    static QByteArray json = qgetenv("QT_QPA_EGLFS_CURSOR");
    if (json.isEmpty())
        json = ":/cursor.json";

    QFile file(QString::fromUtf8(json));
    if (!file.open(QFile::ReadOnly)) {
        m_visible = false;
        return;
    }

    QJsonDocument doc = QJsonDocument::fromJson(file.readAll());
    QJsonObject object = doc.object();

    QString atlas = object.value(QLatin1String("image")).toString();
    Q_ASSERT(!atlas.isEmpty());

    const int cursorsPerRow = object.value(QLatin1String("cursorsPerRow")).toDouble();
    Q_ASSERT(cursorsPerRow);
    m_cursorAtlas.cursorsPerRow = cursorsPerRow;

    const QJsonArray hotSpots = object.value(QLatin1String("hotSpots")).toArray();
    Q_ASSERT(hotSpots.count() == Qt::LastCursor + 1);
    for (int i = 0; i < hotSpots.count(); i++) {
        QPoint hotSpot(hotSpots[i].toArray()[0].toDouble(), hotSpots[i].toArray()[1].toDouble());
        m_cursorAtlas.hotSpots << hotSpot;
    }

    QImage image = QImage(atlas).convertToFormat(QImage::Format_ARGB32_Premultiplied);
    m_cursorAtlas.cursorWidth = image.width() / m_cursorAtlas.cursorsPerRow;
    m_cursorAtlas.cursorHeight = image.height() / ((Qt::LastCursor + cursorsPerRow) / cursorsPerRow);
    m_cursorAtlas.width = image.width();
    m_cursorAtlas.height = image.height();
    m_cursorAtlas.image = image;
}
Exemplo n.º 13
0
void RemoteModel::parseDirectoryListing(const QString& json, const QVariant& userdata)
{
    // Load new JSON root document assuming it's an array
    QJsonDocument doc = QJsonDocument::fromJson(json.toUtf8());
    if(doc.isNull() || !doc.isArray())
        return;
    QJsonArray array = doc.array();

    // Get model index to store the new data under
    QModelIndex parent = userdata.toModelIndex();
    RemoteModelItem* parentItem = const_cast<RemoteModelItem*>(modelIndexToItem(parent));

    // An invalid model index indicates that this is a new root item. This means the old one needs to be entirely deleted first.
    if(!parent.isValid())
    {
        // Clear root item
        beginResetModel();
        delete rootItem;
        rootItem = new RemoteModelItem();
        endResetModel();

        // Set parent model index and parent item to the new values
        parent = QModelIndex();
        parentItem = rootItem;
    }

    // Insert data
    beginInsertRows(parent, 0, array.size());
    QList<RemoteModelItem*> items = RemoteModelItem::loadArray(QJsonValue(array), parentItem);
    foreach(RemoteModelItem* item, items)
        parentItem->appendChild(item);
    endInsertRows();

    // Emit directory listing parsed signal
    emit directoryListingParsed(parent);
}
Exemplo n.º 14
0
QList<Note*> ServerCommunicator::fromJson(QByteArray json) {
    QJsonDocument document = QJsonDocument::fromJson(json);
    QList<Note*> notes;
    // handle an array of notes
    if(document.isArray()) {
        QJsonArray array = document.array();
        for(int i = 0; i < array.size(); i++) {
           QJsonValue value = array.at(i);
           if(value.isObject()) {
               QJsonObject obj = value.toObject();
               Note *note = new Note(obj.value("heading").toString(), obj.value("body").toString());
               note->setRemoteId(obj.value("id").toDouble());
               notes.append(note);
           }
        }
    } else {
        QJsonObject obj = document.object();
        Note *note = new Note(obj.value("heading").toString(), obj.value("body").toString());
        note->setRemoteId(obj.value("id").toDouble());
        notes.append(note);
    }

    return notes;
}
Exemplo n.º 15
0
void PlayFilesModel::parseData(const QJsonArray &array)
{
    beginResetModel();
    m_playList.reserve(array.size());
    for(const auto& record: array)
    {
        m_playList.push_back(PlayItem::fromJson(record.toObject()));

    }
    endResetModel();
    if(!m_playList.isEmpty())
    {
        emit mediaPlayListChanged();
    }
}
Exemplo n.º 16
0
void PanelMenu::showMenu(int x, int y)
{
    if (m_menuManager && m_menuManager->isValid()){
        QDBusPendingReply<QDBusObjectPath> pr = m_menuManager->RegisterMenu();
        if (pr.count() == 1)
        {
            QDBusObjectPath op = pr.argumentAt(0).value<QDBusObjectPath>();
            m_menuInterfacePath = op.path();
            DBusMenu *m_menu = new DBusMenu(m_menuInterfacePath,this);
            connect(m_menu,&DBusMenu::MenuUnregistered,m_menu,&DBusMenu::deleteLater);
            connect(m_menu,&DBusMenu::ItemInvoked,this,&PanelMenu::onItemInvoked);

            QJsonObject targetObj;
            targetObj.insert("x",QJsonValue(x));
            targetObj.insert("y",QJsonValue(y));
            targetObj.insert("isDockMenu",QJsonValue(false));

            QJsonArray contentArry;
            contentArry.append(createRadioItemObj(tr("Fashion mode"),ToFashionMode,DockModeGroup,m_dockModeData->getDockMode() == Dock::FashionMode));
            contentArry.append(createRadioItemObj(tr("Efficient mode"),ToEfficientMode,DockModeGroup,m_dockModeData->getDockMode() == Dock::EfficientMode));
            contentArry.append(createRadioItemObj(tr("Classic mode"),ToClassicMode,DockModeGroup,m_dockModeData->getDockMode() == Dock::ClassicMode));
            contentArry.append(createItemObj("",OperationType(-1)));
            contentArry.append(createRadioItemObj(tr("Keep showing"),ToKeepShowing,HideModeGroup,m_dockModeData->getHideMode() == Dock::KeepShowing));
            contentArry.append(createRadioItemObj(tr("Keep hidden"),ToKeepHidden,HideModeGroup,m_dockModeData->getHideMode() == Dock::KeepHidden));
            contentArry.append(createRadioItemObj(tr("Smart hide"),ToSmartHide,HideModeGroup,m_dockModeData->getHideMode() == Dock::SmartHide));
            contentArry.append(createItemObj("",OperationType(-1)));
            contentArry.append(createItemObj(tr("Notification area settings"),ToPluginSetting));

            QJsonObject contentObj;
            contentObj.insert("items",contentArry);
            targetObj.insert("menuJsonContent",QString(QJsonDocument(contentObj).toJson()));

            m_menu->ShowMenu(QString(QJsonDocument(targetObj).toJson()));
        }
    }
}
Exemplo n.º 17
0
void ImportDialog::setImportTypes() {

    switchToResourcesParentIfRequired();
    QFile config("resources/config/config.json");
    config.open(QFile::ReadOnly | QFile::Text);
    QJsonDocument document = QJsonDocument::fromJson(config.readAll());
    if (!document.isNull() && !document.isEmpty()) {

        QString importFormatsInfo;
        QString importFormatsFilterList;
        QHash<QString, QString> iconsMap;

        QJsonObject configObject = document.object();
        if (!configObject.isEmpty()) {
            QJsonArray fileFormats = configObject["importFormats"].toArray();
            int formatsCounter = 0;
            foreach (const QJsonValue& fileFormat, fileFormats) {
                QJsonObject fileFormatObject = fileFormat.toObject();

                QString ext(fileFormatObject["extension"].toString());
                QString icon(fileFormatObject.value("icon").toString());

                if (formatsCounter > 0) {
                    importFormatsInfo.append(",");
                }

                // set ' or' on last import type text
                if (formatsCounter == fileFormats.count() - 1) {
                    importFormatsInfo.append(" or");
                }

                importFormatsFilterList.append(QString("*.%1 ").arg(ext));
                importFormatsInfo.append(" .").append(ext);
                iconsMap[ext] = icon;
                formatsCounter++;
            }
Exemplo n.º 18
0
void ConfigHelper::exportGuiConfigJson(const QString &file)
{
    QJsonArray confArray;
    int size = model->rowCount();
    for (int i = 0; i < size; ++i) {
        Connection *con = model->getItem(i)->getConnection();
        QJsonObject json;
        json["remarks"] = QJsonValue(con->profile.name);
        json["method"] = QJsonValue(con->profile.method.toLower());
        json["password"] = QJsonValue(con->profile.password);
        json["server_port"] = QJsonValue(con->profile.serverPort);
        json["server"] = QJsonValue(con->profile.serverAddress);
        confArray.append(QJsonValue(json));
    }

    QJsonObject JSONObj;
    JSONObj["configs"] = QJsonValue(confArray);
    JSONObj["localPort"] = QJsonValue(1080);
    JSONObj["shareOverLan"] = QJsonValue(false);

    QJsonDocument JSONDoc(JSONObj);

    QFile JSONFile(file);
    JSONFile.open(QIODevice::WriteOnly | QIODevice::Text);
    if (!JSONFile.isOpen()) {
        qCritical() << "Error: cannot open " << file;
        return;
    }
    if(!JSONFile.isWritable()) {
        qCritical() << "Error: cannot write into " << file;
        return;
    }

    JSONFile.write(JSONDoc.toJson());
    JSONFile.close();
}
Exemplo n.º 19
0
void MainWindow::handleCategoryResp(QByteArray data)
{
    if(!categorieMap.contains("Uncategorized")) {
        QStandardItem *uncategorized = new QStandardItem("Uncategorized");
        uncategorized->setData(QVariant::fromValue(QString("user/" + userId + "/category/global.uncategorized")),CATEGORY_ENTRY_ID);
        treeModel->appendRow(uncategorized);
        categorieMap.insert("Uncategorized",uncategorized);
    }

    QJsonParseError jerror;
    QJsonDocument doc = QJsonDocument::fromJson(data,&jerror);
    qDebug()<<doc;
    if(jerror.error == QJsonParseError::NoError || ! doc.isEmpty()) {
        QJsonArray arr = doc.array();
        QString tempLabel,tempId;

        for(int row = 0;row<arr.size();row++)
        {
            QJsonObject obj = arr[row].toObject();
            tempLabel = obj.value("label").toString();
            tempId = obj.value("id").toString();
            qDebug()<<tempLabel;
            if(!categorieMap.contains(tempLabel)) {
                QStandardItem *category = new QStandardItem(tempLabel);
                category->setData(QVariant::fromValue(tempId),CATEGORY_ENTRY_ID);
                treeModel->appendRow(category);
                categorieMap.insert(tempLabel,category);
            }
        }

    }
    else {
        qDebug() << "error when parsing json";
    }

}
Exemplo n.º 20
0
bool MainWindow::on_subscibe()
{
    QJsonObject *json = new QJsonObject();
    QJsonObject *j1 = new QJsonObject();
    QJsonObject *j2 = new QJsonObject();
    QJsonArray *jarr = new QJsonArray();

    j1->insert("id",QJsonValue("user/" + userId + "/category/tech"));
    j1->insert("label",QJsonValue(QString("tech")));

    //j2->insert("id",userIdjson);
    //j2->insert("label",QJsonValue(QString("weekly")));

    json->insert("id",QJsonValue("feed/" + subDialog->getFeedUrl()));
    json->insert("title",QJsonValue(subDialog->getFeedTitle()));

    jarr->insert(0,*j1);
    //jarr->insert(1,*j2);

    json->insert("categories",*jarr);

    QJsonDocument *docu =  new QJsonDocument(*json);
    //qDebug() << docu->toJson();

    request.setUrl(SUBSCRIPTIONS_URL);
    request.setHeader(QNetworkRequest::ContentTypeHeader,"application/json");
    o2req->post(request,docu->toJson());
    reqCategories();

    delete json;
    delete j1;
    delete j2;
    delete jarr;

    return true;
}
Exemplo n.º 21
0
void TomboyItemUploadJob::start()
{
    // Convert note to JSON
    QJsonObject jsonNote;
    jsonNote[QLatin1String("guid")] = mSourceItem.remoteId();
    switch (mJobType) {
    case JobType::DeleteItem:
        jsonNote[QLatin1String("command")] = QStringLiteral("delete");
        break;
    case JobType::AddItem:
        jsonNote[QLatin1String("create-date")] = getCurrentISOTime();
    // Missing break is intended
    case JobType::ModifyItem:
        jsonNote[QLatin1String("title")] = mNoteContent->headerByType("subject")->asUnicodeString();
        jsonNote[QLatin1String("note-content")] = mNoteContent->mainBodyPart()->decodedText();
        jsonNote[QLatin1String("note-content-version")] = QStringLiteral("1");
        jsonNote[QLatin1String("last-change-date")] = getCurrentISOTime();
    }

    // Create the full JSON object
    QJsonArray noteChanges;
    noteChanges.append(jsonNote);
    QJsonObject postJson;
    postJson[QLatin1String("note-changes")] = noteChanges;
    postJson[QLatin1String("latest-sync-revision")] = QString::number(++mRemoteRevision);
    QJsonDocument postData;
    postData.setObject(postJson);

    // Network request
    QNetworkRequest request = QNetworkRequest(QUrl(mContentURL));
    request.setHeader(QNetworkRequest::ContentTypeHeader, QStringLiteral("application/json; boundary=7d44e178b0439"));
    request.setHeader(QNetworkRequest::ContentLengthHeader, postData.toJson().length());
    mReply = mRequestor->put(request, QList<O0RequestParameter>(), postData.toJson());
    connect(mReply, &QNetworkReply::finished, this, &TomboyItemUploadJob::onRequestFinished);
    qCDebug(TOMBOYNOTESRESOURCE_LOG) << "TomboyItemUploadJob: Start network request";
}
Exemplo n.º 22
0
VNoteFile *VNoteFile::fromJson(VDirectory *p_directory,
                               const QJsonObject &p_json,
                               FileType p_type,
                               bool p_modifiable)
{
    // Attachments.
    QJsonArray attachmentJson = p_json[DirConfig::c_attachments].toArray();
    QVector<VAttachment> attachments;
    for (int i = 0; i < attachmentJson.size(); ++i) {
        QJsonObject attachmentItem = attachmentJson[i].toObject();
        attachments.push_back(VAttachment(attachmentItem[DirConfig::c_name].toString()));
    }

    return new VNoteFile(p_directory,
                         p_json[DirConfig::c_name].toString(),
                         p_type,
                         p_modifiable,
                         QDateTime::fromString(p_json[DirConfig::c_createdTime].toString(),
                                               Qt::ISODate),
                         QDateTime::fromString(p_json[DirConfig::c_modifiedTime].toString(),
                                               Qt::ISODate),
                         p_json[DirConfig::c_attachmentFolder].toString(),
                         attachments);
}
Exemplo n.º 23
0
bool FileManager::open( QString path, QList<TrackModel*>* const trackModels, CategoryData* const categoryData, ImageData* const imageData )
{
    trackModels->clear();

    QString jsonFromFile;
    QFile file;
    file.setFileName( path );
    file.open( QIODevice::ReadOnly | QIODevice::Text );
    jsonFromFile = file.readAll();
    file.close();

    // Get jsonObject out of jsonDoc
    QJsonDocument jsonDoc    = QJsonDocument::fromJson( jsonFromFile.toUtf8() );
    QJsonObject   jsonObject = jsonDoc.object();

    // Parse track data
    QJsonArray tracksArray = jsonObject.value("tracks").toArray();
    for ( int i = 0; i < tracksArray.size(); i++ )
    {
        QJsonObject trackObj    = tracksArray.at(i).toObject();
        TrackModel* trackModel  = new TrackModel( trackObj );
        trackModels->append( trackModel );
    }

    // Parse category data
    if ( jsonObject.contains("categoryPath") )
    {
        QString categoryPath = jsonObject.value("categoryPath").toString("");
        FileManager::import( categoryPath, categoryData, imageData );
        qDebug() << "Loaded category data from" << categoryPath;
    }
    else
        qDebug() << "No category data found...";

    return trackModels->size() > 0;
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
ComparisonInput_t JsonFilterParametersReader::readComparisonInput(const QString name, ComparisonInput_t defaultValue, int arrayIndex)
{
    BOOST_ASSERT(m_CurrentFilterIndex.isEmpty() == false);
    if (m_CurrentFilterIndex.contains(name) == false)
    {
        return defaultValue;
    }

    if (m_CurrentFilterIndex.value(name).isArray())
    {
        QJsonArray cInputsArray = m_CurrentFilterIndex.value(name).toArray();
        if (cInputsArray.size() > arrayIndex && cInputsArray[arrayIndex].isObject())
        {
            QJsonObject cInputObject = cInputsArray[arrayIndex].toObject();
            ComparisonInput_t cInput;
            if (cInput.readJson(cInputObject) == true)
            {
                return cInput;
            }
        }
    }

    return defaultValue;
}
SimpleTask *SimpleTaskManager::STFromJSON(QJsonObject obj, SimpleTask *father)
{
    SimpleTask *_st;
    _st = new SimpleTask;

    if(father != NULL)
    {
        _st->_father = father;
    }
    else
    {
        _st->_manager = this;
    }

    _st->_name = obj.value("name").toString().toUtf8().constData();
    _st->_description = obj.value("description").toString().toUtf8().constData();
    _st->_id = obj.value("id").toString().toUInt();
    _st->_done = IntToSTDoneType(obj.value("done").toString().toInt());
    _st->_timeCreation = obj.value("timeCreation").toString().toULongLong();
    _st->_timeDone = obj.value("timeDone").toString().toULongLong();
    _st->_timeStart = obj.value("timeStart").toString().toULongLong();
    _st->_timeDue = obj.value("timeDue").toString().toULongLong();
    _st->_priority = obj.value("priority").toString().toInt();
    _st->_level = obj.value("level").toString().toUInt();

    QJsonArray subTasks = obj.value("subTasks").toArray();

    for(auto i = subTasks.begin(); i != subTasks.end(); ++i)
    {
        QJsonValue subTask = *i;
        SimpleTask *_subTask = STFromJSON(subTask.toObject(), _st);
        _st->addSubTask(_subTask);
    }

    return _st;
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
QVector<double> JsonFilterParametersReader::readArray(const QString name, QVector<double> value)
{
    BOOST_ASSERT(m_CurrentFilterIndex.isEmpty() == false);
    if (m_CurrentFilterIndex.contains(name) == false)
    {
        return value;
    }

    if (m_CurrentFilterIndex.value(name).isArray())
    {
        QJsonArray jsonArray = m_CurrentFilterIndex.value(name).toArray();
        QVector<double> vector;
        for (QJsonArray::iterator iter = jsonArray.begin(); iter != jsonArray.end(); ++iter)
        {
            if ((*iter).isDouble())
            {
                vector.push_back((*iter).toDouble());
            }
        }
        return vector;
    }

    return value;
}
Exemplo n.º 27
0
bool QPubNub::decrypt(const QJsonArray& messages, const QStringList& channels) {
  QPubNubCrypt crypt(m_cipherKey);
  for (int i=0,len=messages.size();i<len;++i) {
    int errorCode = 0;
    QJsonValue value(crypt.decrypt(messages[i].toString().toLocal8Bit(), errorCode));
    if (errorCode != 0) {
      char errorString[1024+1];
      ERR_error_string_n(errorCode, errorString, 1024);
      emit error(errorString, errorCode);
    } else {
      emit message(value, m_timeToken, channels[i]);
    }
  }
  return true;
}
Exemplo n.º 28
0
bool UserBank::load()
{
    QJsonArray a;
    QJsonDocument d;
    bool ok = loadJsonFile("giftrecord.json", d);
    a = d.array();

    if (!ok) {
        qDebug()<< " load record file failed!!";
        return false;
    }
    else {
         qDebug()<< " load record file succeed!!";
    }
    for (int i=0; i<a.size(); i++) {
        QJsonObject b = a[i].toObject();
        record[b["name"].toString()] = b["money"].toInt();
    }
    record[myTr("麻由の天蝎1000")] = 10000000;
    record[myTr("麻由の天蝎10000")] = 10000000;
    record[myTr("麻由の天蝎1000000")] = 10000000;

    return true;
}
Exemplo n.º 29
0
QJsonArray QuickModWriter::versionToJson(const QuickMod &mod)
{
	QJsonArray array;
	foreach (const QuickModVersion &ver, mod.versions)
	{
		QJsonObject obj;
		obj.insert("name", ver.name);
		if (!ver.version.isNull() && ver.name != ver.version)
		{
			obj.insert("version", ver.version);
		}
		obj.insert("type", ver.type);
		obj.insert("mcCompat", QJsonArray::fromStringList(ver.mcCompat));
		QJsonArray refs;
		for (auto ref : ver.references.keys())
		{
			QJsonObject refObj;
			refObj.insert("uid", ref);
			refObj.insert("version", ver.references[ref].version);
			refObj.insert("type", ver.references[ref].type);
			if (ver.references[ref].isSoft)
			{
				refObj.insert("isSoft", true);
			}
			refs.append(refObj);
		}
		obj.insert("references", refs);
		if (!ver.forgeCompat.isEmpty())
		{
			obj.insert("forgeCompat", ver.forgeCompat);
		}
		if (!ver.liteloaderCompat.isEmpty())
		{
			obj.insert("liteloaderCompat", ver.liteloaderCompat);
		}
		obj.insert("sha1", ver.sha1);
		switch (ver.installType)
		{
		case QuickModVersion::ForgeMod:      obj.insert("installType", QStringLiteral("forgeMod"));      break;
		case QuickModVersion::ForgeCoreMod:  obj.insert("installType", QStringLiteral("forgeCoreMod"));  break;
		case QuickModVersion::LiteLoaderMod: obj.insert("installType", QStringLiteral("liteloaderMod")); break;
		case QuickModVersion::Extract:       obj.insert("installType", QStringLiteral("extract"));	    break;
		case QuickModVersion::ConfigPack:    obj.insert("installType", QStringLiteral("configPack"));    break;
		case QuickModVersion::Group:	     obj.insert("installType", QStringLiteral("group"));	        break;
		default: obj.insert("installType", QString("forgeMod")); break;
		}
		QJsonArray urls;
		for (auto download : ver.urls)
		{
			urls.append(downloadToJson(download, ver.urls.size() == 1));
		}
		obj.insert("urls", urls);
		array.append(obj);
	}
	return array;
}
Exemplo n.º 30
0
void NewWakuSettingsWindow::loadPresets()
{
  QStringList dir = QStandardPaths::standardLocations(QStandardPaths::DataLocation);
  if (dir.empty()) {
    mwin->insLog("save directory is not available");
    return;
  }
  QFile file(dir[0] + "/newWakuSettings.json");
  if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
    file.close();
    mwin->insLog("opening settings file failed");
    return;
  }

  QJsonDocument jsd = QJsonDocument::fromJson(file.readAll());

  QJsonArray pages = jsd.array();
  for (int i = 0; i < pages.size(); ++i) {
    ui->presetes->addItem(pages[i].toObject()["title"].toString(),
        pages[i].toObject()["data"].toObject());
  }

  file.close();
}