Ejemplo n.º 1
0
Schema *MessageFacade::defineSchema(QJsonObject *root, ControllerNode *pControllerNode){
    QJsonValue jsonValue = root->value(SCHEMA);
    if (!jsonValue.isUndefined() && jsonValue.isObject()){
        QJsonObject schema= jsonValue.toObject();
        QJsonValue strings =schema.value(STRING_TYPE);
        QJsonValue ints =schema.value(INT_TYPE);
        QJsonValue primaryKey = schema.value(PRIMARY_KEY);
        if (!strings.isUndefined() && strings.isArray() &&!ints.isUndefined()
                && ints.isArray() && !primaryKey.isUndefined() && primaryKey.isObject()){
            QJsonArray columnaStringType = strings.toArray();
            QJsonArray columnaIntsType = ints.toArray();
            QJsonObject columnaPrimaryKey = primaryKey.toObject();
            bool success = true;
            QJsonObject currentObject;
            for (int x = 0; x < columnaStringType.size(); x++){
                currentObject =columnaStringType.at(x).toObject();
                success = success && currentObject.value(currentObject.keys().at(0)).isDouble();
            }
            for (int x = 0; x < columnaIntsType.size(); x++)success = success && columnaIntsType.at(x).isString();
            QString primaryKeyName =columnaPrimaryKey.keys().at(0);
            qDebug() << "validando....";
            if (success && validatingPrimaryKey(primaryKeyName,&columnaPrimaryKey)){
                qDebug() << "validacion completa el JSON es valido";
                Schema *dataSchema = StorageblockFacade::getInstance()->createSchema(1+columnaIntsType.size()+columnaStringType.size());
                unsigned int sizeOfBytes = 0;
                QJsonObject primaryKeyScheme;
                primaryKeyScheme = columnaPrimaryKey.value(primaryKeyName).toObject();
                if (primaryKeyName.compare(INT_TYPE) == 0)sizeOfBytes = sizeof(int);
                else sizeOfBytes = primaryKeyScheme.value(primaryKeyScheme.keys().at(0)).toInt()*sizeof(char);
                dataSchema->setSchemaOverColumn(0,primaryKeyScheme.keys().at(0).toStdString(),sizeOfBytes,
                (primaryKeyName.compare(INT_TYPE) == 0)?SchemeRow::INT_TYPE:SchemeRow::STRING_TYPE);
                int place= 1;
                for (int x = 0; x < columnaIntsType.size(); x++){
                    currentObject =columnaIntsType.at(x).toObject();
                    dataSchema->setSchemaOverColumn(x+(place++),columnaIntsType.at(x).toString().toStdString(),sizeof(int),SchemeRow::INT_TYPE);
                }
                for (int x = 0; x < columnaStringType.size(); x++){
                    currentObject =columnaStringType.at(x).toObject();
                    currentObject.value(currentObject.keys().at(0)).toString();
                    dataSchema->setSchemaOverColumn(x+place,currentObject.keys().at(0).toStdString(),sizeof(char)*currentObject.value(currentObject.keys().at(0)).toInt(),SchemeRow::STRING_TYPE);
                }
                SchemeRow row;
                QString type;
                for(int x = 0; x < dataSchema->getLenght();x++){
                    row = (*dataSchema)[x];
                    type= (row.getTypeRestrictor()==SchemeRow::INT_TYPE)?"int    ":"string";
                    qDebug() << "| type: "<< type<< "\t| name: " << row.toString().c_str() << "\t\t| size: \t"<< row.getByteSize();
                }
                return dataSchema;
            }
        }
    }
    return 0;
}
Ejemplo n.º 2
0
bool DmxAddress::fromJson(QJsonObject& obj) {
    QJsonValue universeValue = obj.value("universe");
    QJsonValue offsetValue = obj.value("offset");

    if(universeValue.isUndefined() || offsetValue.isUndefined()){
        qCritical() << "Missing universe or offset";
        return false;
    }

    universe = universeValue.toVariant().toInt();
    offset = offsetValue.toVariant().toInt();

    return true;
}
Ejemplo n.º 3
0
bool MessageFacade::obtainRaidAndDataStructure(QJsonObject *root, QString *pRaid, QString *pDataStructure)
{
    QJsonValue jsonValue = root->value(RAID_TYPE);
    bool success = false;
    if (!jsonValue.isUndefined() && jsonValue.isString()){
        *pRaid = jsonValue.toString();
        success = StorageblockFacade::getInstance()->isValidRaid(*pRaid);
    }
    jsonValue = root->value(DATASTRUCTURE_TYPE);
    if (!jsonValue.isUndefined() && jsonValue.isString()){
        *pDataStructure=jsonValue.toString();
        success = success&&StorageblockFacade::getInstance()->isValidDataStructure(*pDataStructure);
    }
    return success;
}
Ejemplo n.º 4
0
/**
 * @brief Algorithm::initialize Loads the corresponding QJsonObject for this algorithm
 * @param loader The plugin loader which loads the QJsonObject
 * @return True, if all went well.
 */
