json schema added for checking incoming messages

This commit is contained in:
johan
2013-08-17 19:20:19 +02:00
parent 59e13a2b5f
commit b66c397a46
7 changed files with 158 additions and 10 deletions

View File

@@ -1,12 +1,36 @@
// system includes
#include <stdexcept>
#include <cassert>
// stl includes
#include <iostream>
#include <sstream>
#include <iterator>
// Qt includes
#include <QResource>
// project includes
#include "JsonClientConnection.h"
JsonClientConnection::JsonClientConnection(QTcpSocket *socket) :
QObject(),
_socket(socket)
_socket(socket),
_schemaChecker(),
_receiveBuffer()
{
// read the json schema from the resource
QResource schemaData(":/schema.json");
assert(schemaData.isValid());
Json::Reader jsonReader;
Json::Value schemaJson;
if (!jsonReader.parse(reinterpret_cast<const char *>(schemaData.data()), reinterpret_cast<const char *>(schemaData.data()) + schemaData.size(), schemaJson, false))
{
throw std::runtime_error("Schema error: " + jsonReader.getFormattedErrorMessages()) ;
}
_schemaChecker.setSchema(schemaJson);
// connect internal signals and slots
connect(_socket, SIGNAL(disconnected()), this, SLOT(socketClosed()));
connect(_socket, SIGNAL(readyRead()), this, SLOT(readData()));
}
@@ -50,6 +74,19 @@ void JsonClientConnection::handleMessage(const std::string &message)
return;
}
if (!_schemaChecker.validate(messageRoot))
{
const std::list<std::string> & errors = _schemaChecker.getMessages();
std::stringstream ss;
ss << "Error while validating json: {";
foreach (const std::string & error, errors) {
ss << error << ", ";
}
ss << "}";
sendErrorReply(ss.str());
return;
}
handleNotImplemented(messageRoot);
}