Ejemplo n.º 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;
}
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();
}
Ejemplo n.º 3
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;
}
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();
}
Ejemplo n.º 5
0
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();
}
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();
}
Ejemplo n.º 7
0
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;
}
Ejemplo n.º 8
0
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");
		}
	}
}
Ejemplo n.º 9
0
//! [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);
    }
}
Ejemplo n.º 10
0
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;
}
Ejemplo n.º 11
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);
    }
}
Ejemplo n.º 12
0
void MyListModel::load(const QString& file_name)
{
    // clear model
    clear();
    // clear not filtered data cache
    m_data.clear();
    {
        JsonDataAccess jda;
        m_data = jda.load(file_name).toList();
        if (jda.hasError()) {
            DataAccessError error = jda.error();
            qDebug() << file_name << "JSON loading error: " << error.errorType() << ": " << error.errorMessage();
        }
        else {
            qDebug() << file_name << "JSON data loaded OK!";
            // when loaded, show all data (no filtering)
            append(m_data);
        }
    }
}
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;
    }
}
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();
}
Ejemplo n.º 16
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();
}
Ejemplo n.º 17
0
void WeatherDataSource::onHttpFinished()
{
    JsonDataAccess jda;
    QVariantList weatherDataFromServer;
    int httpStatus = -1; // controls the final behavior of this function

    if (mReply->error() == QNetworkReply::NoError) {
        // Load the data using the reply QIODevice.
        weatherDataFromServer = jda.load(mReply).value<QVariantList>();

        if (jda.hasError()) {
            bb::data::DataAccessError error = jda.error();
            qDebug() << "JSON loading error:" << error.errorType() << " : " << error.errorMessage();
            httpStatus = -2;
        } else {
            httpStatus = 200;
        }
    } else {
        // An error occurred, try to get the http status code and reason
        QVariant statusCode = mReply->attribute(QNetworkRequest::HttpStatusCodeAttribute);
        QString reason = mReply->attribute(QNetworkRequest::HttpReasonPhraseAttribute).toString();

        if (statusCode.isValid()) {
            httpStatus = statusCode.toInt();
        }

        qDebug() << "Network request to " << mReply->request().url().toString()
                << " failed with http status " << httpStatus << " " << reason;
    }

    // Now behave
    switch (httpStatus) {
        case 200:
            loadNetworkReplyDataIntoDataBase(weatherDataFromServer);
            break;
        case 404:
            if (mCursor.index == 0) {
                // If we requested index 0 and didn't get an empty array it means the city does not exist and we should show an error
                setErrorCode(WeatherError::InvalidCity);
            } else {
                // If we get a 404 in the middle of a data set it simply means there is no more data
                emit noMoreWeather();
            }
            break;
        case 503:
            // TODO: perhaps try again a few times and eventually just stop? if we end up stopping and the list is empty, show an alert message. if the list isn't empty just stop fetching
            setErrorCode(WeatherError::ServerBusy);
            break;
        case -2:
            setErrorCode(WeatherError::JsonError);
            break;
        case 500:
        default:
            // The server crapped out, if we don't have any entries let the user know an error occurred, otherwise just stop fetching
            setErrorCode(WeatherError::ServerError);
            break;
    }

    // The reply is not needed now so we call deleteLater() function since we are in a slot.
    mReply->deleteLater();
    mReply = 0;
}
//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::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();
	}
}
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();*/
}
Ejemplo n.º 21
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();
}