bool Algorithm::initialize(QPluginLoader *loader) {
    //read the QJsonObject parameter
    if (!loader) return false;
    QJsonObject tmp = loader->metaData();
    if (tmp.isEmpty()) return false;
    QJsonValue v = tmp.value("MetaData");
    if (v.isUndefined()) return false;
    QJsonObject o = v.toObject();
    if (o.isEmpty()) return false;

    mId = "";
    mName = "";
    mDescription = "";

    QString version = "";
    if (o.contains("Author")) {}
    if (o.contains("Date")) {}
    if (o.contains("Name")) mName = o.value("Name").toString();
    else {} //LOG WARNING
    if (o.contains("Version")) version = o.value("Version").toString();
    else {} //LOG WARNING
    if (o.contains("Description")) mDescription = o.value("Description").toString();
    else {} //LOG WARNING
    mId = mName + " " + version;
    if (mId.trimmed() == "") {} //LOG WARNING

    if (o.contains("Properties")) mDefaultParameters = o.value("Properties").toObject();
    else {} //LOG WARNING

    return true;
}
Ejemplo n.º 5
0
bool QJsonValueProto::isUndefined() const
{
  QJsonValue *item = qscriptvalue_cast<QJsonValue*>(thisObject());
  if (item)
    return item->isUndefined();
  return false;
}
Ejemplo n.º 6
0
Utils::optional<MarkupOrString> ParameterInformation::documentation() const
{
    QJsonValue documentation = value(documentationKey);
    if (documentation.isUndefined())
        return Utils::nullopt;
    return MarkupOrString(documentation);
}
Ejemplo n.º 7
0
void AzubuHandler::handleStatus(const Stream &stream, QNetworkReply* reply)
{

    if(reply->error() != QNetworkReply::NoError) {
        emit streamUncertain(stream);
        reply->deleteLater();
        return;
    }

    QByteArray data = reply->readAll();

    QJsonDocument response(QJsonDocument::fromJson(data.mid(1,data.length()-2)));
    QJsonObject responseObject = response.object();

    QJsonValue online = responseObject["Online"];

    if(online.isNull()) {
        emit streamUncertain(stream);
    } else if(online.isUndefined()) {
        emit streamUncertain(stream);
    } else if(online.toString().compare("0")==0){
        emit streamOffline(stream);
    } else {
        emit streamOnline(stream);
    }

    reply->deleteLater();
}
Ejemplo n.º 8
0
void MessageFacade::interpretMessage(QString pMessage, ControllerNode *pControllerNode)
{
    mut.lock();
    QJsonObject root;
    // se llama al decifrador
    pMessage = decrypt(pMessage);
    QString messageType;
    //se veridica si cumple con el formato JSON
    if (isValidJsonSyntax(pMessage,&root)){
        //Verifica el tipo de mensaje
        QJsonValue jsonValue = root.value(MESSAGE_TYPE);
        if (!jsonValue.isUndefined() && jsonValue.isString()) {
            messageType = jsonValue.toString();
            //para mensajes de tipo storage block
            if (messageType.compare(MESSAGE_TYPE_STORAGE_BLOCK) == 0){
                interpretStorageBlockMessage(&root,pControllerNode);
            }
            //para mensajes que operen sobre los registros
            else if (messageType.compare(MESSAGE_TYPE_REGISTER) == 0){
                interpretRegisterkMessage(&root,pControllerNode);
            }
            //para mensajes que operen sobre los usarios
            else if (messageType.compare(MESSAGE_TYPE_USER) == 0){
                interpretUserMessage(&root,pControllerNode);
            }
        }
    }
    mut.unlock();

}
Ejemplo n.º 9
0
bool Storage::getUserLimits (const QString& user, QVariantMap& target)
{
    QString val;
    QFile file;
    QString filename = QString (CLEPSYDRA_WORKING_FOLDER).append(CLEPSYDRA_JSON_USERDATA_FILENAME);
    file.setFileName(filename);
    if ( !file.isReadable() ) {
        //
        return false;
    }
    if (file.open(QIODevice::ReadOnly | QIODevice::Text)==true) {
        val = file.readAll();
        file.close();
    } else {
        qDebug () << filename << "json file not found";
        return false;
    }

    QJsonDocument d = QJsonDocument::fromJson(val.toUtf8());
    if (d.isEmpty()) {
        qDebug () << "Not valid document.";
        return false;
    }

    QJsonObject obj = d.object();
    QJsonValue mapArray = obj.value(user);
    if (mapArray.isUndefined()) {
        qDebug () << "User not found from limits.";
        return false;
    }

    QVariantMap dataC = mapArray.toObject().toVariantMap();
    target = dataC.take(user).toMap();
    return true;
}
bool CashPointInRadius::fromJson(const QJsonObject &json)
{
    const QJsonValue radius =    json["radius"];
    const QJsonValue latitude =  json["latitude"];
    const QJsonValue longitude = json["longitude"];
    const QJsonValue filter    = json["filter"];

    const QJsonValue topLeft =   json["topLeft"];
    const QJsonValue botRight =  json["bottomRight"];

    if (!radius.isDouble() || !latitude.isDouble() || !longitude.isDouble() ||
        !(filter.isObject() || filter.isUndefined()))
    {
        return false;
    }

    if (!topLeft.isObject() || !botRight.isObject()) {
        return false;
    }

    data["longitude"] = longitude;
    data["latitude"] = latitude;
    data["radius"] = radius;
    data["topLeft"] = topLeft;
    data["bottomRight"] = botRight;

    if (filter.isObject()) {
        data["filter"] = filter;
    }

    return true;
}
Ejemplo n.º 11
0
    bool EtherIPC::readReply(QJsonValue& result) {
        const QString data = fReadBuffer;
        fReadBuffer.clear();

        if ( data.isEmpty() ) {
            setError("Error on socket read: " + fSocket.errorString());
            fCode = 0;
            return false;
        }

        QJsonParseError parseError;
        QJsonDocument resDoc = QJsonDocument::fromJson(data.toUtf8(), &parseError);

        if ( parseError.error != QJsonParseError::NoError ) {
            qDebug() << data << "\n";
            setError("Response parse error: " + parseError.errorString());
            fCode = 0;
            return false;
        }

        const QJsonObject obj = resDoc.object();
        const int objID = obj["id"].toInt(-1);

        if ( objID != fActiveRequest.getCallID() ) { // TODO
            setError("Call number mismatch " + QString::number(objID) + " != " + QString::number(fActiveRequest.getCallID()));
            fCode = 0;
            return false;
        }

        result = obj["result"];

        // get filter changes bugged, returns null on result array, see https://github.com/ethereum/go-ethereum/issues/2746
        if ( result.isNull() && fActiveRequest.getType() == GetFilterChanges ) {
            result = QJsonValue(QJsonArray());
        }

        if ( result.isUndefined() || result.isNull() ) {
            if ( obj.contains("error") ) {
                if ( obj["error"].toObject().contains("message") ) {
                    fError = obj["error"].toObject()["message"].toString();
                }

                if ( obj["error"].toObject().contains("code") ) {
                    fCode = obj["error"].toObject()["code"].toInt();
                }

                return false;
            }

            if ( fActiveRequest.getType() != GetTransactionByHash ) { // this can happen if out of sync, it's not fatal for transaction get
                setError("Result object undefined in IPC response for request: " + fActiveRequest.getMethod());
                qDebug() << data << "\n";
                return false;
            }
        }

        return true;
    }
