/**
 * @brief Function that retrieves network reply from the API, formats the
 *        response and inserts it in Qlabel object displayText to show the
 *        results on the interface.
 */
void MainWindow::networkData(){
    //tests for network error
     QNetworkReply::NetworkError err = reply->error();
     if (err != QNetworkReply::NoError) {
         qDebug() << reply->errorString();
         return;
     }

    //store the network's response in a string
    QString response = (QString)reply->readAll();

    //network reply is stored in JSON format; get only the OCR'd text results
    QJsonDocument jsonDoc = QJsonDocument::fromJson(response.toUtf8());
    QJsonObject jsonObj = jsonDoc.object();
    QJsonArray jsonArr = jsonObj["ParsedResults"].toArray();
    foreach(const QJsonValue& value, jsonArr) {
        QJsonObject obj = value.toObject();
        text.append(obj["ParsedText"].toString());
    }
Esempio n. 2
0
bool MainWindow::Open()
{
    QString tempFileName = QFileDialog::getOpenFileName(this, tr("Open file"));
    if (!tempFileName.isEmpty())
    {
        QFile json(tempFileName);
        if(json.open(QIODevice::ReadOnly))
        {
            QJsonParseError  parseError;
            QJsonDocument jsonDoc = QJsonDocument::fromJson(json.readAll(), &parseError);
            if(parseError.error == QJsonParseError::NoError)
            {
                if(jsonDoc.isObject())
                {
                    m_model->Clear();
                    QJsonObject jsonObject = jsonDoc.object();
                    for (QJsonObject::Iterator iter = jsonObject.begin(); iter != jsonObject.end(); ++iter)
                    {
                        Population newPopulation(iter.key(), iter.value().toInt());
                        m_model->append(newPopulation);
                    }
                    m_fileName = tempFileName;
                    this->setWindowTitle(m_fileName);
                    ui->menuInsert->setEnabled(true);
                    m_isSomethingChanged  = false;
                }
            }else
            {
                json.close();
                return false;
            }
            json.close();
            m_stack->clear();
            return true;

        }else
        {
            return false;
        }
    }
    return true;
}
void MusicTranslationThread::downLoadFinished()
{
    if(m_reply && m_reply->error() == QNetworkReply::NoError)
    {
        QByteArray bytes = m_reply->readAll();
#ifdef MUSIC_GREATER_NEW
        QJsonParseError jsonError;
        QJsonDocument parseDoucment = QJsonDocument::fromJson(bytes, &jsonError);
        ///Put the data into Json
        if(jsonError.error != QJsonParseError::NoError ||
           !parseDoucment.isObject())
        {
            deleteAll();
            emit downLoadDataChanged(QString());
            return ;
        }

        QJsonObject jsonObject = parseDoucment.object();
        if(jsonObject.contains("error"))
        {
            emit downLoadDataChanged(QString());
            deleteAll();
            return ;
        }

        if(jsonObject.contains("trans_result"))
        {
            jsonObject = jsonObject.value("trans_result").toObject();
            if(jsonObject.contains("data"))
            {
                QJsonArray array = jsonObject.value("data").toArray();
                foreach(QJsonValue value, array)
                {
                    if(!value.isObject())
                    {
                       continue;
                    }
                    QJsonObject obj = value.toObject();
                    emit downLoadDataChanged(obj.value("dst").toString());
                    break;
                }
            }
Esempio n. 4
0
void CurrencyTicker::netRequestFinished(QNetworkReply* reply)
{
    bool signalUpdates = false;

    if (reply->error() != QNetworkReply::NetworkError::NoError) {

    } else {
        int statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();

        if (statusCode != 200) {

        } else {
            QByteArray jsonReply = reply->readAll();
            QString temp = QString::fromStdString(jsonReply.data());
            QJsonDocument jsonDoc = QJsonDocument::fromJson(jsonReply);
            QJsonArray jsonArray = jsonDoc.object().value("data").toArray();

            for (auto jsonVal : jsonArray) {
                QJsonObject jsonObject = jsonVal.toObject();
                std::string currencyName = jsonObject.value("name").toString().toStdString();
                std::string currencyCode = jsonObject.value("code").toString().toStdString();

                std::string currencyRate;
                std::ostringstream bufstream;
                bufstream << std::fixed << std::setprecision(8) << jsonObject.value("rate").toDouble();
                currencyRate = bufstream.str();

                m_ExchangeRates[currencyCode] = currencyRate;
                signalUpdates = true;
            }
        }
    }

    if (signalUpdates) {
        Q_EMIT exchangeRatesUpdated();
        if (++count % 20 == 0) {
            Q_EMIT exchangeRatesUpdatedLongPoll();
        }
    }

    QTimer::singleShot(10000, this, SLOT(pollTicker()));
}
Esempio n. 5
0
void analyserQ::fillCombobox(HttpRequestWorker* worker){
	qDebug() << "handleResult";
	QString msg;
	if (worker->error_type == QNetworkReply::NoError) {
		// communication was successful
		msg = worker->response;
	}
	else {
		// an error occurred
		msg = "Error: " + worker->error_str;
		QMessageBox::information(this, "", msg);
		//return;
	}

	//QMessageBox::information(this, "", msg);
	qDebug() << msg;
	qDebug() << msg.toUtf8();
	QJsonParseError error;
	QJsonDocument document = QJsonDocument::fromJson(msg.toUtf8(), &error);

	if (!document.isObject()) {
		qDebug() << "Document is not an object"+error.errorString();
	}
	QJsonObject object = document.object();
	QJsonValue jsonValue = object.value("id");
	if (jsonValue.isUndefined()) {
		qDebug() << "Key id does not exist";
	}

	//QJsonObject object = document.object();
	//qDebug() << err->errorString();
	QJsonValue value = object.value("rows");
	qDebug() << "rowval" + value.toString();
	QJsonArray array = value.toArray();

	//array = fileLoad();
	//qDebug() << "file loaded";

	foreach(const QJsonValue & v, array)
	{
		liste->addItem(v.toObject().value("id").toString());
	}
Esempio n. 6
0
void NetworkManager::reloadActiveConnections()
{
    const QJsonDocument doc = QJsonDocument::fromJson(m_networkInter->activeConnections().toUtf8());
    Q_ASSERT(doc.isObject());
    const QJsonObject obj = doc.object();

    NetworkDevice::NetworkTypes states = NetworkDevice::None;
    QSet<QUuid> activeConnList;
    for (auto info(obj.constBegin()); info != obj.constEnd(); ++info)
    {
        Q_ASSERT(info.value().isObject());
        const QJsonObject infoObj = info.value().toObject();

        const QUuid uuid = infoObj.value("Uuid").toString();
        // if uuid not in device list, its a wireless connection
        const bool isWireless = std::find(m_deviceSet.cbegin(), m_deviceSet.cend(), uuid) == m_deviceSet.cend();

        if (isWireless)
            states |= NetworkDevice::Wireless;
        else
            states |= NetworkDevice::Wired;

        activeConnList.insert(uuid);
    }

    const QSet<QUuid> removedConnList = m_activeConnSet - activeConnList;
    m_activeConnSet = std::move(activeConnList);

    for (auto uuid : removedConnList)
        emit activeConnectionChanged(uuid);

    for (auto uuid : m_activeConnSet)
        emit activeConnectionChanged(uuid);

    if (m_states == states)
        return;

    m_states = states;
    emit networkStateChanged(m_states);

//    qDebug() << "network states: " << m_states;
}
Esempio n. 7
0
//TODO: should use qt's json process lib here
int PkgHandle::loadConfig() { // default "" means use default conf inside, initialize all vars remember
    if (_confpath == QString("")) {
		pr_info("config file emtpy, error");
		return -1; //can not find conf file
    }   

    QByteArray val;
    QFile file(_confpath);
    if(file.open(QIODevice::ReadOnly | QIODevice::Text) == false) {
        pr_info("can not open conf file \n");
        return -1;
    }
    val = file.readAll();
    file.close();
    QJsonDocument doc = QJsonDocument::fromJson(val);
    QJsonObject docobj = doc.object();

    for (QJsonObject::iterator it = docobj.begin(); it != docobj.end(); ++it) {
        if (it.key() == "localpkgdir") {
            _localpkgdir = it.value().toString();
        } else if (it.key() == "prefixdir") {
            _prefixdir = it.value().toString();
        } else if (it.key() == "remoteaddr") {
            _remoteaddr = it.value().toString();
        } else if (it.key() == "remoteuser") {
            _remoteuser = it.value().toString();
        } else if (it.key() == "remotepass") {
            _remotepass = it.value().toString();
        } else if (it.key() == "remotepkgdir") {
            _remotepkgdir = it.value().toString();
        } else if (it.key() == "remotemeta") {
            _remotemetafile = it.value().toString();
        } else if (it.key() == "localmeta") {
            _localmetafile = it.value().toString();
        } else {
            pr_info("unknown json object: %s\n", it.key().toStdString().c_str());
   //         return -1;
        }
    }

    return 0;
}
void MainWindow::handleResponse(HttpRequestWorker *worker) {
    if (worker->error_type == QNetworkReply::NoError) {
        // communication was successful
        // we got a JSON response, let's parse it
        QJsonDocument json = QJsonDocument::fromJson(worker->response);
        QJsonObject jobj = json.object();
        QJsonValue value = jobj.value("message");
        if(value.toString() == "success") {
            value = jobj.value("md5");
            ui->lineEdit_2->setText(value.toString().toUpper());
        } else {
            QMessageBox::information(this,"Error", value.toString());
        }
    }
    else {
        // an error occurred
        QString msg = "Error: " + worker->error_str;
        QMessageBox::information(this, "", msg);
    }
}
Esempio n. 9
0
///
/// \brief Widget::loadIcons
/// load all icons from items.json
void Widget::loadIcons() {
    QFile file;
    QString txt;
    file.setFileName(":/resources/items.json");

    file.open(QIODevice::ReadOnly | QIODevice::Text);
    txt = file.readAll();
    file.close();

    // parse JSON
    QJsonDocument doc = QJsonDocument::fromJson(txt.toUtf8());
    QJsonObject obj = doc.object();
    for (auto it = obj.begin(); it != obj.end(); ++it) {
        QCheckBox* check = new QCheckBox();
        check->setText((*it).toObject().value("complete_name").toString());
        check->setIcon(QIcon((*it).toObject().value("icon").toString()));
        check->setIconSize(QSize(50,50));
        ui->gridLayout->addWidget(check);
    }
}
Esempio n. 10
0
void Updater::DoneLatestQuery()
{
    Timer->stop();
    if(Client->WasError())
    {
        Skip();
        return;
    }
    QJsonDocument JsonResponse = QJsonDocument::fromJson(Client->GetPageData());
    QJsonObject JsonObj = JsonResponse.object();
    AppReference = QString("http://bablosoft.com/") + JsonObj["script"].toString();
    RemoteVersion = JsonObj["version"].toString();
    QStringList Changelog;
    if(JsonObj.contains("changelog"))
    {
        QVariantList array = JsonObj["changelog"].toArray().toVariantList();
        foreach(QVariant v,array)
        {
            Changelog.append(v.toString().replace("\n",""));
        }
void CodeClassResultsGridWidget::loadLayout(const QByteArray &data)
{
	QJsonDocument jsd = QJsonDocument::fromJson(data);
	QJsonObject jso = jsd.object();
	int col_cnt = jso.value(PROP_COL_COUNT).toInt();
	for (int i = columnCount(); i < col_cnt; ++i) {
		addColumn();
	}
	int row_cnt = jso.value(PROP_ROW_COUNT).toInt();
	for (int i = rowCount(); i < row_cnt; ++i) {
		addRow();
	}
	QJsonArray cells = jso.value(PROP_CELLS).toArray();
	for (int i = 0; i < cells.count(); ++i) {
		QJsonValue jsv = cells.at(i);
		CodeClassResultsWidget *rw = resultsWidgetAt(i / col_cnt, i % col_cnt);
		QF_ASSERT(rw != nullptr, "Bad result widget index", continue);
		rw->loadSetup(jsv.toObject());
	}
}
Esempio n. 12
0
void GDTalker::parseResponseUserName(const QByteArray& data)
{
    QJsonParseError err;
    QJsonDocument doc = QJsonDocument::fromJson(data, &err);

    if (err.error != QJsonParseError::NoError)
    {
        emit signalBusy(false);
        return;
    }

    QJsonObject jsonObject = doc.object();
    qCDebug(KIPIPLUGINS_LOG)<<"User Name is: " << jsonObject[QString::fromLatin1("name")].toString();
    QString temp           = jsonObject[QString::fromLatin1("name")].toString();

    qCDebug(KIPIPLUGINS_LOG) << "in parseResponseUserName";

    emit signalBusy(false);
    emit signalSetUserName(temp);
}
Esempio n. 13
0
//------------------------------------------------------------------------------
// Name: operator==
//------------------------------------------------------------------------------
bool QJsonDocument::operator==(const QJsonDocument &other) const {

	if(isArray() && other.isArray()) {
		return array() == other.array();
	}

	if(isObject() && other.isObject()) {
		return object() == other.object();
	}

	if(isEmpty() && other.isEmpty()) {
		return true;
	}

	if(isNull() && other.isNull()) {
		return true;
	}

	return false;
}
Esempio n. 14
0
QVariantMap APIHelper::jsonToVariantMap(const QByteArray &json)
{
#ifdef QT_DEBUG
        qDebug() << "Start to parse JSON into QVariantMap.";
#endif
        QString jsonString(json);

#ifdef QT_DEBUG
        qDebug() << json;
#endif
        QJsonParseError err;

        QJsonDocument jsonDoc = QJsonDocument::fromJson(jsonString.toUtf8(), &err);

#ifdef QT_DEBUG
        qDebug() << err.errorString();
#endif

    return jsonDoc.object().toVariantMap();
}
Esempio n. 15
0
bool FileManager::import( QString path, CategoryData* categoryData, ImageData* imageData )
{
    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();

    categoryData->initWithJson( jsonObject );
    categoryData->path = path;

    imageData->initWithJson( jsonObject );

    return true;
}
void MainWindow::on_actionOpen_Preset_triggered()
{
    QFileDialog dialog(this);
    dialog.setViewMode(QFileDialog::Detail);
    dialog.setAcceptMode(QFileDialog::AcceptOpen);
    dialog.setFileMode(QFileDialog::AnyFile);
    QStringList filters;
    filters << NAME_FILTER_PRESET
            << NAME_FILTER_ANY;
    dialog.setNameFilters(filters);
    QString file;
    if (dialog.exec())
    {
        QFile file(dialog.selectedFiles().at(0));
        if (file.exists())
        {
            file.open(QIODevice::ReadOnly | QIODevice::Text);
            QString jsonString = (QString) file.readAll();
            QJsonDocument doc = QJsonDocument::fromJson(jsonString.toUtf8());
            if (doc.isNull())
            {
                QMessageBox box;
                QString boxText;
                boxText.append("It appears that ")
                       .append(QFileInfo(file).fileName())
                       .append("is not a valid preset file");
                box.setText("It appears that file is not a valid preset");
                box.setStandardButtons(QMessageBox::Ok);
                box.exec();
            }
            else
            {
                QJsonObject json = doc.object();
                taskTab->setValuesFromJson(json);
                audioTab->setValuesFromJson(json);
                visualTab->setValuesFromJson(json);
            }
        }

    }
}
Esempio n. 17
0
void Style::loadStyleInfo(const QString &name, const QString &path)
{
    QString filePath(path + "/style");
    QFile file(filePath);
    if (!file.open(QIODevice::ReadOnly)) {
        qWarning() << QString("Failed to load the style '%1'. Could not open %1 for reading.").arg(filePath);
        return;
    }

    StyleInfo *info = new StyleInfo;
    info->m_name = name;
    info->m_path = path;
    info->m_prettyName = name;

    QByteArray data = file.readAll();
    file.close();

    QJsonParseError error;
    QJsonDocument doc = QJsonDocument::fromJson(data, &error);
    if (error.error != QJsonParseError::NoError) {
        qWarning("Error parsing %s at offset %d: %s", qPrintable(filePath), error.offset, qPrintable(error.errorString()));
        delete info;
        return;
    }
    QJsonObject json = doc.object();

    if (json.contains("prettyName")) {
        info->m_prettyName = json.value("prettyName").toString();
    }
    if (json.contains("qmlFile")) {
        info->m_qml = path + "/" + json.value("qmlFile").toString();
    }

    if (info->m_qml.isEmpty()) {
        qWarning() << QString("Failed to load the style '%1'. Missing 'qmlFile' field.").arg(path);
        delete info;
        return;
    }

    s_styles.insert(name, info);
}
Esempio n. 18
0
void EarthquakeModel::parseFile( const QByteArray& file )
{
    QJsonDocument jsonDoc = QJsonDocument::fromJson(file);
    QJsonValue earthquakesValue = jsonDoc.object().value(QStringLiteral("earthquakes"));

    // Parse if any result exists
    if (earthquakesValue.isArray()) {
        // Add items to the list
        QList<AbstractDataPluginItem*> items;

        QJsonArray earthquakeArray = earthquakesValue.toArray();
        for (int earthquakeIndex = 0; earthquakeIndex < earthquakeArray.size(); ++earthquakeIndex) {
            QJsonObject levelObject = earthquakeArray[earthquakeIndex].toObject();

            // Converting earthquake's properties from JSON to appropriate types
            const QString eqid = levelObject.value(QStringLiteral("eqid")).toString(); // Earthquake's ID
            const double longitude = levelObject.value(QStringLiteral("lng")).toDouble();
            const double latitude = levelObject.value(QStringLiteral("lat")).toDouble();
            const double magnitude = levelObject.value(QStringLiteral("magnitude")).toDouble();
            const QString dateString = levelObject.value(QStringLiteral("datetime")).toString();
            const QDateTime date = QDateTime::fromString(dateString, QStringLiteral("yyyy-MM-dd hh:mm:ss"));
            const double depth = levelObject.value(QStringLiteral("depth")).toDouble();

            if( date <= m_endDate && date >= m_startDate && magnitude >= m_minMagnitude ) {
                if( !itemExists( eqid ) ) {
                    // If it does not exists, create it
                    GeoDataCoordinates coordinates( longitude, latitude, 0.0, GeoDataCoordinates::Degree );
                    EarthquakeItem *item = new EarthquakeItem( this );
                    item->setId( eqid );
                    item->setCoordinate( coordinates );
                    item->setMagnitude( magnitude );
                    item->setDateTime( date );
                    item->setDepth( depth );
                    items << item;
                }
            }
        }

        addItemsToList( items );
    }
}
Esempio n. 19
0
void OS2LPlugin::slotProcessTCPPackets()
{
    QTcpSocket *socket = (QTcpSocket *)sender();
    if (socket == NULL)
        return;

    QHostAddress senderAddress = socket->peerAddress();
    QByteArray message = socket->readAll();
    QJsonDocument json = QJsonDocument::fromJson(message);

    qDebug() << "[TCP] Received" << message.length() << "bytes from" << senderAddress.toString();
    QJsonObject jsonObj = json.object();
    QJsonValue jEvent = jsonObj.value("evt");
    if (jEvent.isUndefined())
        return;

    QString event = jEvent.toString();

    if (event == "btn")
    {
        QJsonValue jName = jsonObj.value("name");
        QJsonValue jState = jsonObj.value("state");
        qDebug() << "Got button event with name" << jName.toString() << "and state" << jState.toString();
        uchar value = jState.toString() == "off" ? 0 : 255;
        emit valueChanged(m_inputUniverse, 0, getHash(jName.toString()), value, jName.toString());
    }
    else if (event == "cmd")
    {
        QJsonValue jId = jsonObj.value("id");
        QJsonValue jParam = jsonObj.value("param");
        qDebug() << "Got CMD message" << jId.toInt() << "with param" << jParam.toDouble();
        quint32 channel = quint32(jId.toInt());
        QString cmd = QString("cmd%1").arg(channel);
        emit valueChanged(m_inputUniverse, 0, quint32(jId.toInt()), uchar(jParam.toDouble()), cmd);
    }
    else if (event == "beat")
    {
       qDebug() << "Got beat message" << message;
       emit valueChanged(m_inputUniverse, 0, 8341, 255, "beat");
    }
}
void HwaHomePage::onAction(const QString& action, const QVariant& param)
{
	qDebug("HwaHomePage::onAction");
	QJsonParseError error;
	QJsonDocument json = QJsonDocument::fromJson(action.toLatin1(), &error);
	if (error.error == QJsonParseError::NoError)
	{
		QJsonObject jObj = json.object();
		if (jObj.contains("action"))
		{
			int action = jObj.value("action").toInt();
			HwaPlatformConfigManager& mgr = HwaPlatformConfigManager::getManager();
			switch (action)
			{
			case NEW_PROJECT:
				{
					this->closeProject(_project);

					QString projectName = jObj.value("projectName").toString();
					_project = this->createProject(projectName);

					if (_project && _homeRoot)
					{
						//大小为2不正常
						qDebug() << "-->size=" << _homeRoot->findChildren<QObject*>(projectName).size();
						QObject* qmlProject = _homeRoot->findChild<QObject*>(projectName);
						_project->setRoot(qmlProject);
						_project->newProject();
					}
				}
				break;
			case CLICK_NEW_PROJECT:
				std::vector<ProjectInfor> projIfnors = mgr.getProjectsInfor();
				foreach (const ProjectInfor& infor, projIfnors)
				{
					//action New clicked
					emit command(QString("{\"projectName\":\"%1\",\"objectName\":\"%2\",\"picture\":\"%3\",\"text\":\"%4\",\"action\":\"%5\"}")
						.arg(infor.className.c_str(), jObj.value("objectName").toString()
						, infor.icon.c_str(), infor.description.c_str(), QString::number(CLICK_NEW_PROJECT)), "");
				}
			}
Esempio n. 21
0
void Shadow::stupConf(){
    QFile file(CONF);
    if(!file.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        QMessageBox::warning(this,"IO error!","Can not read config file");
    }
    QJsonParseError json_error;
    QByteArray jsonByteArray = file.readAll();
    file.close();
    QJsonDocument jsonDoc = QJsonDocument::fromJson(jsonByteArray,&json_error);
    QJsonObject jsonObj;
    if(json_error.error == QJsonParseError::NoError){
        if(jsonDoc.isObject()){
            jsonObj = jsonDoc.object();
        }
    }
    QString val;
    val = GetJsonVal("scrollwidth",jsonObj);
    if (val != ""){
        ui->scrollWidth->setText(val);
    }

    val = GetJsonVal("root",jsonObj);
    if(val!="")
    {
        ui->outputDir->setText(val);
    }

    val = GetJsonVal("scale",jsonObj);
    if(val!="")
    {
        ui->scale->setValue(val.toInt());
        //ui->scale->setText(val);
    }

    val = GetJsonVal("atten",jsonObj);
    if(val!="")
    {
        ui->attenuator->setText(val);
    }
}
void PAAlternativeLauncher::authenticateFinished()
{
	QNetworkReply *reply = dynamic_cast<QNetworkReply *>(sender());
	if(reply)
	{
		if(reply->error() == QNetworkReply::NoError)
		{
			info.log("Login", "Authentication information received.", true);
			QJsonDocument authjson = QJsonDocument::fromJson(reply->readAll());
			info.log("Login", "Authentication information decoded.", true);
			mSessionTicket = authjson.object()["SessionTicket"].toString();
			info.log("Login", QString("Session ticket is %1.").arg(mSessionTicket), true);
			if(!mSessionTicket.isEmpty())
			{
				QSettings settings;
				settings.setValue("login/sessionticket", mSessionTicket);
				settings.setValue("login/username", mUserNameLineEdit->text());

				QNetworkRequest request(QUrl("https://uberent.com/Launcher/ListStreams?Platform=" + mPlatform));
				request.setRawHeader("X-Authorization", mSessionTicket.toUtf8());
				request.setRawHeader("X-Clacks-Overhead", "GNU Terry Pratchett");
				request.setRawHeader("User-Agent", QString("PAAlternativeLauncher/%1").arg(VERSION).toUtf8());
				info.log("Login", "Retrieving available streams.", true);
				QNetworkReply *reply = mNetworkAccessManager->get(request);
				connect(reply, SIGNAL(finished()), SLOT(streamsFinished()));
			}
			else
			{
				info.critical(tr("Authenticate"), tr("Empty session ticket"));
				setState(login_state);
			}
		}
		else
		{
			info.critical(tr("Authenticate"), tr("Error while authenticating.\n%1").arg(reply->errorString()));
			setState(login_state);
		}

		reply->deleteLater();
	}
}
Esempio n. 23
0
void ChatServer::receiveData() {
    QTcpSocket * socket = qobject_cast<QTcpSocket*>(sender());
    QByteArray received = socket->readAll();

    // в received может содержаться несколько сообщений
    // их надо разбить:
    while (received.length()) {
        // сообщение возьмет себе столько, сколько нужно
        QJsonDocument doc = QJsonDocument::fromBinaryData(received);
        if (doc.isNull()) {
            // плохие данные
            emit alert("Unknown message format");
            return;
        }

        QVariantMap data = doc.object().toVariantMap();
        if (!data.contains("type")) {
            emit alert("Message should have 'type' key");
            return;
        }

        // конвертация типа в const char* для рассчета CRC
        auto typeString = data["type"].toString();
        auto typeBuffer = typeString.toUtf8();
        auto typeChars = typeBuffer.constData();

        qWarning() << "get message:" << doc;

        switch (mt(typeChars)) {
            case mt("login"): processLoggingInData(socket, data); break;
            case mt("signin"): processSigningInData(socket, data); break;
            case mt("logout"): processLoggingOutData(socket, data); break;
            case mt("changestatus"): processChangingStatusData(socket, data); break;
            case mt("sendmessage"): processSendingData(socket, data); break;
            case mt("messagereceived"): processMessageReceivedData(socket, data); break;
            default: alert("Unknown message type"); break;
        }
        // сдвиг полученного массива на кол-во считанных данных
        received = received.right(received.length() - doc.toBinaryData().length());
    }
}
QPointer<TrainTimetable> PlkApiResponseParser::parseResponse(QByteArray response){


    QPointer<TrainTimetable> timetable = new TrainTimetable();

    QJsonParseError err;
    QJsonDocument doc = QJsonDocument::fromJson(response, &err);
    QJsonObject json_root = doc.object();
    QJsonArray json_connections = json_root["P"].toArray();
    QString json_travel_source =  json_root["S"].toString();
    QString json_travel_destination =  json_root["T"].toString();

    if(err.error != QJsonParseError::NoError){
        throw new NotJsonResponseException("The response drom the server did not contain valid JSON. " + err.errorString());
    }

    for(int i=0; i< json_connections.size(); i++){

        QJsonObject single_result = json_connections[i].toObject();

        QPointer<TrainConnection> connection = new TrainConnection();
        connection->setSource(json_travel_source);
        connection->setDestination(json_travel_destination);
        connection->setJourneyStartDate(QDateTime::fromString(single_result["O"].toString(), "dd.MM.yyyy HH:mm"));
        connection->setJourneyEndDate(QDateTime::fromString(single_result["P"].toString(), "dd.MM.yyyy HH:mm"));



        QStringList train_types;
        QJsonArray trains = single_result["N"].toArray();
        for(int j=0;j<trains.size();j++){
            QJsonObject curr_train = trains[j].toObject();
            train_types.append(curr_train["P"].toString());
        }
        connection->setCarrierName(train_types.join(","));
        timetable->addConnection(connection);
    }


    return timetable;
}
Esempio n. 25
0
void renderPDF417(QPainter *painter, int /*dpi*/, const QRectF &r, const QString &_str, OROBarcode *bc)
{
  #if QT_VERSION >= 0x050000
  QByteArray ba = QByteArray(bc->format().toStdString().c_str(), bc->format().toStdString().length());
  QJsonDocument doc = QJsonDocument::fromJson(ba);
  QJsonObject obj = doc.object();
  QJsonValue codewords = obj.value("codewords");
  QJsonValue columns = obj.value("columns");
  QJsonValue errorCorrection = obj.value("errorCorrection");
  QJsonValue type = obj.value("type");

  QPen pen(Qt::NoPen);
  QBrush brush(QColor("black"));
  painter->save();
  painter->setPen(pen);
  painter->setBrush(brush);

  QString str = _str;
  BarcodeItem bci;
  bci.ar=(Zint::QZint::AspectRatioMode)0;
  bci.bc.setText(str);
  bci.bc.setSecurityLevel(errorCorrection.toInt());
  bci.bc.setWidth(columns.toInt());
  bci.bc.setInputMode(UNICODE_MODE);
  if (type.toString() == "truncated")
      bci.bc.setSymbol(BARCODE_PDF417TRUNC);
  else
      bci.bc.setSymbol(BARCODE_PDF417);
  bci.bc.setPdf417CodeWords(codewords.toInt());
  bci.bc.setWhitespace(0);
  bci.bc.setFgColor(QColor("black"));
  bci.bc.setBgColor(QColor("white"));
  bci.update();

  bci.paint(painter, r);
  bci.update();

  painter->restore();
  #endif
  return;
}
//! ----  slot_parse_fanart_info ------------------------------------------------
void CPlexusArtist::parseInfo(QByteArray bytes)
{
  CLog::log(LOG_INFO, "PROVIDER", "Parsing info", "PlexusArtist");

  /*-------------------------------------------------*/
  /* Get id from sender reply                        */
  /* ------------------------------------------------*/
  QObject* reply = qobject_cast<QObject*>(sender());

  if (!reply || !_listRequests.contains(reply))   return;
  const int id = _listRequests.take(reply);

  /*-------------------------------------------------*/
  /* Parse info                                      */
  /* ------------------------------------------------*/
  bool imageFound = false;

  QJsonDocument jsonResponse = QJsonDocument::fromJson(bytes);
  QJsonObject jsonObject = jsonResponse.object();
  QJsonArray fanarts = jsonObject["media"].toArray();

  for (int c = 0; c < fanarts.size(); c++) {
    QJsonObject fanart = fanarts[c].toObject();
    bool imageAlreadyPresent = false;

    // image has to be stored
    if (!fanart["url"].toString().isEmpty())
    {
      //Paulo Pina: Need to implement image existance and status check by new field idProvider.
      if (!imageAlreadyPresent) {
        QUrl url = fanart["url"].toString();
        QObject *reply = CNetworkAccess::instance()->get(url);
        _listRequests[reply] = id;

        connect(reply, SIGNAL(data(QByteArray)), this, SLOT(receivedInfo(QByteArray)));
        connect(reply, SIGNAL(error(QNetworkReply*)), this, SLOT(stopSearch()));
        imageFound = true;
        break;//For now, just get first fanart
      }
    }
  }
Esempio n. 27
0
/*!
 * \brief JsonParser::readJson
 * Analizuje plik ze scenariuszem w formacie json, dodaje obiekty do
 * symulacji i tworzy ścieżki po których obiekty będą się poruszały
 * \param fileName ścieżka do pliku ze scenariuszem
 */
void JsonParser::readJson(QString fileName)
{
   QString val;
   QFile file;
   file.setFileName(fileName);
   file.open(QIODevice::ReadOnly | QIODevice::Text);
   val = file.readAll();
   file.close();

   QJsonDocument d = QJsonDocument::fromJson(val.toUtf8());
   QJsonObject sett2 = d.object();

   QJsonArray objects = sett2.value(QString("Objects")).toArray();

   for (int i = 0; i < objects.size(); i++) {
      QJsonObject obj = objects[i].toObject();
      QString type = obj.value("TypeObject").toString();
      double speed = obj.value("Speed").toDouble();

      QJsonArray points = obj.value(QString("Points")).toArray();

      QJsonObject point = points[0].toObject();
      double CoX = point.value(QString("CoordX")).toDouble();
      double CoY = point.value(QString("CoordY")).toDouble();

      Simulation::getInstance()->addObject(type, speed, CoX, CoY);

      double CoXOld = CoX;
      double CoYOld = CoY;

      for (int j = 1; j < points.size(); j++) {
          point = points[j].toObject();
          CoX = point.value(QString("CoordX")).toDouble();
          CoY = point.value(QString("CoordY")).toDouble();
          Simulation::getInstance()->addPath(i, CoX - CoXOld, CoY - CoYOld);
          //obj_[i].get()->addPathIt(CoX - CoXOld, CoY - CoYOld);
          CoXOld = CoX;
          CoYOld = CoY;
      }
   }
}
void MainWindow::on_otherButton_clicked()
{

    QEventLoop eventLoop;
    // "quit()" the event-loop, when the network request "finished()"
    QNetworkAccessManager mgr;
    QObject::connect(&mgr, SIGNAL(finished(QNetworkReply*)), &eventLoop, SLOT(quit()));
    QUrl url("https://api.spark.io/v1/devices/53ff70066667574852212067/reading?access_token=94f1858893b749831ee5704732a1814beea6b678");
    QNetworkRequest req(url);
    QNetworkReply *reply = mgr.get(req);
    eventLoop.exec(); // blocks stack until "finished()" has been called

    if (reply->error() == QNetworkReply::NoError) {

        QString strReply = (QString)reply->readAll();
        qDebug() << "Response:" << strReply;
        QJsonDocument jsonResponse = QJsonDocument::fromJson(strReply.toUtf8());
        QJsonObject jsonObj = jsonResponse.object();
        qDebug() << "result:" << jsonObj["result"].toInt();
        delete reply;
    }
    else {
        //failure
        qDebug() << "Failure" <<reply->errorString();
        delete reply;
    }


/*
    QNetworkAccessManager *networkManager = new QNetworkAccessManager(this);
    QUrlQuery postData;
    postData.addQueryItem("access_token","94f1858893b749831ee5704732a1814beea6b678");
    postData.addQueryItem("params","l2,HIGH");
    QUrl url("https://api.spark.io/v1/devices/53ff70066667574852212067/led");
    QNetworkRequest request(url);
    request.setHeader(QNetworkRequest::ContentTypeHeader,
                      "application/x-www-form-urlencoded");
    networkManager->post(request,postData.toString(QUrl::FullyEncoded).toUtf8());
*/

}
bool SceneDeserializer::load(std::shared_ptr<BaseScene> scene)
{
    bool hasErrors = false;
    if (FILE *file = std::fopen(m_filepath.toLocal8Bit(), "r"))
    {
        try
        {
            QByteArray bytes;
            const size_t BUFFER_SIZE = 64 * 1024;
            char buffer[BUFFER_SIZE];
            while (size_t readCount = std::fread(buffer, sizeof(char), BUFFER_SIZE, file))
            {
                bytes.append(buffer, readCount);
            }

            QJsonParseError parseError;
            QJsonDocument document = QJsonDocument::fromJson(bytes, &parseError);
            if (parseError.error == QJsonParseError::NoError)
            {
                deserialize(document.object(), scene);
            }
            else
            {
                assert(!"load() failed: cannot parse JSON.");
                hasErrors = true;
            }
        }
        catch (...)
        {
            std::fclose(file);
            throw;
        }
        std::fclose(file);
    }
    else
    {
        assert(!"load() failed: cannot open file.");
        hasErrors = true;
    }
    return !hasErrors;
}
Esempio n. 30
0
//---------------------------------------------------------
//   onGetMediaUrlReply
//---------------------------------------------------------
void LoginManager::onGetMediaUrlReply(QNetworkReply* reply, int code, const QJsonObject& response)
      {
      if (code == HTTP_OK) {
            QJsonValue urlValue = response.value("url");
            if (urlValue.isString()) {
                  _mediaUrl = urlValue.toString();
                  QString mp3Path = QDir::tempPath() + QString("/temp_%1.mp3").arg(qrand() % 100000);
                  _mp3File = new QFile(mp3Path);
                  Score* score = mscore->currentScore()->masterScore();
                  int br = preferences.getInt(PREF_EXPORT_MP3_BITRATE);
                  preferences.setPreference(PREF_EXPORT_MP3_BITRATE, 128);
                  if (mscore->saveMp3(score, mp3Path)) { // no else, error handling is done in saveMp3
                        _uploadTryCount = 0;
                        uploadMedia();
                        }
                  preferences.setPreference(PREF_EXPORT_MP3_BITRATE, br);
                  }
            }
      else // TODO: handle request error properly
            qWarning("%s", getErrorString(reply, response).toUtf8().constData());
#if 0
      disconnect(_oauthManager, SIGNAL(requestReady(QByteArray)),
            this, SLOT(onGetMediaUrlRequestReady(QByteArray)));
      QJsonDocument jsonResponse = QJsonDocument::fromJson(ba);
      QJsonObject response = jsonResponse.object();
      QJsonValue urlValue = response.value("url");
      if (urlValue.isString()) {
            _mediaUrl = response.value("url").toString();
            QString mp3Path = QDir::tempPath() + QString("/temp_%1.mp3").arg(qrand() % 100000);
            _mp3File = new QFile(mp3Path);
            Score* score = mscore->currentScore()->masterScore();
            int br = preferences.getInt(PREF_EXPORT_MP3_BITRATE);
            preferences.setPreference(PREF_EXPORT_MP3_BITRATE, 128);
            if (mscore->saveMp3(score, mp3Path)) { // no else, error handling is done in saveMp3
                  _uploadTryCount = 0;
                  uploadMedia();
                  }
            preferences.setPreference(PREF_EXPORT_MP3_BITRATE, br);
            }
#endif
      }