示例#1
0
bool LoginReply::parse(const QByteArray& data)
{
	JsonDataAccess jsonObject;
	QVariant node = jsonObject.loadFromBuffer(data);
	if (jsonObject.hasError()) {
		qWarning() << "error converting JSON data: " << jsonObject.error().errorMessage();
	} else {
		qDebug() << "before parse: " << QString(data);
		QVariantMap map = node.value<QVariantMap>();
		if (map["status"].toString() == "OK") {
			m_status = true;
			m_sessionKey = map["sessionKey"].toString();
			QVariantList friendList = map["friends"].value<QVariantList>();
			for (int i = 0; i < friendList.size(); i++) {
				m_ppIds.append(friendList[i].toString());
			}
			QVariantList pinList = map["pins"].value<QVariantList>();
			for (int i = 0; i < pinList.size(); i++) {
				m_pins.append(pinList[i].toString());
			}

			return true;
		}
	}

	return false;
}
示例#2
0
void NetworkBus::onLineIsOpenFinished(QNetworkReply* reply){
	if(reply->error() != QNetworkReply::NoError){
		m_error = QString::fromUtf8("线路开通数据请求错误,请检查网络后重试!");
		onError();
		reply->deleteLater();
		return;
	}else{
		JsonDataAccess jda; // at are you
		const QVariant qtData = jda.loadFromBuffer(reply->readAll());
		// TODO if qtData has some error

		const QVariantMap map = qtData.toMap();
		const QString msg = map.values("msg").value(0).toString();
		const QString success = map.values("success").value(0).toString();
		if(success != "true" || msg != "ok"){
			m_error = QString::fromUtf8("线路开通返回失败,请检查网络后重试!");
			onError();
			return;
		}
		const QVariantList data = map["data"].toList();
		m_eid = data.at(0).toMap().value("eid").toString();
		m_isopen = data.at(0).toMap().value("isopen").toInt();
		qDebug() << "isOpen:" << m_isopen << "  eid:" << m_eid << "\n";
		reply->deleteLater();
		this->get_online_gps();
	}
}
void QBNetwork::onRequestUsers() {
	QNetworkReply* reply = qobject_cast<QNetworkReply*>(sender());
	if (reply) {
		const int available = reply->bytesAvailable();
		if (available > 0) {
			const QByteArray buffer(reply->readAll());
			QString response = QString::fromUtf8(buffer);

			JsonDataAccess jda;
			QVariant qtData = jda.loadFromBuffer(response);
			if (jda.hasError()) {
				const DataAccessError err = jda.error();
				emit error(
						tr("Error converting JSON data: %1").arg(
								err.errorMessage()));
			} else {
				emit usersReceived(response);
			}
		} else {
			emit error("Wrong reply for request users request");
		}
		reply->deleteLater();
	} else {
		emit error("Wrong reply for request users request");
	}

	disconnectFromAll();
}
示例#4
0
bool GetLocationsReply::parse(const QByteArray& data)
{
    JsonDataAccess jsonObject;
    QVariant node = jsonObject.loadFromBuffer(data);
    if (jsonObject.hasError()) {
        qWarning() << "error converting JSON data: " << jsonObject.error().errorMessage();
    } else {
        qDebug() << "before parse: " << QString(data);
        QVariantMap map = node.value<QVariantMap>();
        if (map["status"].toString() == "OK") {
            m_status = true;
            QVariantList friendList = map["friends"].value<QVariantList>();
            for (int i = 0; i < friendList.size(); i++) {
                QString friendStr = friendList[i].toString();
                QStringList fields = friendStr.split(",");
                // if incorrect number of fields, stop parsing
                if (fields.size() != 4) return false;
                QString ppId = fields.at(0);
                double x = fields.at(1).toDouble();
                double y = fields.at(2).toDouble();
                int visibility = fields.at(3).toInt();
                m_friends.append(User(ppId, x, y, visibility));
            }

            return true;
        }
    }

    return false;
}
示例#5
0
void NetworkBus::onAlllineDataModelFinished(QNetworkReply* reply){
	if(reply->error() != QNetworkReply::NoError){
		m_error = QString::fromUtf8("所有线路数据请求错误,请检查网络后重试!");
		onError();
		reply->deleteLater();
		return;
	}else{
		JsonDataAccess jda; // at are you
		const QVariant qtData = jda.loadFromBuffer(reply->readAll());
		// TODO if qtData has some error

		const QVariantMap map = qtData.toMap();
		const QString msg = map.values("msg").value(0).toString();
		const QString success = map.values("success").value(0).toString();
		if(success != "true" || msg != "ok"){
			m_error = QString::fromUtf8("所有线路数据返回不成功,请检查网络后重试!");
			onError();
			reply->deleteLater();
			return;
		}
		//

		const QVariantList data = map["data"].toList();
		if(data.isEmpty() || data.length() == 0){
			m_error = QString::fromUtf8("未查询到所有公交车线路数据!");
			onError();
			reply->deleteLater();
			return ;
		}
		QString result = "";
		m_alllineDataModel->clear();
		for(int i=0;i<data.length();i++){
			const QVariantMap iMap = data.at(i).toMap();
			busline *bus = new busline;
			bus->setBeginTime(iMap.value("begin_time").toString());
			bus->setEndTime(iMap.value("end_time").toString());
			bus->setId(iMap.value("id").toString());
			bus->setStartStation(iMap.value("start_station").toString());
			bus->setEndStation(iMap.value("end_station").toString());
			bus->setPrice(iMap.value("price").toString());
			bus->setLineName(iMap.value("line_name").toString());
			bus->setIsOpen(iMap.value("isopen").toInt());//1
			bus->setDir(iMap.value("dir").toInt());//0/1
			bus->setCityId(m_city_id);
			if(bus->getIsOpen() == 1)
			m_alllineDataModel->append(bus);
		}
		reply->deleteLater();
	}
	qDebug()<< "m_allline datamodel size:" << m_alllineDataModel->size();
	m_error = QString::fromUtf8("查询到所有公交车线路数据!");
	this->setProcess(false);
	emit processChanged();

	emit alllineDataModelChanged();
}
void QBNetwork::onRequestSessionRegister() {
	QNetworkReply* reply = qobject_cast<QNetworkReply*>(sender());

	QString response;
	if (reply) {
		const int available = reply->bytesAvailable();
		if (available > 0) {
			const QByteArray buffer(reply->readAll());
			response = QString::fromUtf8(buffer);

			JsonDataAccess jda;
			QVariant qtData = jda.loadFromBuffer(response);
			if (jda.hasError()) {
				const DataAccessError err = jda.error();
				emit error(
						tr("Error converting JSON data: %1").arg(
								err.errorMessage()));
			} else {
				const QVariantMap object = qtData.value<QVariantMap>();
				QMapIterator<QString, QVariant> it(object);
				while (it.hasNext()) {
					it.next();
					if (it.key() == "session") {
						QVariantMap sessObject = it.value().toMap();
						QMapIterator<QString, QVariant> sit(sessObject);
						while (sit.hasNext()) {
							sit.next();
							if (sit.key() == "user_id") {
								m_userId = sit.value().toString();
							}
							if (sit.key() == "token") {
								m_token = sit.value().toString();
							}
						}
					}
				}

				if (m_token != NULL) {
					//register after we have session
					emit sessionEstablished();
					registerNewUser();
				} else {
					emit error("Wrong reply for register session request");
				}
			}
		} else {
			emit error("Wrong reply for register session request");
		}
		reply->deleteLater();
	} else {
		emit error("Wrong reply for register session request");
	}

	disconnectFromAll();
}
void VolumeRequest::requestResponse(QByteArray& result) {
	qDebug() << " DataRequest::requestResponse QString result=" << QString(result);
	
	JsonDataAccess jda;
	QVariant jsonVariant = jda.loadFromBuffer( QString(result));
	
	QVariantMap map = jsonVariant.toMap();
	QVariantList records = map.value("records").toList();
	
	emit success(mutateRecords(records));
}
示例#8
0
//! [1]
void NetworkBus::onSublineInfFinished(QNetworkReply* reply){
	if(reply->error() != QNetworkReply::NoError){
		m_error = QString::fromUtf8("站点信息请求失败,请检查网络后重试!");
		onError();
		reply->deleteLater();
		return ;
	}else{
		JsonDataAccess jda; // at are you
		const QVariant qtData = jda.loadFromBuffer(reply->readAll());
		// TODO if qtData has some error

		const QVariantMap map = qtData.toMap();
		const QString msg = map.values("msg").value(0).toString();
		const QString success = map.values("success").value(0).toString();
		if(success != "true" || msg != "ok"){
			m_error = QString::fromUtf8("站点信息返回不成功,请稍后重试!");
			onError();
			reply->deleteLater();
			return;
		}
		const QVariantMap data = map["data"].toMap();
		const QVariantList stations = data["stations"].toList();
		if(stations.isEmpty() || stations.length() == 0){
			m_error = QString::fromUtf8("未查询到站点数据!");
			onError();
			reply->deleteLater();
			return ;
		}
		m_dataModel->clear();
		for(int i=0;i<stations.length();i++){
			const QVariantMap var = stations.at(i).toMap();
			station *sta = new station();
			sta->setCode(var["code"].toString());
			sta->setId(var["id"].toString());
			sta->setLat(var["lat"].toString());
			sta->setLng(var["lng"].toString());
		//	QString name = QString::number(i+1) ;
		//	name.append(var["name"].toString());
			sta->setIndex(QString::number(i+1));
		//	qDebug() << "name string : " << name ;
			sta->setName(var["name"].toString());
			if(m_dir == 0)
				startStation->append(sta);
			else endStation->append(sta);
		}
		m_dataModel->append(m_dir == 0 ? *startStation : *endStation);
	}
	qDebug() << "\nm_dataModel size :"<<m_dataModel->size() << "\n";
	emit dataModelChanged();
	emit buslineChanged();
	reply->deleteLater();
	this->get_lineisopen();
}
示例#9
0
//! [1]
void NetworkBus::get_online_gps_finished(QNetworkReply* reply){
	if(reply->error() != QNetworkReply::NoError){
		m_error = QString::fromUtf8("GPS定位数据请求失败,请稍后重试!");
		onError();
		reply->deleteLater();
		return ;
	}else{
		JsonDataAccess jda; // at are you
		const QVariant qtData = jda.loadFromBuffer(reply->readAll());
		const QVariantMap map = qtData.toMap();

		const QVariantList records = map["records"].toList();
	//	const QVariantList stations = data["stations"].toList();
		if(records.isEmpty()){
			m_error = QString::fromUtf8("不在服务时间!");
			onError();
			reply->deleteLater();
			return ;
		}
		for(int i=0;i<m_dataModel->size()-1;i++){
			station* sta = m_dataModel->value(i);
			sta->setBusState(NULL);
		//	m_dataModel->value(i)->setBusState("");
			for(int j = 0 ; j < records.length();j++){
				const QStringList var = records.at(j).toStringList();
				const QString cur_station_state = var[19];
				const QString next_station = var[17];
				const QString cur_station = var[18];
				const QString subline_ids = var[20];
				if(subline_id() != subline_ids) continue;
			//	float leftPadding = 0;
				if(cur_station == m_dataModel->value(i)->name() && next_station == m_dataModel->value(i+1)->name()){
					if(cur_station_state != "2"){//显示在站点
					//	m_dataModel->value(i)->setBusState("cur_station");
						sta->setBusState("cur_station");
					}
					else{//显示正中间
					//	m_dataModel->value(i)->setBusState("middle");
						sta->setBusState("middle");
					}
				}
			}
			m_dataModel->replace(i,sta);
		}
	}
	setProcess(false);
	emit processChanged();
	emit busstateChanged();
	reply->deleteLater();
}
void NetworkManager::onFinished(QNetworkReply* reply) {
    using namespace bb::data;
    bool disconnected = disconnect(&m_netManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(onFinished(QNetworkReply*)));
    Q_ASSERT(disconnected);
    if (reply->error() == QNetworkReply::NoError) {
        JsonDataAccess json;
        QString contentString = reply->readAll();
        QVariantMap content = json.loadFromBuffer(contentString).toMap();
        bool ok;
        int replyCode = content["id"].toInt(&ok);
        if (!ok) replyCode = -1;
        emit confirmationCode(replyCode);
    }
    reply->deleteLater();
}
void QBNetwork::onRequestLogin() {
	QNetworkReply* reply = qobject_cast<QNetworkReply*>(sender());
	QString response;
	if (reply) {
		if (reply->error() == QNetworkReply::NoError) {
			const int available = reply->bytesAvailable();
			if (available > 0) {
				const QByteArray buffer(reply->readAll());
				response = QString::fromUtf8(buffer);
				JsonDataAccess jda;
				QVariant qtData = jda.loadFromBuffer(response);
				if (jda.hasError()) {
					const DataAccessError err = jda.error();
					showError(
							tr("Error converting JSON data: %1").arg(
									err.errorMessage()));
				} else {
					const QVariantMap object = qtData.value<QVariantMap>();
					QMapIterator<QString, QVariant> it(object);
					while (it.hasNext()) {
						it.next();
						if (it.key() == "user") {
							QVariantMap sessObject = it.value().toMap();
							QMapIterator<QString, QVariant> sit(sessObject);
							while (sit.hasNext()) {
								sit.next();
								if (sit.key() == "id") {
									break;
								}
							}
						}
					}
				}
			}
		} else {
			if (reply->error() < 100) {
				showError("Please check your internet connection");
				return;
			}
			response =
					tr("Error: %1 status: %2").arg(reply->errorString(),
							reply->attribute(
									QNetworkRequest::HttpStatusCodeAttribute).toString());
		}
		reply->deleteLater();
	}
	requestUsers();
}
示例#12
0
void RocknRoll::onArtistReply(QNetworkReply* reply)
{
	QString response;
	bool success = false;
	if(reply)
	{
		if(reply->error() == QNetworkReply::NoError)
		{
			int available = reply->bytesAvailable();
			QString jString = reply->readAll();
			qDebug() << "jString ================= " << jString;
			JsonDataAccess jda;
			//QVariantList list = jda.loadFromBuffer(jString)->toValue<QVariantList>();
			QVariantList list = jda.loadFromBuffer(jString).value<QVariantList>();
			qDebug() <<"lisssssssssssssssssssssssssssssssst " << list;
//			if (available > 0)
//			{
//				int bufSize = sizeof(char) * available + sizeof(char);
//				QByteArray buffer(bufSize, 0);
//				int read = reply->read(buffer.data(), available);
//				response = QString(buffer);
//				QJsonDocument jdoc = response.toJson();
//				qDebug() << "****** " << response << " ******" << endl;
//				JsonDataAccess jda;
//				QVariant list = jda.load("/bb10_client/dummy.json");
//				QVariant jdoc = jda.loadFromBuffer(response);
//				QList<QVariant> list = jdoc.toList();
//				qDebug() << "null jdoc: " << jdoc.isNull() << endl;
//				qDebug() << "empty jdoc: " << jdoc.isEmpty() << endl;
//				success = true;
//			}
		}
		else
		{
			response = QString("Error: ") + reply->errorString() + QString(" status: ") + reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toString();
			qDebug() << response;
		}
		reply->deleteLater();
	}
	if (response.trimmed().isEmpty())
	{
		response = QString("Request failed. Check connection");
		qDebug() << response;
	}
	emit complete(response, success);

}
void SocialInvocation::childCardDone(const bb::system::CardDoneMessage &doneMessage)
{
	SystemToast* toast = new SystemToast(this);
	if (doneMessage.dataType().compare("application/json") == 0)
	{
		// The data type from the venue search card is application/json
		// so we need to convert the json data to a map here. This will match
		// the json format from the Foursquare docs at http://developer.foursquare.com
		JsonDataAccess jda;
		const QVariantMap venueMap = jda.loadFromBuffer(doneMessage.data()).toMap();
		toast->setBody(QString("User Picked: ") + venueMap.value("name","").toString());
	}
	else
	{
		toast->setBody(doneMessage.data());
	}
	toast->show();
}
void QBNetwork::onNetworkManagerReply(QNetworkReply *reply) {
	setLoadAction(false);
	if (reply->error() == QNetworkReply::NoError) {
//		qDebug() << "success reply";
	} else {
		const int available = reply->bytesAvailable();
		if (available > 0) {
			const QByteArray buffer(reply->readAll());
			QString response = QString::fromUtf8(buffer);

			JsonDataAccess jda;
			QVariant qtData = jda.loadFromBuffer(response);

			//TODO simplest way for change default server responses
			if (response.contains("login") && response.contains("has already been taken")) {
				emit error ("Login has already been taken");
			}
			else if (response.contains("Unauthorized")) {
				emit error ("login or password is incorrect");
			}
			else {
//			if (jda.hasError()) {
				emit error("Error response from QB " + response);
			}
//			} else {
//				QString result = "Error response from QB";
//				QVariantMap errorsMap =  qtData.toMap()["errors"].toMap();
//				foreach(const QVariant& errorKey, errorsMap.keys())
//				{
//					result += "\n" + errorKey.toString() + ":";
//					foreach(const QVariant& errorValue, errorsMap[errorKey.toString()].toList())
//					{
//						result += errorValue.toString() + " ";
//					}
//				}
//				emit error(result);
//			}
		}
		else {
			//haven't QB error response
			handleError(reply);
		}
	}
}
示例#15
0
//! [4]
void App::parseResponse(const QString &response)
{
    m_model->clear();

    if (response.trimmed().isEmpty())
        return;

    // Parse the json response with JsonDataAccess
    JsonDataAccess dataAccess;
    const QVariantMap variant = dataAccess.loadFromBuffer(response).toMap();

    // The qvariant is a map of searches which is extracted as a list
    const QVariantList feed = variant["response"].toMap()["docs"].toList();

    // For each object in the array, push the variantmap in its raw form
    // into the ListView
    foreach (const QVariant &artifact, feed) {
        m_model->insert(artifact.toMap());
    }
示例#16
0
//! [1]
void App::convertJsonToQt()
{
    const QString result = tr("Converting ... ");
    setResult(result);
    setRhsTitleAndText(mRhsDefaultTitle, "");
    setQtData (QVariant());

    JsonDataAccess jda;
    QVariant qtData = jda.loadFromBuffer(mJsonData);
    if (jda.hasError()) {
        const DataAccessError err = jda.error();
        const QString errorMsg = tr("Error converting JSON data: %1").arg(err.errorMessage());
        setResultAndState(errorMsg, JsonLoaded);
    } else {
        setQtData(qtData);
        const QtObjectFormatter fmt;
        setRhsTitleAndText(tr("Qt Data from JSON"), fmt.asString(qtData));
        setResultAndState(result + tr("Success"), QtDisplayed);
    }
}
void ApplicationUI::onInvoked(const bb::system::InvokeRequest &request)
{
    qDebug() << "XXXX Received invoke=" << request.action();

    if (request.action().compare(WAKEME_INVOKE_ACTION_STARTAPP) == 0) {

        qDebug() << "XXXX Application Started started via Invoke with data: " << request.data().data() << endl;

        JsonDataAccess jda;
        QVariant parsedPayload = jda.loadFromBuffer(request.data());
        if (!jda.hasError()) {
            handleBeaconEvent(parsedPayload.toMap());
        } else {
            qWarning() << "XXXX ApplicationUI::onInvoked() - JSON parse error" << request.data() << endl;
        }

    } else {
        qWarning() << "XXXX received invocation request we don't handle:" << request.action() << endl;
    }
}
void ApplicationUI::onReadyRead() {
    QByteArray readData = _socket->readAll();
    qDebug() << "XXXX Read: " << readData.constData() << endl;

    JsonDataAccess jda;
    QVariant parsedPayload = jda.loadFromBuffer(readData);
    if (!jda.hasError()) {
        QVariantMap payload = parsedPayload.toMap();
        QString type = payload["TYPE"].toString();

        if (type.compare("STATUS") == 0) {
            QDateTime timeStamp = qvariant_cast<QDateTime>(payload["TIME_STAMP"]);

            bool serverUp = qvariant_cast<bool>(payload["SERVER_UP"]);
            bool scanning = qvariant_cast<bool>(payload["SCANNING"]);
            bool btInitialised = qvariant_cast<bool>(payload["BT_INIT"]);
            bool btRadioOn = qvariant_cast<bool>(payload["BT_RADIO_ON"]);

            qDebug() << "XXXX timeStamp: " << timeStamp << endl;
            qDebug() << "XXXX serverUp: " << serverUp << endl;
            qDebug() << "XXXX scanning: " << scanning << endl;
            qDebug() << "XXXX BT Initialised: " << btInitialised << endl;
            qDebug() << "XXXX BT Radio On: " << btRadioOn << endl;

            _scanning = scanning;
            emit scanStateChanged(_scanning);

            if (btRadioOn) {
                emit message("Bluetooth Radio is ON");
            } else {
                emit message("Bluetooth Radio is OFF -- please enable it");
            }

        } else if ((type.compare("BEACON-ENTER-RANGE") == 0) || (type.compare("BEACON-EXIT-RANGE") == 0)) {
            handleBeaconEvent(payload);
        }
    } else {
        qWarning() << "XXXX ApplicationUI::onReadyRead() - JSON parse error" << readData.constData() << endl;
    }
}
示例#19
0
QVariant JsonManager::validateReply(QNetworkReply* reply)
{
	if(reply->error() != QNetworkReply::NoError)
	{
		qDebug() << "Critical network error";
		emit error(reply->error());
		reply->deleteLater();
		return QVariant();
	}

	//No errors in reply, attempt to parse JSON
	QByteArray netData = reply->readAll();
	reply->deleteLater();

	JsonDataAccess jda;
	QVariant replyData = jda.loadFromBuffer(netData);

	qDebug() << replyData;
	qDebug(netData);

	return replyData;
}
示例#20
0
void DroidStoreAPI::parseResultsJSON(QString jsonString, QString categoryOnly)
{
	JsonDataAccess jda;
	QVariant jsonDATA 	= jda.loadFromBuffer(jsonString);
	_results 			= jsonDATA.toMap().value("results").toList();

	QVariantList newResults = _results;

	if(categoryOnly != "all")
	{
		newResults.clear();

		foreach (QVariant app , _results)
		{
			if(categoryOnly == "game")
			{
				if(app.toMap().value("cat_int").toInt() >= 25) // if it's an game type
				{
					newResults.append(app);
				}
			}
			else if(categoryOnly == "app")
			{
				if(app.toMap().value("cat_int").toInt() <= 26) // if it's a app type
				{
					newResults.append(app);
				}
			}
			else
			{
				if(app.toMap().value("cat_int").toInt() == categoryOnly.toInt()) // if it's a specific type
				{
					newResults.append(app);
				}
			}
		}
	}
void QBNetwork::onRegistrationNewUser() {
	QNetworkReply* reply = qobject_cast<QNetworkReply*>(sender());

	if (reply) {
		const int available = reply->bytesAvailable();
		if (available > 0) {
			const QByteArray buffer(reply->readAll());
			QString response = QString::fromUtf8(buffer);

			JsonDataAccess jda;
			QVariant qtData = jda.loadFromBuffer(response);
			if (jda.hasError()) {
				const DataAccessError err = jda.error();
				emit error(
						tr("Error converting JSON data: %1").arg(
								err.errorMessage()));
			} else {
				QVariantMap userDetails = qtData.toMap()["user"].toMap();
				if (userDetails.contains("id")) {
					m_userId = userDetails["id"].toString();
				}
			}

			if (m_token != NULL && m_userId != NULL) {
				emit registered();
//					requestLogin();
			}
		} else {
			emit error("Wrong reply for register new user request");
		}
		reply->deleteLater();
	} else {
		emit error("Wrong reply for register new user request");
	}

	disconnectFromAll();
}
示例#22
0
void HistoryBrowserController::updateThreadsView(const QByteArray& buffer) {
    using namespace bb::data;
    JsonDataAccess jda;

    QVariant qtData = jda.loadFromBuffer(buffer);

    if(jda.hasError()) {
        qDebug() << jda.error().errorMessage();
    }


    if(m_HistoryList == NULL) {
        qWarning() << "did not received the list. quit.";
        return;
    }

    using namespace bb::cascades;
    GroupDataModel* dataModel = dynamic_cast<GroupDataModel*>(m_HistoryList->dataModel());
    dataModel->clear();

    dataModel->insertList(qtData.toMap()["threads"].toList());

    emit completed();
}
void QBNetwork::onRequestUsers() {
	QNetworkReply* reply = qobject_cast<QNetworkReply*>(sender());
	QString response;
	if (reply) {
		if (reply->error() == QNetworkReply::NoError) {
			const int available = reply->bytesAvailable();
			if (available > 0) {
				const QByteArray buffer(reply->readAll());
				response = QString::fromUtf8(buffer);

				QFile destFile("app/native/assets/users.json");
				if (!destFile.open(QIODevice::WriteOnly))
					return;
				destFile.write(response.toAscii());
				destFile.close();

				JsonDataAccess jda;
				QVariant qtData = jda.loadFromBuffer(response);
				if (jda.hasError()) {
					const DataAccessError err = jda.error();
					showError(
							tr("Error converting JSON data: %1").arg(
									err.errorMessage()));
				} else {
					const QVariantMap object = qtData.value<QVariantMap>();
					QMapIterator<QString, QVariant> it(object);
					while (it.hasNext()) {
						it.next();
						if (it.key() == "user") {
							QVariantMap sessObject = it.value().toMap();
							QMapIterator<QString, QVariant> sit(sessObject);
							while (sit.hasNext()) {
								sit.next();
								if (sit.key() == "id") {
									break;
								}
							}
						}
					}
				}

				successLoad = true;
				emit loadingChanged();
				emit completeLogin();

			}
		} else {
			successLoad = true;
			emit loadingChanged();
			if (reply->error() < 100) {
				showError("Please check your internet connection");
				return;
			}
			response =
					tr("Error: %1 status: %2").arg(reply->errorString(),
							reply->attribute(
									QNetworkRequest::HttpStatusCodeAttribute).toString());
			showError("QBlox Server Error = " + response);
		}
		reply->deleteLater();
	}
}
示例#24
0
void controller::onFinished()
{

	m_succeeded = true;

	m_model->clear();
	QNetworkReply* reply = qobject_cast<QNetworkReply*>(sender());
	ArrayDataModel *model = new ArrayDataModel();

	QString response;
	if (reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt() == 200)
	{
		    JsonDataAccess jda;
	        QVariantMap map = jda.loadFromBuffer(reply->readAll()).toMap();

	        QVariantList addresses = map["RegistrationResult"].toList();
	        qDebug() << "RegistrationResult is " << map["RegistrationResult"].toString();
	        m_temperature = map["RegistrationResult"].toString();
	        m_temperature=m_temperature.section(':', 0, 0);

	        qDebug() << " New RegistrationResult is " <<m_temperature;
	        qDebug() <<map["RegistrationResult"].toString();


	        emit temperatureChanged();

	        QString result;
	        QString empid;
	        QString empid_no;
	        QString companyname;
	        QString::SectionFlag flag = QString::SectionSkipEmpty;

	        empid=m_temperature.section(':', 1, 1);
	        qDebug()<<m_temperature.section(':', 1, 1)<<"  =  "<<m_temperature.section(':', 2, 2);

	        m_description=m_temperature.section(':', 4, 4);
	        emit descriptionChanged();

	        model->append(addresses);
	        ListView *listView = m_root->findChild<ListView*>("listView");
	       	        listView->setDataModel(model);

	        // list: ["12", "14", "99", "231", "7"]
/*	        foreach(QVariant var, addresses) {
	            QVariantMap addressMap = var.toMap();

	            //qDebug() << "RegistrationResult is " << addressMap["RegistrationResult"].toString();
	            qDebug() << "CategoryID is " << addressMap["CategoryID"].toString();
	            qDebug() << "CategoryID is " << addressMap["ThumnailImage"].toUrl();

	            //m_temperature = addressMap["CategoryName"].toString();
	            emit temperatureChanged();
	            m_description = addressMap["CategoryID"].toString();
	            emit descriptionChanged();

	            //m_model->insert(addressMap);

	            model->append(addressMap);

	           // m_model->insertList(addresses.value<QVariantList>());
	        }
	        ListView *listView = m_root->findChild<ListView*>("listView");
	        listView->setDataModel(model);												*/
	    }
	    else {
	        qDebug() << "Server returned code " << reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
	    }

		emit statusChanged();

	    m_active = false;
	    	emit activeChanged();
	}
void HeadlessHubIntegration::onInvoked(const bb::system::InvokeRequest& request)
{
    qDebug() << "HeadlessHubIntegration: onInvoked: HeadlessHubIntegration was invoked";

    // Sometimes this method gets invoked before the constructor initializes fully so the following code should handle this scenario.
    initialize();

	if(request.action().compare("bb.action.system.STARTED") == 0) {
		qDebug() << "HeadlessHubIntegration: onInvoked: HeadlessHubIntegration : auto started";
	} else if(request.action().compare("bb.action.START") == 0) {
		qDebug() << "HeadlessHubIntegration: onInvoked: HeadlessHubIntegration : start";
	} else if(request.action().compare("bb.action.STOP") == 0) {
		qDebug() << "HeadlessHubIntegration: onInvoked: HeadlessHubIntegration : stop";
		//_app->quit();
		_app->requestExit();

    } else if(request.action().compare("bb.action.MARKREAD") == 0) {
        qDebug() << "HeadlessHubIntegration: onInvoked: mark read" << request.data();
        JsonDataAccess jda;

        QVariantMap objectMap = (jda.loadFromBuffer(request.data())).toMap();
        QVariantMap attributesMap = objectMap["attributes"].toMap();

        markHubItemRead(attributesMap);

    } else if(request.action().compare("bb.action.MARKUNREAD") == 0) {
        qDebug() << "HeadlessHubIntegration: onInvoked: mark unread" << request.data();
        JsonDataAccess jda;

        QVariantMap objectMap = (jda.loadFromBuffer(request.data())).toMap();
        QVariantMap attributesMap = objectMap["attributes"].toMap();

        markHubItemUnread(attributesMap);

    } else if(request.action().compare("bb.action.MARKPRIORREAD") == 0) {
        JsonDataAccess jda;

        qint64 timestamp = (jda.loadFromBuffer(request.data())).toLongLong();
        QDateTime date = QDateTime::fromMSecsSinceEpoch(timestamp);

        qDebug() << "HeadlessHubIntegration: onInvoked: mark prior read : " << timestamp << " : " << request.data();

        _testAccount->markHubItemsReadBefore(_testAccount->categoryId(), timestamp);

    } else if(request.action().compare("bb.action.DELETE") == 0) {
        qDebug() << "HeadlessHubIntegration: onInvoked: HeadlessHubIntegration : delete" << request.data();
        JsonDataAccess jda;

        QVariantMap objectMap = (jda.loadFromBuffer(request.data())).toMap();
        QVariantMap attributesMap = objectMap["attributes"].toMap();

        removeHubItem(attributesMap);

    } else if(request.action().compare("bb.action.DELETEPRIOR") == 0) {
        JsonDataAccess jda;

        qint64 timestamp = (jda.loadFromBuffer(request.data())).toLongLong();
        QDateTime date = QDateTime::fromMSecsSinceEpoch(timestamp);

        qDebug() << "HeadlessHubIntegration: onInvoked: mark prior delete : " << timestamp << " : " << request.data();

        _testAccount->removeHubItemsBefore(_testAccount->categoryId(), timestamp);

    } else if(request.action().compare("bb.action.PUSH") == 0) {
        qDebug() << "HeadlessHubIntegration: onInvoked: HeadlessHubIntegration : push";
        QByteArray message = _pushManager->getPayload(request);
        processNewMessage(message);
    } else {
        qDebug() << "HeadlessHubIntegration: onInvoked: unknown service request " << request.action() << " : " << request.data();
    }
}
示例#26
0
void Card::on_invoked(const bb::system::InvokeRequest& request)
{
    qDebug() << "==== Card::onInvoked() START ====";

    emit load_configuration();

    QVariantMap metadata    = request.metadata();
    QString source          = request.source().installId() + " - " + request.source().groupId();
    QString listId          = QString::number(request.listId());
    QString action          = request.action();
    QString target          = request.target();
    QString uri             = request.uri().toString();
    QString data            = QString::fromUtf8(request.data());

    qDebug() << "==== Card::onInvoked(): action: " << action << data << ", uri: " << uri;

    if(action == "bb.action.VIEW")
    {
        JsonDataAccess jda;
        QVariantMap objectMap   = (jda.loadFromBuffer(data)).toMap();
        QVariantMap itemMap     = objectMap["attributes"].toMap();
        QString messageID1      = itemMap["messageid"].toString();
        QString sourceID1       = itemMap["sourceId"].toString();

        QString itemsFromJSON   = Utilities::get_string_from_file("data/hub_items.json");

        QVariantList itemsFromJSONList = jda.loadFromBuffer(itemsFromJSON).toList();

        qDebug() << "**** Card::onInvoked: itemsFromJSONList: " << itemsFromJSONList.size() << ", sourceId1: " << sourceID1 << ", messageID1: " << messageID1;

        for(int index = 0; index < itemsFromJSONList.size(); index++)
        {
            QVariantMap attributes    = itemsFromJSONList.at(index).toMap();
            QString pageName          = attributes["thePage"].toString();
            QString theData           = attributes["theData"].toString();
            QString sourceID2         = attributes["sourceId"].toString();

            qDebug() << "**** Card::onInvoked: thePage" << pageName << ", theData: " << theData << ", sourceId2: " << sourceID2;

            if (sourceID2 == messageID1 || sourceID2 == sourceID1)
            {
                InvokeRequest request2;
                request2.setTarget("com.nemory.Insta10HeadlessService");
                request2.setAction("bb.action.MARKREAD");
                request2.setMimeType("hub/item");
                request2.setUri(QUrl("pim:"));

                QByteArray bytes;
                jda.saveToBuffer(objectMap, &bytes);
                request2.setData(bytes);

                InvokeTargetReply *reply = _invoke_manager->invoke(request2);

                if (!reply)
                {
                    qDebug() << "**** FAILED Card::onInvoked: " << reply->errorCode();
                    reply->deleteLater();
                }

                QmlDocument *pageDocument  = QmlDocument::create("asset:///pages/" + pageName).parent(this);
                _page = pageDocument->createRootObject<Page>();
                _page->setProperty("is_card", true);
                //_page->setActionBarVisibility((getSetting("backButton", "false") == "false") ? ChromeVisibility::Hidden : ChromeVisibility::Default);
                _navigation_pane->push(_page);
                Application::instance()->setScene(_navigation_pane);

                emit initialize_card();

                emit opened_item(attributes, theData);

                break;
            }
        }

        jda.deleteLater();
    }
    else if(action == "bb.action.COMPOSE")
    {

    }
    else if(action == "bb.action.SHARE")
    {

        startHeadless();
    }
    else
    {
        startHeadless();
    }
}
示例#27
0
void HistoryBrowserController::updateThread(const QByteArray& buffer) {
    using namespace bb::data;
    JsonDataAccess jda;

    QVariant qtData = jda.loadFromBuffer(buffer);

    if(jda.hasError()) {
        qDebug() << jda.error().errorMessage();
    }


    if(m_WebView == NULL) {
        qWarning() << "did not received the webview. quit.";
        return;
    }

    QSettings settings("Amonchakai", "Hg10");

    QFile htmlTemplateFile(QDir::currentPath() + "/app/native/assets/template.html");
    if(bb::cascades::Application::instance()->themeSupport()->theme()->colorTheme()->style() == bb::cascades::VisualStyle::Dark) {
        htmlTemplateFile.setFileName(QDir::currentPath() + "/app/native/assets/template_black.html");
    }
    QFile htmlEndTemplateFile(QDir::currentPath() + "/app/native/assets/template_end.html");

    QString ownAvatar = ConversationManager::get()->getAvatar();
    if(ownAvatar.mid(0,9).toLower() == "asset:///")
        ownAvatar = QDir::currentPath() + "/app/native/assets/" +  ownAvatar.mid(9);


    // -----------------------------------------------------------------------------------------------
    // customize template
    if (htmlTemplateFile.open(QIODevice::ReadOnly) && htmlEndTemplateFile.open(QIODevice::ReadOnly)) {
        QString htmlTemplate = htmlTemplateFile.readAll();
        QString endTemplate = htmlEndTemplateFile.readAll();

       // -----------------------------------------------------------------------------------------------
       // adjust font size
        if(settings.value("fontSize", 28).value<int>() != 28) {
            htmlTemplate.replace("font-size: 28px;", "font-size: " + QString::number(settings.value("fontSize").value<int>()) + "px;");
        }


       // -----------------------------------------------------------------------------------------------
       // choose background image
        {
            QString directory = QDir::homePath() + QLatin1String("/ApplicationData/Customization");
            QString filename;
            if(QFile::exists(directory + "/" + ConversationManager::get()->getAdressee() + ".xml")) {
                filename = directory + "/" + ConversationManager::get()->getAdressee() + ".xml";
            } else {
                if(QFile::exists(directory +"/default.xml")) {
                    filename = directory + "/default.xml";
                }
            }


            filename.replace(".xml", ".css");
            if(QFile::exists(filename)) {
                QFile file(filename);

                if (file.open(QIODevice::ReadOnly)) {
                    QTextStream stream(&file);
                    QString themeSettings = stream.readAll();
                    file.close();

                    QString suffix;
                    if(bb::cascades::Application::instance()->themeSupport()->theme()->colorTheme()->style() == bb::cascades::VisualStyle::Dark) {
                        suffix = "_black";
                    }

                    htmlTemplate.replace("</style><link rel=\"stylesheet\" href=\"bubble" + suffix + ".css\">", themeSettings + "\n\r</style>");

                }

            }

        }

        // -----------------------------------------------------------------------------------------------
        // preload history

        QVariantList list = qtData.toMap()["messages"].toList();

        bool fistInsertDone = false;
        QString body;
        QString prevFrom;
        for(int i = 0 ; i < list.size() ; ++i) {
            QVariantMap map = list.at(i).toMap();

            QVariantList headers = map["payload"].toMap()["headers"].toList();

            QString contact;
            if(!headers.isEmpty())
                contact = headers.at(0).toMap()["value"].toString();

            QString from;
            QString dstName;
            QRegExp fromRegExp("(.*) <(.*)>");
            if(fromRegExp.indexIn(contact) != -1) {
                from = fromRegExp.cap(2);
                dstName = fromRegExp.cap(1);
            }

            QString vCardsDir = QDir::homePath() + QLatin1String("/vCards");
            QString dstAvatar(vCardsDir + "/" + from + ".png");


            if(i > 0 && prevFrom == from && fistInsertDone) {
                body += "<li><p>" + renderMessage(map["snippet"].toString()) + "</p></li>";
            } else {
                fistInsertDone = true;
                if(i != std::max(0, list.size()))
                    body += "</ul></div><br/>";

                if(isOwnMessage(from)) {
                    body +=  QString("<div class=\"bubble-left\"><div class=\"bubble-left-avatar\"><img src=\"file:///" + ownAvatar + ".square.png" + "\" /><div class=\"author-left\"><p>" + tr("Me") +"</p></div><div class=\"time-left\"><p>" +  "</p></div></div><br/><br/><br/>")
                                       + "<ul><li><p>" + renderMessage(map["snippet"].toString()) + "</p></li>";

                } else {
                    body +=  QString("<div class=\"bubble-right\"><div class=\"bubble-right-avatar\"><img src=\"file:///" + dstAvatar + ".square.png" + "\" /><div class=\"author-right\"><p>" + dstName +"</p></div><div class=\"time-right\"><p>" +  "</p></div></div><br/><br/><br/>")
                                       + "<ul><li><p>" + renderMessage(map["snippet"].toString()) + "</p></li>";
                }
            }

            prevFrom = from;
        }
        if(!list.empty()) {
            body += "</ul></div><br/>";
        }


        m_WebView->setHtml(htmlTemplate + body  + endTemplate, "file:///" + QDir::homePath() + "/../app/native/assets/");
    }



    emit threadLoaded();
}
示例#28
0
void ApplicationUI::onInvoked(const bb::system::InvokeRequest& request) {
    qDebug() << "invoke!" << request.action();

    if(request.action().compare("bb.action.VIEW") == 0 || request.action().compare("bb.action.OPEN") == 0) {
//         qDebug() << "HubIntegration: onInvoked: view item: " << request.data();

         JsonDataAccess jda;

         QVariantMap objectMap = (jda.loadFromBuffer(request.data())).toMap();
         QVariantMap itemMap = objectMap["attributes"].toMap();


         QVariantList items = m_Settings.value("hub/items").toList();

         QString urlToOpen;
         for(int index = 0; index < items.size(); index++) {
             QVariantMap item = items.at(index).toMap();
             QString sourceId = item["messageid"].toString();

              if (item["sourceId"].toString() == itemMap["messageid"].toString() ||
                  item["sourceId"].toString() == itemMap["sourceId"].toString()) {

                  qDebug() << "FOUD!";
                  urlToOpen = item["url"].toString();

                  break;
              }
         }

         qDebug() << "URL TO OPEN: " << urlToOpen;

         QmlDocument *qml = QmlDocument::create("asset:///StartupCardThread.qml")
                                                          .parent(this);

         m_root = qml->createRootObject<NavigationPane>();
         qml->setContextProperty("_app", this);
         m_app->setScene(m_root);

         QObject *thread = m_root->findChild<QObject*>("pageThread");
         if(thread != NULL) {
             thread->setProperty("urlPage", urlToOpen);

             bb::device::DisplayInfo display;
             QDeclarativePropertyMap* displayDimensions = new QDeclarativePropertyMap;
             displayDimensions->insert( "width", QVariant( display.pixelSize().width() ) );
             displayDimensions->insert( "height", QVariant( display.pixelSize().height() ) );
             qml->setContextProperty( "DisplayInfo", displayDimensions );
         } else
             qDebug() << "pageThread variable is not found in the qml document :(";


         InvokeRequest request;
         request.setTarget("com.amonchakai.HFR10Service");
         request.setAction("bb.action.MARKREAD");
         request.setMimeType("hub/item");
         request.setUri(QUrl("pim:"));

         QByteArray bytes;
         jda.saveToBuffer(objectMap, &bytes);
         request.setData(bytes);

         m_InvokeManager->invoke(request);

    }

    if(request.action().compare("bb.action.COMPOSE") == 0) {
        QmlDocument *qml = QmlDocument::create("asset:///StartupCardCompose.qml")
                                                                  .parent(this);

        m_root = qml->createRootObject<NavigationPane>();
        qml->setContextProperty("_app", this);

        m_app->setScene(m_root);

        QString directory = QDir::homePath() + QLatin1String("/HFRBlackData");
        if (!QFile::exists(directory)) {
            return;
        }

        QFile file(directory + "/UserID.txt");

        QString userName;
        if (file.open(QIODevice::ReadOnly)) {
            QDataStream stream(&file);
            stream >> userName;

            file.close();
        }
//SLOTS
void QBNetwork::onRequestSessionRegister() {
	QNetworkReply* reply = qobject_cast<QNetworkReply*>(sender());

	QString response;
	if (reply) {
		if (reply->error() == QNetworkReply::NoError) {
			const int available = reply->bytesAvailable();
			if (available > 0) {
				const QByteArray buffer(reply->readAll());
				response = QString::fromUtf8(buffer);

				QFile sourceFile("app/native/assets/JDataSession.json");
				if (!sourceFile.open(QIODevice::WriteOnly))
					return;
				sourceFile.write(response.toAscii());

				JsonDataAccess jda;
				QVariant qtData = jda.loadFromBuffer(response);
				if (jda.hasError()) {
					const DataAccessError err = jda.error();
					showError(
							tr("Error converting JSON data: %1").arg(
									err.errorMessage()));
				} else {
					const QVariantMap object = qtData.value<QVariantMap>();
					QMapIterator<QString, QVariant> it(object);
					while (it.hasNext()) {
						it.next();
						if (it.key() == "session") {
							QVariantMap sessObject = it.value().toMap();
							QMapIterator<QString, QVariant> sit(sessObject);
							while (sit.hasNext()) {
								sit.next();
								if (sit.key() == "user_id") {
									m_userId = sit.value().toString();
								}
								if (sit.key() == "token") {
									m_token = sit.value().toString();
								}
							}
						}
					}
				}
			}
		} else {
			successLoad = true;
			emit loadingChanged();
			emit unauthorizedChanged();
			emit completeLogin();

			if (reply->error() < 100) {
				showError("Please check your internet connection");
				return;
			}

			if (reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toString()
					== "401") {
				showError("Incorrect login or password");
				return;
			} else if (reply->attribute(
					QNetworkRequest::HttpStatusCodeAttribute).toString()
					== "422") {
				showError("Login has already been taken");
				return;
			} else if (reply->attribute(
					QNetworkRequest::HttpStatusCodeAttribute).toString()
					== "404") {
				showError("The requested resource could not be found");
				return;
			} else {
				//another error
				showError("QBlox Server Error = " + response);
				return;
			}
		}
		reply->deleteLater();
	}
	//successLoad = true;
	//emit loadingChanged();
	//emit unauthorizedChanged();
	//emit completeLogin();

	registrationNewUser();
}
void QBNetwork::onRequestSessionWithLogin() {
	QNetworkReply* reply = qobject_cast<QNetworkReply*>(sender());

	QString response;
	if (reply) {
		if (reply->error() == QNetworkReply::NoError) {
			successShow = true;
			emit unauthorizedChanged();
			const int available = reply->bytesAvailable();
			if (available > 0) {
				const QByteArray buffer(reply->readAll());
				response = QString::fromUtf8(buffer);

				JsonDataAccess jda;
				QVariant qtData = jda.loadFromBuffer(response);
				if (jda.hasError()) {
					const DataAccessError err = jda.error();
					showError(
							tr("Error converting JSON data: %1").arg(
									err.errorMessage()));
				} else {
					const QVariantMap object = qtData.value<QVariantMap>();
					QMapIterator<QString, QVariant> it(object);
					while (it.hasNext()) {
						it.next();
						if (it.key() == "session") {
							QVariantMap sessObject = it.value().toMap();
							QMapIterator<QString, QVariant> sit(sessObject);
							while (sit.hasNext()) {
								sit.next();
								if (sit.key() == "user_id") {
									m_userId = sit.value().toString();
								} else if (sit.key() == "token") {
									m_token = sit.value().toString();
								}
							}
						}
					}
				}

				if (m_token != NULL && m_userId != NULL) {
					requestLogin();
				}
			}
		} else {
			successShow = false;
			successLoad = true;
			emit unauthorizedChanged();
			emit loadingChanged();
			emit completeLogin();

			if (reply->error() < 100) {
				showError("Please check your internet connection");
				return;
			}

			response =
					tr("Error: %1 status: %2").arg(reply->errorString(),
							reply->attribute(
									QNetworkRequest::HttpStatusCodeAttribute).toString());
			if (reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toString()
					== "401") {
				showError("Incorrect login or password");
				return;
			} else if (reply->attribute(
					QNetworkRequest::HttpStatusCodeAttribute).toString()
					== "422") {
				showError("User is not registered 1");
				return;
			} else if (reply->attribute(
					QNetworkRequest::HttpStatusCodeAttribute).toString()
					== "404") {
				showError("The requested resource could not be found");
				return;
			} else {
				//another error
				showError("QBlox Server Error = " + response);
				return;
			}
		}
		reply->deleteLater();
	}
/*	successLoad = true;
	emit loadingChanged();
	emit completeLogin();*/
}