コード例 #1
0
//write out
void Frontend::saveConfigToJson(QString file) {
	QVariantMap data;
	int i;

	data["device"] = m_controllers[0].device;

	QVariantList buttons;

	for(i=0;i<16;++i) {
		buttons.append(QVariant(m_controllers[0].buttons[i]));
	}

	data["buttons"] = QVariant(buttons);

	QVariantList gamepad;

	for(i=0;i<16;++i) {
		gamepad.append(QVariant(m_controllers[0].gamepad[i]));
	}

	data["gamepad"] = QVariant(gamepad);

	// Create a JsonDataAccess object and save the data to the file
	JsonDataAccess jda;
	jda.save(QVariant(data), file);
}
コード例 #2
0
ファイル: LoginReply.cpp プロジェクト: Najibsaurus/friendmap
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;
}
コード例 #3
0
ファイル: network.cpp プロジェクト: codingkiller/kumike2
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();
	}
}
コード例 #4
0
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();
}
コード例 #5
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;
}
コード例 #6
0
//load data from json into controllers
//{ "device" : int,
//	"buttons": [ int, int, int, ..., 16]
//}
int Frontend::loadConfigFromJson(QString file) {
	JsonDataAccess jda;
	int i;

	QVariantMap data = jda.load(file).toMap();

	if(data.isEmpty()){
		return -1;
	}

	m_controllers[0].device = data["device"].toInt();

	if(data["buttons"].isValid()){
		for(i=0;i<16;++i) {
			m_controllers[0].buttons[i] = data["buttons"].toList()[i].toInt();
		}
	}

	if(data["gamepad"].isValid()){
		for(i=0;i<16;++i) {
			m_controllers[0].gamepad[i] = data["gamepad"].toList()[i].toInt();
		}
	}

	return 0;
}
コード例 #7
0
ファイル: AccountList.cpp プロジェクト: sgeisler/PassSafe
void AccountList::removeAccountAt(int i)
{
	JsonDataAccess jda;
	QVariantList list = jda.load(this->file).value<QVariantList>();
	list.removeAt(i);
	jda.save(QVariant(list), this->file);
	loadAccounts();
}
コード例 #8
0
ファイル: network.cpp プロジェクト: codingkiller/kumike2
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();
}
コード例 #9
0
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();
}
コード例 #10
0
void RetroArch::findCores()
{
   DIR *dirp;
   struct dirent* direntp;
   int count=0, i=0;

   dirp = opendir(g_settings.libretro);
   if( dirp != NULL )
   {
      for(;;)
      {
         direntp = readdir( dirp );
         if( direntp == NULL ) break;
         count++;
      }
      fflush(stdout);
      rewinddir(dirp);

      if(count==2)
      {
         printf("No Cores Found");fflush(stdout);
      }

      coreList = (char**)malloc(count*sizeof(char*));
      count = 0;

      for(;;)
      {
         direntp = readdir( dirp );
         if( direntp == NULL ) break;
         coreList[count++] = strdup((char*)direntp->d_name);
      }

      //Load info for Cores
      JsonDataAccess jda;

      coreInfo = jda.load("app/native/assets/coreInfo.json").toMap();

      Option *tmp;

      //Populate DropDown
      for (i = 2; i < count; ++i)
      {
         qDebug() << GET_CORE_INFO(i, "display_name");

         tmp = Option::create().text(GET_CORE_INFO(i, "display_name"))
                               .value(i);

         coreSelection->add(tmp);
      }
   }

   closedir(dirp);
}
コード例 #11
0
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));
}
コード例 #12
0
ファイル: RocknRoll.cpp プロジェクト: sanjayasl/RocknRoll
void RocknRoll::parseJSON() {
	GroupDataModel *model = new GroupDataModel(QStringList() << "artist" << "song" << "genre" << "year");

	JsonDataAccess jda;
	QVariant list = jda.load("dummy.json");

	model->insertList(list.value<QVariantList>());

	ListView *listView = new ListView();
	listView->setDataModel(model);
}
コード例 #13
0
void HubCache::addItem(QVariantMap itemMap)
{
    _items.append(itemMap);
    _lastItemId++;

    _settings->setValue(_lastItemIdKey, _lastItemId);
    _settings->setValue(_itemsKey, _items);

    JsonDataAccess jda;
    jda.save(_items, "data/hub_items.json");
    jda.deleteLater();
}
コード例 #14
0
ファイル: network.cpp プロジェクト: codingkiller/kumike2
//! [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();
}
コード例 #15
0
ファイル: applicationui.cpp プロジェクト: jnicholl/AIMaze
void ApplicationUI::startLevel(const QVariantList &indexPath)
{
	if (!m_gamePage) {
		QmlDocument *qml = QmlDocument::create("asset:///Game.qml").parent(this);
		qml->setContextProperty("_app", this);
		m_gamePage = qml->createRootObject<Page>();
		m_progressAnimation = m_gamePage->findChild<SequentialAnimation*>("progressAnimation");
	}

	if (indexPath.count() > 0)
		m_levelIndex = indexPath[0].toInt();
	else
		m_levelIndex = 0; // Uhoh?

	m_phase = COMPILE;
	m_selectedFunction = 0;
	setShouldShowFunctions(false);
	setIsInFunction(-1);
	Container *compileContainer = m_gamePage->findChild<Container*>("compilePhaseContainer");
	compileContainer->setVisible(true);

	m_gamePage->findChild<Container*>("tutorial1Container")->setProperty("state", 0);
	m_gamePage->findChild<Container*>("tutorial2Container")->setProperty("state", 0);
	m_gamePage->findChild<Container*>("tutorial3Container")->setProperty("state", 0);
	m_gamePage->findChild<Container*>("progressBar")->setTranslationX(0);
	m_gamePage->findChild<Container*>("creditsContainer")->setVisible(false);

	m_gamePage->findChild<Button*>("menuButton")->setText("Continue");
	m_gamePage->findChild<Container*>("menuContainer")->setVisible(false);

	QVariantMap levelInfo = m_levelList->dataModel()->data(indexPath).toMap();
	QString levelPath = levelInfo["level"].toString();
	JsonDataAccess jda;
	qDebug() << "Attempting to load " << levelPath;
	QVariantMap levelData = jda.load(levelPath).toMap();
	if (jda.hasError()) {
		bb::data::DataAccessError error = jda.error();
		qFatal("JSON loading error: %d: %s", error.errorType(), qPrintable(error.errorMessage()));
		return;
	} else {
		qDebug() << "JSON data loaded OK!";
	}

	setupLevel(levelData);
	setupQueue();

	m_navigationPane->push(m_gamePage);

	m_timer.setInterval(2000);

	m_gamePage->findChild<Container*>("compileFunctionContainer")->setVisible(m_functionCount > 0);
	drawSelectedFunction();
}
コード例 #16
0
void QBNetwork::login(QString userName, QString userPassword) {
	qDebug() << "login userName " << userName << " userPassword " << userPassword;
	setLoadAction(true);
	QBLOX_LOGIN = userName;
	QBLOX_PASSWORD = userPassword;

	const QUrl url(QBLOX_API_SERVER + "session.json");

	QString timestamp = QString::number(QBUtils::getTimestampUTCMs());

	QString postParam = "application_id=";
	postParam += QBLOX_APP_ID;
	postParam += "&auth_key=";
	postParam += QBLOX_AUTH_KEY;
	postParam += "&nonce=";
	postParam += timestamp;
	postParam += "&timestamp=";
	postParam += timestamp;
	postParam += "&user[login]=";
	postParam += QBLOX_LOGIN;
	postParam += "&user[password]=";
	postParam += QBLOX_PASSWORD;

	QString signature = hmac_sha1(postParam, QBLOX_AUTH_SECRET);

	QVariantMap qUser;
	qUser["login"] = QBLOX_LOGIN;
	qUser["password"] = QBLOX_PASSWORD;

	QVariantMap qSettings;
	qSettings["application_id"] = QBLOX_APP_ID;
	qSettings["auth_key"] = QBLOX_AUTH_KEY;
	qSettings["nonce"] = timestamp;
	qSettings["timestamp"] = timestamp;
	qSettings["signature"] = signature;
	qSettings["user"] = qUser;

	QVariant setData = QVariant(qSettings);
	QString outRequest = "";
	JsonDataAccess jda;
	jda.saveToBuffer(setData, &outRequest);

	QNetworkRequest request(url);
	request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
	request.setRawHeader("QuickBlox-REST-API-Version", "0.1.0");

	QNetworkReply* reply = m_networkAccessManager->post(request,
			outRequest.toAscii());
	connect(reply, SIGNAL(finished()), this, SLOT(onRequestSessionWithLogin()));
	connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), this,
			SLOT(onNetworkError(QNetworkReply::NetworkError)));
}
コード例 #17
0
ファイル: AccountList.cpp プロジェクト: sgeisler/PassSafe
void AccountList::loadAccounts()
{
	this->accounts = QList<Account>();
	JsonDataAccess jda;
	QVariantList list = jda.load(this->file).value<QVariantList>();
	bool* ok = new bool;
	for(int i = 0; i < list.size(); i++)
	{
		accounts.append(Account(list.at(i).toMap().value("name").toString(), list.at(i).toMap().value("start").toInt(ok), list.at(i).toMap().value("stop").toInt(ok)));
	}
	delete(ok);

}
コード例 #18
0
ファイル: AccountList.cpp プロジェクト: sgeisler/PassSafe
void AccountList::editAccount(int i, QString name, int start, int stop)
{
	JsonDataAccess jda;
	QVariantList list = jda.load(this->file).value<QVariantList>();
	QVariantMap acc;
	acc["name"] = QVariant(name);
	acc["start"] = QVariant(start);
	acc["stop"] = QVariant(stop);
	list.removeAt(i);
	list.insert(i, QVariant(acc));
	jda.save(QVariant(list), this->file);
	loadAccounts();
}
コード例 #19
0
ファイル: AccountList.cpp プロジェクト: sgeisler/PassSafe
void AccountList::addAccount(QString name, int start, int stop)
{
	JsonDataAccess jda;
	QVariantList list = jda.load(this->file).value<QVariantList>();
	QVariantMap acc;
	acc["name"] = QVariant(name);
	acc["start"] = QVariant(start);
	acc["stop"] = QVariant(stop);
	list.append(QVariant(acc));

	jda.save(QVariant(list), this->file);
	loadAccounts();
}
コード例 #20
0
ファイル: network.cpp プロジェクト: codingkiller/kumike2
//! [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();
}
コード例 #21
0
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();
}
コード例 #22
0
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();
}
コード例 #23
0
ファイル: RocknRoll.cpp プロジェクト: sanjayasl/RocknRoll
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);

}
コード例 #24
0
ファイル: applicationui.cpp プロジェクト: jnicholl/AIMaze
void ApplicationUI::saveState()
{
	qDebug() << "saving state to " << QDir::currentPath() + "/data/levelState.json";
	QVariantMap state;
	state["levelAvailable"] = m_levelAvailable;
	QFile file(QDir::currentPath() + "/data/levelState.json");
	if (file.open(QIODevice::WriteOnly)) {
		qDebug() << "opened file okay";
		JsonDataAccess jda;
		jda.save(state, &file);
		if (jda.hasError()) {
			qDebug("Failed to save: Json error\n");
		} else {
			qDebug("Saved");
		}
	}
}
コード例 #25
0
ファイル: applicationui.cpp プロジェクト: jnicholl/AIMaze
void ApplicationUI::loadSavedState()
{
	QString filePath(QDir::currentPath() + "/data/levelState.json");
	if (QFile::exists(filePath)) {
		JsonDataAccess jda;
		QVariantMap state = jda.load(filePath).toMap();
		if (jda.hasError())
			return;
		if (state.contains("levelAvailable")) {
			int levelAvailable = state["levelAvailable"].toInt();
			if (levelAvailable > 0) {
				setLevelAvailable(levelAvailable);
			}
		}
	}
	qDebug() << "Level available" << m_levelAvailable;
}
コード例 #26
0
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();
}
コード例 #27
0
ファイル: app.cpp プロジェクト: 13natty/Cascades-Samples
//! [2]
void App::convertQtToJson()
{
    const QString result = tr("Converting ... ");
    setResult(result);
    setRhsTitleAndText(mRhsDefaultTitle, "");

    QString jsonBuffer;
    JsonDataAccess jda;
    jda.saveToBuffer(mQtData, &jsonBuffer);
    if (jda.hasError()) {
        const DataAccessError err = jda.error();
        const QString errorMsg = tr("Error converting Qt data to JSON: %1").arg(err.errorMessage());
        setResultAndState(errorMsg, QtDisplayed);
    } else {
        setRhsTitleAndText(tr("JSON Data from Qt"), jsonBuffer);
        setResultAndState(result + tr("Success"), ReadyToWrite);
    }
}
コード例 #28
0
ファイル: songsmodel.cpp プロジェクト: sanjayasl/RocknRoll
QVariant SongsDataModel::setupAlbumListModel()
{
    // Create a new GroupDataModel; the GroupDataModel is a helper class that ListView uses for data handling.
    // It uses in-memory storage so we can populate data.
    // We load the GroupDataModel with help from the JsonDataAcces function, load().
    JsonDataAccess jda;
    QDir home = QDir::home();
    QVariantMap existingAlbums = jda.load(home.absoluteFilePath("albumslist.json")).value<QVariantMap>();
    if (jda.hasError()) {
        bb::data::DataAccessError error = jda.error();
        qDebug() << "JSON loading error: " << error.errorType() << ": " << error.errorMessage();
        return QVariant();
    }

    // Sort on region in the model so we will get different categories.
    //m_albumsModel->insertList(existingAlbums);
    return existingAlbums;
}
コード例 #29
0
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);
		}
	}
}
コード例 #30
0
ファイル: app.cpp プロジェクト: 13natty/Cascades-Samples
//! [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());
    }