Ejemplo n.º 12
0
/*!
 * Convert string \a json in JSON format to variant \a data.
 *
 * The format of the json string is assumed to be a one-item array.
 *
 * Returns true if the conversion is successful, false otherwise.
 *
 * \sa convertToJson()
 */
bool VersitUtils::convertFromJson(const QString &json, QVariant *data)
{
    const QJsonDocument jsonDoc = QJsonDocument::fromJson(json.toUtf8());
    const QJsonValue jsonValue = jsonDoc.array().at(0);
    if (jsonValue.isUndefined())
        return false;
    *data = jsonValue.toVariant();
    return true;
}
void QProcessResultThread::GetStringValue( QString& strValue, const char* pKey, const QJsonObject& jsonObj )
{
    strValue = "";

    QJsonValue jsonVal = jsonObj.value( pKey );
    if ( !jsonVal.isUndefined( ) && jsonVal.isString( ) ) {
        strValue = jsonVal.toString( );
    }
}
Ejemplo n.º 14
0
void GetManyTestCase::onTextMessageReceived(QString message)
{
    DEBUG(m_testClientId,"Message received");
    TRACE(m_testClientId,message);

    QJsonParseError parseError;
    QJsonDocument  jsonDocument;
    QJsonObject    jsonObject;

    jsonDocument = QJsonDocument::fromJson(message.toUtf8(),&parseError);
    jsonObject = jsonDocument.object();
    if (parseError.error == QJsonParseError::NoError)
    {
        QString actionString =jsonObject["action"].toString();

        if (actionString != "get")
        {
            WARNING(m_testClientId,"Received incorrect action.");
            emit finished(false);
            return;
        }

        QString requestId = jsonObject["requestId"].toString();
        QJsonObject errorObject = jsonObject["error"].toObject();
        if (!errorObject.empty())
        {
            WARNING(m_testClientId,"Get Many failed.");
            QString errorMessage = errorObject["message"].toString();
            DEBUG(m_testClientId,QString("Error! Request ID : %1, Message : %2").arg(requestId, errorMessage));
            emit finished(false);
            return;
        }

        QJsonValue receivedValue = jsonObject.value("value");
        if(receivedValue.isUndefined())
        {
            WARNING(m_testClientId,"Get response doesn't contain any values.");
            emit finished(false);
            return;
        }
        else if(!receivedValue.isArray())
        {
            WARNING(m_testClientId,"Get response doesn't contain a value array as it should.");
            emit finished(false);
            return;
        }

        INFO(m_testClientId,"Successfully got many values.");
        emit  finished(true);
    }
    else
    {
        emit  finished(false);
    }
}
Ejemplo n.º 15
0
bool LedRun::fromJson(QJsonObject& obj) {
    QJsonValue dmxStartValue = obj.value("start");
    QJsonValue dmxEndValue = obj.value("end");
    QJsonValue reverseValue = obj.value("reverse");

    if(dmxStartValue.isUndefined() || dmxEndValue.isUndefined()){

        qCritical() << "Missing DMX start or end address";

        return false;
    }

    bool parseSuccess = true;

    QJsonObject dmxStartObj = dmxStartValue.toObject();
    QJsonObject dmxEndObj = dmxEndValue.toObject();

    parseSuccess &= dmxStart.fromJson( dmxStartObj );
    parseSuccess &= dmxEnd.fromJson( dmxEndObj );
    reverse = reverseValue.toBool();

    return parseSuccess;
}
Ejemplo n.º 16
0
ServerConfig::ServerConfig(const QJsonValue& value)
    : _networkType(ServerConfig::NetworkType::disabled)
{
    if (!value.isUndefined()) // else: take default values
    {
        if (!value.isObject())
            throw new InvalidFieldException(entity_name, "");
        QJsonObject o = value.toObject();
        QJsonValue networkType = o[network_type_field];
        if (networkType.isString())
            _networkType = deserializeNetworkType(networkType.toString());
        else
            throw InvalidFieldException(entity_name, network_type_field);
    }
}
Ejemplo n.º 17
0
Goods *Parser::ParseGoods(const QJsonObject &jGoods) {
    QJsonValue jValue;

    // barcode
    jValue = jGoods.value("barcode");
    if (jValue.isUndefined() || !jValue.isString()) {
        return NULL;
    }
    QString strBarcode = jValue.toString();

    // name
    jValue = jGoods.value("name");
    if (jValue.isUndefined() || !jValue.isString()) {
        return NULL;
    }
    QString strName = jValue.toString();

    // unit
    jValue = jGoods.value("unit");
    if (jValue.isUndefined() || !jValue.isString()) {
        return NULL;
    }
    QString strUnit = jValue.toString();

    // category
    jValue = jGoods.value("category");
    if (jValue.isUndefined() || !jValue.isString()) {
        return NULL;
    }
    QString strCategory = jValue.toString();

    // subCategory
    jValue = jGoods.value("subCategory");
    if (jValue.isUndefined() || !jValue.isString()) {
        return NULL;
    }
    QString strSubCategory = jValue.toString();

    // price
    jValue = jGoods.value("price");
    if (jValue.isUndefined() || !jValue.isDouble()) {
        return NULL;
    }
    float fPrice = (float)jValue.toDouble();

    // new a goods object
    Goods *pGoods = new Goods(strBarcode, strName);
    pGoods->SetCategory(strCategory, strSubCategory);
    pGoods->SetQuantUnit(strUnit);
    pGoods->SetUnitPrice(fPrice);

    return pGoods;
}
Ejemplo n.º 18
0
//! Gets an item from the cache.
QJsonValue VaultFront::get(
	CacheType type,  //!< The type of the requested item.
	int id
) const
{
	// Try fetching the item.
	AsyncFetch* fetch = 0;
	switch( type )
	{
	case CacheType::Class :
		fetch = m_core->classes()->get( id );
		break;

	case CacheType::ObjectType :
		fetch = m_core->objectTypes()->get( id );
		break;

	case CacheType::PropertyDefinition :
		fetch = m_core->propertyDefinitions()->get( id );

	// Unknown item, return the null we set earlier.
	default:
		break;
	};	

	QJsonValue value;
	if( fetch->state() == AsyncFetch::Finished )
	{
		value = fetch->value();
		Q_ASSERT( ! value.isNull() && ! value.isUndefined() );
	}
	else if( fetch->state() == AsyncFetch::Error )
	{
		value = QJsonValue::Null;
	}
	else
	{
		Q_ASSERT( false );
	}
	fetch->deleteLater();

	// Return the value.
	return value;
}
Ejemplo n.º 19
0
ItemOffer *Parser::ParseOffer(const QJsonObject &jOffer,
        const QHash<QString, Goods *> &pGoodsMap) {
    QJsonValue jValue;

    // type
    jValue = jOffer.value("type");
    if (jValue.isUndefined() || !jValue.isString()) {
        return NULL;
    }
    QString strType = jValue.toString();

    ItemOffer *pOffer = NULL;
    // parse offer info for each type
    if (!strType.compare(OFFER_TYPE_BUY3FREE1)) { // OfferBuy3Free1
        pOffer = ParseBuy3Free1(jOffer, pGoodsMap);
    }

    return pOffer;
}
Ejemplo n.º 20
0
void LocationManager::goToAddressFromResponse(const QJsonObject& responseData) {
    QJsonValue status = responseData["status"];
    qDebug() << responseData;
    if (!status.isUndefined() && status.toString() == "success") {
        const QJsonObject& data = responseData["data"].toObject();
        const QJsonValue& userObject = data["user"];
        const QJsonValue& placeObject = data["place"];

        if (!placeObject.isUndefined() && !userObject.isUndefined()) {
            emit multipleDestinationsFound(userObject.toObject(), placeObject.toObject());
        } else if (placeObject.isUndefined()) {
            Application::getInstance()->getAvatar()->goToLocationFromAddress(userObject.toObject()["address"].toObject());
        } else {
            Application::getInstance()->getAvatar()->goToLocationFromAddress(placeObject.toObject()["address"].toObject());
        }
    } else {
        QMessageBox::warning(Application::getInstance()->getWindow(), "", "That user or location could not be found.");
    }
}
Ejemplo n.º 21
0
void analyserQ::fillCombobox(HttpRequestWorker* worker){
	qDebug() << "handleResult";
	QString msg;
	if (worker->error_type == QNetworkReply::NoError) {
		// communication was successful
		msg = worker->response;
	}
	else {
		// an error occurred
		msg = "Error: " + worker->error_str;
		QMessageBox::information(this, "", msg);
		//return;
	}

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

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

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

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

	foreach(const QJsonValue & v, array)
	{
		liste->addItem(v.toObject().value("id").toString());
	}
Ejemplo n.º 22
0
void MessageFacade::interpretRegisterkMessage(QJsonObject *root, ControllerNode *pControllerNode)
{
    QJsonValue jsonValue = root->value(SUB_MESSAGE_TYPE);
    QString messageSubType;
    if (!jsonValue.isUndefined() && jsonValue.isString()) {
        messageSubType = jsonValue.toString();
        // para ontener un registro
        if (messageSubType.compare(SUB_MESSAGE_TYPE_OBTAIN) == 0){
            QJsonArray a= jsonValue.toArray();
        }
        // para insertar un registro
        else if (messageSubType.compare(SUB_MESSAGE_TYPE_SAVE) == 0){

        }
        // para borrar un registro
        else if (messageSubType.compare(SUB_MESSAGE_TYPE_ERASE) == 0){

        }
    }
}
Ejemplo n.º 23
0
    int findId(QString id, int rowHint)
    {
        Q_ASSERT(rowHint >= 0);

        const int count = _data.count();
        if (rowHint < count) {
            QJsonValue hintId = _data[rowHint].toObject()[EnginioString::id];
            if (hintId == id)
                return rowHint;
            if (id.isEmpty() && (hintId.isNull() || hintId.isUndefined()))
                return rowHint;
        }

        // TODO optimize it, in most caseses we need to just check around rowHint
        for (int i = count - 1; i >= 0; --i) {
            if (_data[i].toObject()[EnginioString::id] == id)
                return i;
        }
        return -1;
    }
Ejemplo n.º 24
0
void MessageFacade::interpretUserMessage(QJsonObject *root, ControllerNode *pControllerNode)
{
    QJsonValue jsonValue = root->value(SUB_MESSAGE_TYPE);
    QString messageSubType;
    if (!jsonValue.isUndefined() && jsonValue.isString()) {
        messageSubType = jsonValue.toString();
        // para crear un usuario
        if (messageSubType.compare(SUB_MESSAGE_TYPE_CREATE) == 0){

        }
        // para asociar un usuario con un storageblock
        else if (messageSubType.compare(SUB_MESSAGE_TYPE_ASSOCIATE) == 0){

        }
        // para iniciar seccion con el usuario
        else if (messageSubType.compare(SUB_MESSAGE_TYPE_START_SESSION) == 0){

        }
    }
}
Ejemplo n.º 25
0
void MessageFacade::interpretStorageBlockMessage(QJsonObject *root, ControllerNode *pControllerNode)
{
    QJsonValue jsonValue = root->value(SUB_MESSAGE_TYPE);
    QString messageSubType;
    if (!jsonValue.isUndefined() && jsonValue.isString()) {
        messageSubType = jsonValue.toString();
        // para crear un storage block
        if (messageSubType.compare(SUB_MESSAGE_TYPE_CREATE) == 0){
            createStorageBlock(root,pControllerNode);
        }
        // para listar los storage
        else if (messageSubType.compare(SUB_MESSAGE_TYPE_LIST) == 0){

        }
        // para borrar un storage block
        else if (messageSubType.compare(SUB_MESSAGE_TYPE_ERASE) == 0){

        }
    }
}
Ejemplo n.º 26
0
void OS2LPlugin::slotProcessTCPPackets()
{
    QTcpSocket *socket = (QTcpSocket *)sender();
    if (socket == NULL)
        return;

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

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

    QString event = jEvent.toString();

    if (event == "btn")
    {
        QJsonValue jName = jsonObj.value("name");
        QJsonValue jState = jsonObj.value("state");
        qDebug() << "Got button event with name" << jName.toString() << "and state" << jState.toString();
        uchar value = jState.toString() == "off" ? 0 : 255;
        emit valueChanged(m_inputUniverse, 0, getHash(jName.toString()), value, jName.toString());
    }
    else if (event == "cmd")
    {
        QJsonValue jId = jsonObj.value("id");
        QJsonValue jParam = jsonObj.value("param");
        qDebug() << "Got CMD message" << jId.toInt() << "with param" << jParam.toDouble();
        quint32 channel = quint32(jId.toInt());
        QString cmd = QString("cmd%1").arg(channel);
        emit valueChanged(m_inputUniverse, 0, quint32(jId.toInt()), uchar(jParam.toDouble()), cmd);
    }
    else if (event == "beat")
    {
       qDebug() << "Got beat message" << message;
       emit valueChanged(m_inputUniverse, 0, 8341, 255, "beat");
    }
}
Ejemplo n.º 27
0
QJsonRpcMessage QJsonRpcMessage::createErrorResponse(QJsonRpc::ErrorCode code,
                                                     const QString &message,
                                                     const QJsonValue &data) const
{
    QJsonRpcMessage response;
    QJsonObject error;
    error.insert(QLatin1String("code"), code);
    if (!message.isEmpty())
        error.insert(QLatin1String("message"), message);
    if (!data.isUndefined())
        error.insert(QLatin1String("data"), data);

    response.d->type = QJsonRpcMessage::Error;
    QJsonObject *object = response.d->object.data();
    object->insert(QLatin1String("jsonrpc"), QLatin1String("2.0"));
    if (d->object->contains(QLatin1String("id")))
        object->insert(QLatin1String("id"), d->object->value(QLatin1String("id")));
    else
        object->insert(QLatin1String("id"), 0);
    object->insert(QLatin1String("error"), error);
    return response;
}
Ejemplo n.º 28
0
void AzubuHandler::handlePreview() {

    QNetworkReply *reply = qobject_cast<QNetworkReply*>(QObject::sender());
    QByteArray data = reply->readAll();

    // delete the reply
    reply->deleteLater();

    QJsonDocument response(QJsonDocument::fromJson(data.mid(1,data.length()-3)));
    QJsonObject streamJson = response.object();

    QJsonValue online = streamJson["Online"];

    if(!online.isNull() && !online.isUndefined() && !online.toString().compare("0")==0) {
        AzubuStream stream;
        stream.read(streamJson);
        emit setPreview(stream);
    } else {
        emit resetPreview();
    }

}
Ejemplo n.º 29
0
ItemOffer *Parser::ParseBuy3Free1(const QJsonObject &jOffer,
        const QHash<QString, Goods *> &pGoodsMap) {
    QJsonValue jValue;

    // barcodes
    jValue = jOffer.value("barcodes");
    if (jValue.isUndefined() || !jValue.isArray()) {
        return NULL;
    }
    QJsonArray jCodeArray = jValue.toArray();

    ItemOffer *pOffer = new OfferBuy3Free1();
    // parse each barcode
    for (int i = 0; i < jCodeArray.size(); ++i) {
        jValue = jCodeArray.at(i);

        if (jValue.isString()) { // add offer goods
            pOffer->InsertGoods(pGoodsMap.value(jValue.toString()));
        }
    }

    return pOffer;
}
Ejemplo n.º 30
0
Nuria::Internal::JsonRpcRequest Nuria::Internal::JsonRpcUtil::dissectRequestObject (const QJsonObject &object) {
	static const QString jsonrpc2_0 = QStringLiteral("2.0");
	static const QString jsonrpcField = QStringLiteral("jsonrpc");
	static const QString methodField = QStringLiteral("method");
	static const QString paramsField = QStringLiteral("params");
	static const QString idField = QStringLiteral("id");
	static const QString pathField = QStringLiteral("path"); // Resource extension
	
	// Get values
	JsonRpcRequest result;
	QJsonValue jsonrpcValue = object.value (jsonrpcField);
	QJsonValue methodValue = object.value (methodField);
	QJsonValue paramsValue = object.value (paramsField);
	QJsonValue idValue = object.value (idField);
	QJsonValue pathValue = object.value (pathField);
	
	// Json-Rpc 2.0 sanity check of the "id" field
	if (idValue.type () == QJsonValue::Bool ||
	    idValue.type () == QJsonValue::Array ||
	    idValue.type () == QJsonValue::Object) {
		result.version = InvalidRequest;
	        return result;
		
	}
	
	// Store id now so we can reply with more precise error messages if needed.
	result.id = idValue;
	
	// Check other fields
	if (jsonrpcValue.type () != QJsonValue::String ||
	    methodValue.type () != QJsonValue::String ||
	    jsonrpcValue.toString () != jsonrpc2_0) {
		result.version = InvalidRequest;
		return result;
	}
	
	// This implementation needs the "params" field to be an object (if it exists)
	if (!paramsValue.isUndefined () && paramsValue.type () != QJsonValue::Object) {
		result.version = InvalidParams;
		return result;
	}
	
	// The request is at least a 2.0 request.
	result.version = JsonRpc2_0;
	
	// Check that if "path" exists it's a string. In this case, it's a
	// request with the Resource extension.
	if (!pathValue.isUndefined ()) {
		if (pathValue.isString ()) {
			result.version = JsonRpc2_0_Resource;
			result.path = pathValue.toString (); // Store 'path'
		} else {
			result.version = InvalidRequest;
			return result;
		}
		
	}
	
	// Fill 'result'
	result.method = methodValue.toString ();
	result.params = paramsValue.toObject ().toVariantMap ();
	return result;
}