Example #1
0
TEST(MinibarRouter,Unittest){
    RouteNode root;
    Json::Value pathValues;
    TokenSet test = tokenize("foo/bar/baz","/");

    // insert route
    root.addRoute(test,42);
    root.addRoute(tokenize("foo/*/gorf","/"),13);
    root.addRoute(tokenize("foo/bar/baz/:gorf","/"),29);

    // prevent duplicates
    ASSERT_THROW(root.addRoute(test,42),MinibarException);

    // matching
    pathValues.clear();
    ASSERT_TRUE(root.matchRoute(tokenize("x/y/z","/"),pathValues) == RouteNode::NO_ROUTE_MATCH);
    ASSERT_TRUE(pathValues.empty());

    pathValues.clear();
    ASSERT_TRUE(root.matchRoute(tokenize("foo/bar/baz","/"),pathValues) == 42);
    ASSERT_TRUE(pathValues.empty());

    pathValues.clear();
    ASSERT_TRUE(root.matchRoute(tokenize("foo/bar/baz/goat","/"),pathValues) == 29);
    ASSERT_TRUE(pathValues.isMember("gorf"));
    ASSERT_TRUE(pathValues["gorf"].asString().compare("goat") == 0);
}
Example #2
0
bool SpriteData::importData(Json::Value root)
{
    mSpriteHash.clear();
    if (root.empty())
    {
        return false;
    }
    else
    {
        mResourceDirPath = QString::fromStdString(root["resourceDirPath"].asString());

        Json::Value sprites = root["sprites"];
        for(Json::Value::iterator iter = sprites.begin() ; sprites.end() != iter ; iter++)
        {
            QString keyName = QString::fromStdString(iter.key().asString());
            Json::Value data = *iter;
            SpriteDef sDef;

            sDef.mGridX = data["gridX"].asInt();
            sDef.mGridY = data["gridY"].asInt();
            sDef.mCenterX = data["centerX"].asInt();
            sDef.mCenterY = data["centerY"].asInt();
            sDef.mImageID = keyName;

            mSpriteHash.insert(keyName, sDef);
        }
        return true;
    }
}
Example #3
0
CommandProcessor::CommandProcessor(string &json_cmd_str)
{
	Json::Reader reader;
	Json::Value root;
	bool parseresult = false;
	m_validate_cmd = 0;
	try
	{
		parseresult = reader.parse(json_cmd_str, root);
		if(parseresult && !root.empty())
		{
			m_test_type = root["TestType"].asString();
			m_run_id = root["RunID"].asString();
			m_commands = root["Commands"];
			m_validate_cmd = 1;
		}
		else
		{
			Log::Error("JSON parse error or no command in the json");
		}
	}
	catch(...)
	{
		Log::Error("Get parse command exception");
	}
}
Example #4
0
void Settings::setJson(const std::string & name, const Json::Value & value) {
	if (!value.empty())
		set(name, json_writer.write( value )); //todo: remove later

	std::lock_guard<std::mutex> lock(m_mutex);
	m_json[name] = value;
}
Example #5
0
TransactionSkeleton toTransactionSkeleton(Json::Value const& _json)
{
    TransactionSkeleton ret;
    if (!_json.isObject() || _json.empty())
        return ret;

    if (!_json["from"].empty())
        ret.from = jsToAddress(_json["from"].asString());
    if (!_json["to"].empty() && _json["to"].asString() != "0x")
        ret.to = jsToAddress(_json["to"].asString());
    else
        ret.creation = true;

    if (!_json["value"].empty())
        ret.value = jsToU256(_json["value"].asString());

    if (!_json["gas"].empty())
        ret.gas = jsToU256(_json["gas"].asString());

    if (!_json["gasPrice"].empty())
        ret.gasPrice = jsToU256(_json["gasPrice"].asString());

    if (!_json["data"].empty())							// ethereum.js has preconstructed the data array
        ret.data = jsToBytes(_json["data"].asString());

    if (!_json["code"].empty())
        ret.data = jsToBytes(_json["code"].asString());

    if (!_json["nonce"].empty())
        ret.nonce = jsToU256(_json["nonce"].asString());
    return ret;
}
Example #6
0
  bool KeepLiveStreamAlive()
  {
    //Example request:
    //{"CardId":"String content","Channel":{"BroadcastStart":"String content","BroadcastStop":"String content","ChannelId":"1627aea5-8e0a-4371-9022-9b504344e724","ChannelType":0,"DefaultPostRecordSeconds":2147483647,"DefaultPreRecordSeconds":2147483647,"DisplayName":"String content","GuideChannelId":"1627aea5-8e0a-4371-9022-9b504344e724","LogicalChannelNumber":2147483647,"Sequence":2147483647,"Version":2147483647,"VisibleInGuide":true},"RecorderTunerId":"1627aea5-8e0a-4371-9022-9b504344e724","RtspUrl":"String content","StreamLastAliveTime":"\/Date(928142400000+0200)\/","StreamStartedTime":"\/Date(928142400000+0200)\/","TimeshiftFile":"String content"}
    //Example response:
    //true
    if(!g_current_livestream.empty())
    {
      Json::StyledWriter writer;
      std::string arguments = writer.write(g_current_livestream);

      Json::Value response;
      int retval = ForTheRecordJSONRPC("ForTheRecord/Control/KeepLiveStreamAlive", arguments, response);

      if (retval != E_FAILED)
      {
        //if (response == "true")
        //{
        return true;
        //}
      }
    }

    return false;
  }
Example #7
0
bool deserialize(const Json::Value& node, glm::quat& q)
{
	if (node.empty())
	{
		std::cout << "Node is empty." << std::endl;
		return false;
	}
	if (!node.isArray())
	{
		std::cout << "Node data type is not array." << std::endl;
		return false;
	}
	if (node.size() != 4)
	{
		std::cout << "Node data type is not array with size 4." << std::endl;
		return false;
	}

	glm::quat temp;
	for (unsigned int i = 0; i < 4; ++i)
	{
		if (!deserialize(node[i], temp[i]))
		{
			std::cout << "Node data at index " << i << " is invalid." << std::endl;
			return false;
		}
	}

	q = temp;
	return true;
}
Example #8
0
/** Test entity writing */
void testEntityWrite() {
    IndexHandler ih;
    std::string name = "_x";
    std::string field_name = "a";
    defpair e1Def;

    // setup test entity
    e1Def.push_back(std::make_pair(new IntegerColumn(), field_name));
    makeTestEntity(name, e1Def);
    writeEntities();

    // Fetch the entity written
    Json::Value value;
    ih.fetchEntity(name, value);

    // Ensure name matches and attribute exists
    assert(std::strcmp(value[JSON_ATTR_ENT_ENT].asCString(),
        name.c_str()) == 0);
    assert(value[JSON_ATTR_ENT_FIELDS].isMember(field_name));
    assert(std::strcmp(value[JSON_ATTR_ENT_FIELDS][field_name].asCString(),
        COLTYPE_NAME_INT) == 0);

    // Cleanup
    removeEntities();
    releaseObjects();

    for (defpair::iterator it = e1Def.begin() ; it != e1Def.end(); ++it)
        delete it->first;

    // test removal
    Json::Value json;
    ih.fetchRaw("*", json);
    assert(json.empty());
}
Example #9
0
uint32_t screen::serialize_events (uint8_t* dest, int maxlength)
{
    static int dimx = -1, dimy = -1;
    Json::Value events;
    if (update.events || dimx != gps->dimx || dimy != gps->dimy)
    {
        events["dims"]["x"] = gps->dimx;
        events["dims"]["y"] = gps->dimy;
        dimx = gps->dimx;
        dimy = gps->dimy;
    }
    bool colors_changed = update_colors();
    if (update.events || colors_changed)
    {
        Json::Value all_colors;
        for (int i = 0; i < 16; i++)
        {
            Json::Value cur_color;
            for (int j = 0; j < 3; j++)
                cur_color.append((int)(255.0 * colors[i][j]));
            all_colors.append(cur_color);
        }
        events["colors"] = all_colors;
    }
    if (events.empty())
        return 0;
    std::string json = Json::toSimpleString(events);
    strncpy((char*)dest, json.c_str(), maxlength);
    update.events = false;
    return json.size();
}
Example #10
0
BOOL C360ChromePlugIn::ExportUrl(Json::Value& url_obj, int32 nPid, PFAVORITELINEDATA* ppData, int32 nDataNum, int32& nRealDataNum)
{
	if (url_obj.empty() || url_obj["type"].asString() != std::string("url"))
	{
		return FALSE;
	}

	if( nDataNum == nRealDataNum)
		return FALSE;

	ppData[nRealDataNum]->nId = nRealDataNum + ID_VALUE_360EXTREME_BEGIN;
	ppData[nRealDataNum]->bFolder = false;
	ppData[nRealDataNum]->bDelete = false;
	StringToInt64(url_obj["date_added"].asString(), ppData[nRealDataNum]->nAddTimes);
	ppData[nRealDataNum]->nLastModifyTime =  0;
	ppData[nRealDataNum]->nPid = nPid;

	wcscpy_s(ppData[nRealDataNum]->szTitle, MAX_LENGTH -1, StringHelper::Utf8ToUnicode(url_obj["name"].asString()).c_str());
	wcscpy_s(ppData[nRealDataNum]->szUrl, MAX_LENGTH - 1, StringHelper::Utf8ToUnicode(url_obj["url"].asString()).c_str());
	ppData[nRealDataNum]->szUrl[MAX_LENGTH-1] = 0;

	CCRCHash ojbCrcHash;
	ojbCrcHash.GetHash((BYTE *)ppData[nRealDataNum]->szTitle, wcslen(ppData[nRealDataNum]->szTitle) * sizeof(wchar_t),  \
		(BYTE *)&ppData[nRealDataNum]->nHashId, sizeof(int32));

	nRealDataNum++;

    return TRUE;
}
Example #11
0
int API::api_read(Json::Value &request, Json::Value &response, Json::Value &errors)
{
	if (validate_read(request["data"], errors) < 0)
	{
		response["status"] = Json::Value(STATUS_STRUCTURE);
		return -1;
	}

	int user = authenticate(request["auth"]);

	if (user == -1)
	{
		response["status"] = STATUS_AUTH;
		errors.append(Json::Value("Authentication failed"));
		return -1;
	}
	create_session(response, user);

	Json::Value call_data;

	if (strcmp(request["data"]["view"].asCString(), "list") == 0)
	{
		if (strcmp(request["data"]["type"].asCString(), "profile") == 0) 			call_data = read_profile_list(request["data"], user, errors);
		else if (strcmp(request["data"]["type"].asCString(), "department") == 0) 	call_data = read_department_list(request["data"], user, errors);
		else if (strcmp(request["data"]["type"].asCString(), "user") == 0) 			call_data = read_user_list(request["data"], user, errors);
		else if (strcmp(request["data"]["type"].asCString(), "pictogram") == 0) 	call_data = read_pictogram_list(request["data"], user, errors);
		else if (strcmp(request["data"]["type"].asCString(), "application") == 0) 	call_data = read_application_list(request["data"], user, errors);
		else if (strcmp(request["data"]["type"].asCString(), "category") == 0) 		call_data = read_category_list(request["data"], user, errors);
		else
		{
			response["status"] = STATUS_STRUCTURE;
			errors.append(Json::Value("Invalid data type requested"));
		}
	}
	else
	{
		if (strcmp(request["data"]["type"].asCString(), "profile") == 0) 			call_data = read_profile_details(request["data"], user, errors);
		else if (strcmp(request["data"]["type"].asCString(), "department") == 0) 	call_data = read_department_details(request["data"], user, errors);
		else if (strcmp(request["data"]["type"].asCString(), "user") == 0) 			call_data = read_user_details(request["data"], user, errors);
		else if (strcmp(request["data"]["type"].asCString(), "pictogram") == 0) 	call_data = read_pictogram_details(request["data"], user, errors);
		else if (strcmp(request["data"]["type"].asCString(), "application") == 0) 	call_data = read_application_details(request["data"], user, errors);
		else if (strcmp(request["data"]["type"].asCString(), "category") == 0) 		call_data = read_category_details(request["data"], user, errors);

		else
		{
			response["status"] = STATUS_STRUCTURE;
			errors.append(Json::Value("Invalid data type requested"));
		}
	}

	if (!errors.empty())
	{
		response["status"] = Json::Value(STATUS_ACCESS);
		return -1;
	}

	response["data"] = call_data;

	return 0;
}
static void createYEIImpl(VRPNMultiserverData &data, OSVR_PluginRegContext ctx,
                          Json::Value const &root, std::string port) {
    if (port.empty()) {
        throw std::runtime_error(
            "Could not create a YEI device: no port specified!.");
    }
    port = normalizeAndVerifySerialPort(port);

    bool calibrate_gyros_on_setup =
        root.get("calibrateGyrosOnSetup", false).asBool();
    bool tare_on_setup = root.get("tareOnSetup", false).asBool();
    double frames_per_second = root.get("framesPerSecond", 250).asFloat();

    Json::Value commands = root.get("resetCommands", Json::arrayValue);
    CStringArray reset_commands;

    if (commands.empty()) {
        // Enable Q-COMP filtering by default
        reset_commands.push_back("123,2");
    } else {
        for (Json::ArrayIndex i = 0, e = commands.size(); i < e; ++i) {
            reset_commands.push_back(commands[i].asString());
        }
    }

    osvr::vrpnserver::VRPNDeviceRegistration reg(ctx);

    reg.registerDevice(new vrpn_YEI_3Space_Sensor(
        reg.useDecoratedName(data.getName("YEI_3Space_Sensor")).c_str(),
        reg.getVRPNConnection(), port.c_str(), 115200, calibrate_gyros_on_setup,
        tare_on_setup, frames_per_second, 0, 0, 1, 0,
        reset_commands.get_array()));
    reg.setDeviceDescriptor(
        osvr::util::makeString(com_osvr_Multiserver_YEI_3Space_Sensor_json));
}
int BitcoinMarketInfo::getBitcoinMarketInfo() {


    Curly curly;
    Json::Value retJSON;

    if (curly.Fetch(this->serviceURL) == CURLE_OK){

        if (curly.HttpStatus() != 200) {
            return FAIL;
        }
        retJSON = curly.getContentJSON();
        //std::cout << "status: " << curly.HttpStatus() << std::endl;
        //std::cout << "type: " << curly.Type() << std::endl;
        //std::vector<std::string> headers = curly.Headers();

        //for(std::vector<std::string>::iterator it = headers.begin();
        //        it != headers.end(); it++)
        //    std::cout << "Header: " << (*it) << std::endl;
        if (!retJSON.empty()) {
            this->setBuy(retJSON.get("ticker", "" ).get("buy", "" ).asDouble());
            this->setDate(retJSON.get("ticker", "" ).get("date", "" ).asInt());
            this->setHigh(retJSON.get("ticker", "" ).get("high", "" ).asDouble());
            this->setLast(retJSON.get("ticker", "" ).get("last", "" ).asDouble());
            this->setLow(retJSON.get("ticker", "" ).get("low", "" ).asDouble());
            this->setVol(retJSON.get("ticker", "" ).get("vol", "" ).asDouble());
            this->setSell(retJSON.get("ticker", "" ).get("sell", "" ).asDouble());
            return SUCCESS;
        }
    }

    return FAIL;
}
Example #14
0
    Expectations::Expectations(Json::Value jsonElement) {
        if (jsonElement.empty()) {
            fIgnoreFailure = kDefaultIgnoreFailure;
        } else {
            Json::Value ignoreFailure = jsonElement[kJsonKey_ExpectedResults_IgnoreFailure];
            if (ignoreFailure.isNull()) {
                fIgnoreFailure = kDefaultIgnoreFailure;
            } else if (!ignoreFailure.isBool()) {
                SkDebugf("found non-boolean json value for key '%s' in element '%s'\n",
                         kJsonKey_ExpectedResults_IgnoreFailure,
                         jsonElement.toStyledString().c_str());
                DEBUGFAIL_SEE_STDERR;
                fIgnoreFailure = kDefaultIgnoreFailure;
            } else {
                fIgnoreFailure = ignoreFailure.asBool();
            }

            Json::Value allowedDigests = jsonElement[kJsonKey_ExpectedResults_AllowedDigests];
            if (allowedDigests.isNull()) {
                // ok, we'll just assume there aren't any AllowedDigests to compare against
            } else if (!allowedDigests.isArray()) {
                SkDebugf("found non-array json value for key '%s' in element '%s'\n",
                         kJsonKey_ExpectedResults_AllowedDigests,
                         jsonElement.toStyledString().c_str());
                DEBUGFAIL_SEE_STDERR;
            } else {
                for (Json::ArrayIndex i=0; i<allowedDigests.size(); i++) {
                    fAllowedResultDigests.push_back(GmResultDigest(allowedDigests[i]));
                }
            }
        }
    }
Example #15
0
    void expectFill (
        std::string const& label,
        Type status,
        Status::Strings messages,
        std::string const& message)
    {
        value_.clear ();
        fillJson (Status (status, messages));

        auto prefix = label + ": ";
        expect (!value_.empty(), prefix + "No value");

        auto error = value_[jss::error];
        expect (!error.empty(), prefix + "No error.");

        auto code = error[jss::code].asInt();
        expect (status == code, prefix + "Wrong status " +
                std::to_string (code) + " != " + std::to_string (status));

        auto m = error[jss::message].asString ();
        expect (m == message, m + " != " + message);

        auto d = error[jss::data];
        size_t s1 = d.size(), s2 = messages.size();
        expect (s1 == s2, prefix + "Data sizes differ " +
                std::to_string (s1) + " != " + std::to_string (s2));
        for (auto i = 0; i < std::min (s1, s2); ++i)
        {
            auto ds = d[i].asString();
            expect (ds == messages[i], prefix + ds + " != " +  messages[i]);
        }
    }
Example #16
0
// TODO: this should be removed once we decide to remove backward compatibility with old log filters
dev::eth::LogFilter toLogFilter(Json::Value const& _json, Interface const& _client)	// commented to avoid warning. Uncomment once in use @ PoC-7.
{
    dev::eth::LogFilter filter;
    if (!_json.isObject() || _json.empty())
        return filter;

    // check only !empty. it should throw exceptions if input params are incorrect
    if (!_json["fromBlock"].empty())
        filter.withEarliest(_client.hashFromNumber(jsToBlockNumber(_json["fromBlock"].asString())));
    if (!_json["toBlock"].empty())
        filter.withLatest(_client.hashFromNumber(jsToBlockNumber(_json["toBlock"].asString())));
    if (!_json["address"].empty())
    {
        if (_json["address"].isArray())
            for (auto i : _json["address"])
                filter.address(jsToAddress(i.asString()));
        else
            filter.address(jsToAddress(_json["address"].asString()));
    }
    if (!_json["topics"].empty())
        for (unsigned i = 0; i < _json["topics"].size(); i++)
        {
            if (_json["topics"][i].isArray())
            {
                for (auto t: _json["topics"][i])
                    if (!t.isNull())
                        filter.topic(i, jsToFixed<32>(t.asString()));
            }
            else if (!_json["topics"][i].isNull()) // if it is anything else then string, it should and will fail
                filter.topic(i, jsToFixed<32>(_json["topics"][i].asString()));
        }
    return filter;
}
Example #17
0
    void test_OK ()
    {
        testcase ("OK");
        fillJson (Status ());
        expect (value_.empty(), "Value for empty status");

        fillJson (0);
        expect (value_.empty(), "Value for 0 status");

        fillJson (Status::OK);
        expect (value_.empty(), "Value for OK status");

        fillJson (tesSUCCESS);
        expect (value_.empty(), "Value for tesSUCCESS");

        fillJson (rpcSUCCESS);
        expect (value_.empty(), "Value for rpcSUCCESS");
    }
void mtsTeleOperationECM::Configure(const Json::Value & jsonConfig)
{
    Json::Value jsonValue;

    // read scale if present
    jsonValue = jsonConfig["scale"];
    if (!jsonValue.empty()) {
        mScale = jsonValue.asDouble();
    }

    // read orientation if present
    jsonValue = jsonConfig["rotation"];
    if (!jsonValue.empty()) {
        vctMatRot3 orientation; // identity by default
        cmnDataJSON<vctMatRot3>::DeSerializeText(orientation, jsonConfig["rotation"]);
        SetRegistrationRotation(orientation);
    }
}
Example #19
0
  std::string GetLiveStreamURL(void)
  {
    std::string stream = "";

    if(!g_current_livestream.empty())
    {
      stream = g_current_livestream["RtspUrl"].asString();
    }
    return stream;
  }
Example #20
0
void ActorCreator::AddComponent( int32_t componentId, Json::Value& setters )
{
    std::auto_ptr<PropertyLoaderBase<Component> > compLoader = mComponentLoaderFactory( componentId );
    if( setters.isArray() && !setters.empty() )
    {
        compLoader->Load( *setters.begin() );
    }

    mComponentLoaders.insert( componentId, static_cast<ComponentLoader_t*>( compLoader.release() ) );
}
Example #21
0
int getParamVal(std::string param, Json::Value const& item, int defvalue) {
  Json::Value nnType = item[param];
  if (!nnType.empty())
  {
    int n = nnType.asInt();
    console->info("{0}={1}", param, n);
    return n;
  }
  else  
    return  defvalue;
  }
Example #22
0
int API::validate_read(Json::Value &data, Json::Value &errors)
{
	if (!data.isMember("type"))
	{
		errors.append(Json::Value("\"data\":\"type\" key missing"));
	}
	else
	{
		if (!data["type"].isString())
		{
			errors.append(Json::Value("\"data\":\"type\" was not a string"));
		}
	}

	if (!data.isMember("ids"))
	{
		errors.append(Json::Value("\"data\":\"ids\" key missing"));
	}

	if (!data.isMember("view"))
	{
		errors.append(Json::Value("\"data\":\"view\" key missing"));
	}
	else if (!data["view"].isString())
	{
		errors.append(Json::Value("\"data\":\"view\" was not a string"));
	}
	else
	{
		if (strcmp(data["view"].asCString(), "list") == 0)
		{
			if (!data["ids"].isNull())
			{
				errors.append(Json::Value("\"data\":\"ids\" was not null for list request"));
			}
		}
		else if (strcmp(data["view"].asCString(), "details") == 0)
		{
			if (!data["ids"].isArray())
			{
				errors.append(Json::Value("\"data\":\"ids\" was not array for details request"));
			}
		}
		else
		{
			errors.append(Json::Value("\"data\":\"view\" had an invalid value"));
		}
	}

	if (errors.empty()) return 0;
	else return -1;
}
Example #23
0
bool CRazberry::GetInitialDevices()
{
	m_updateTime=0;
	std::string sResult;
#ifndef DEBUG_ZWAVE_INT	
	std::string szURL=GetControllerURL();

	bool bret;
	bret=HTTPClient::GET(szURL,sResult);
	if (!bret)
	{
		_log.Log(LOG_ERROR,"Razberry: Error getting data!");
		return 0;
	}
#else
	sResult=readInputTestFile("test.json");
#endif
	Json::Value root;

	Json::Reader jReader;
	bool ret=jReader.parse(sResult,root);
	if (!ret)
	{
		_log.Log(LOG_ERROR,"Razberry: Invalid data received!");
		return 0;
	}

	Json::Value jval;
	jval=root["controller"];
	if (jval.empty()==true)
		return 0;
	m_controllerID=jval["data"]["nodeId"]["value"].asInt();

	for (Json::Value::iterator itt=root.begin(); itt!=root.end(); ++itt)
	{
		const std::string kName=itt.key().asString();
		if (kName=="devices")
		{
			parseDevices(*itt);
		}
		else if (kName=="updateTime")
		{
			std::string supdateTime=(*itt).asString();
			m_updateTime=(time_t)atol(supdateTime.c_str());
		}
	}

	return true;
}
Example #24
0
bool deserialize(const Json::Value& node, bool& b)
{
	if (node.empty())
	{
		std::cout << "Node is empty." << std::endl;
		return false;
	}
	if (!node.isBool())
	{
		std::cout << "Node data type is not boolean." << std::endl;
		return false;
	}
	b = node.asBool();
	return true;
}
Example #25
0
bool deserialize(const Json::Value& node, uint8_t& val)
{
	if (node.empty())
	{
		std::cout << "Node is empty." << std::endl;
		return false;
	}
	if (!node.isNumeric())
	{
		std::cout << "Node data type is not numeric." << std::endl;
		return false;
	}
	val = (uint8_t)node.asInt();
	return true;
}
Example #26
0
StandardTrace::DebugOptions debugOptions(Json::Value const& _json)
{
	StandardTrace::DebugOptions op;
	if (!_json.isObject() || _json.empty())
		return op;
	if (!_json["disableStorage"].empty())
		op.disableStorage = _json["disableStorage"].asBool();
	if (!_json["disableMemory"].empty())
		op.disableMemory = _json["disableMemory"].asBool();
	if (!_json["disableStack"].empty())
		op.disableStack =_json["disableStack"].asBool();
	if (!_json["fullStorage"].empty())
		op.fullStorage = _json["fullStorage"].asBool();
	return op;
}
Example #27
0
bool deserialize(const Json::Value& node, double& d)
{
	if (node.empty())
	{
		std::cout << "Node is empty." << std::endl;
		return false;
	}
	if (!node.isNumeric())
	{
		std::cout << "Node data type is not numeric." << std::endl;
		return false;
	}
	d = node.asDouble();
	return true;
}
Example #28
0
bool deserialize(const Json::Value& node, std::string& str)
{
	if (node.empty())
	{
		std::cout << "Node is empty." << std::endl;
		return false;
	}
    if (!node.isString())
    {
        std::cout << "Node data type is not string." << std::endl;
        return false;
    }
    str = node.asString();
    return true;
}
Example #29
0
bool deserialize(const Json::Value& node, float& f)
{
	if (node.empty())
	{
		std::cout << "Node is empty." << std::endl;
		return false;
	}
	if (!node.isNumeric())
	{
		std::cout << "Node data type is not numeric." << std::endl;
		return false;
	}
	f = node.asFloat();
	return true;
}
Example #30
0
static void streamMetaInformationCb(hbm::streaming::StreamClient& stream, const std::string& method, const Json::Value& params)
{
	if (method == hbm::streaming::META_METHOD_AVAILABLE) {
		std::cout << "The following signal(s) are available : ";
		// simply subscibe all signals that become available.
		hbm::streaming::signalReferences_t signalReferences;
		for (Json::ValueConstIterator iter = params.begin(); iter!= params.end(); ++iter) {
			const Json::Value& element = *iter;
			std::cout << element.asString() << ", ";
			signalReferences.push_back(element.asString());
		}
		std::cout << std::endl << std::endl;

		try {
			stream.subscribe(signalReferences);
			std::cout << "The following " << signalReferences.size() << " signal(s) were subscribed: ";
		} catch(const std::runtime_error& e) {
			std::cerr << "Error '" << e.what() << "' subscribing the following signal(s): ";
		}

		for(hbm::streaming::signalReferences_t::const_iterator iter=signalReferences.begin(); iter!=signalReferences.end(); ++iter) {
			std::cout << "'" << *iter << "' ";
		}
		std::cout << std::endl << std::endl;

	} else if(method==hbm::streaming::META_METHOD_UNAVAILABLE) {
		std::cout << "The following signal(s) are not available anyore: ";

		for (Json::ValueConstIterator iter = params.begin(); iter!= params.end(); ++iter) {
			const Json::Value& element = *iter;
			std::cout << element.asString() << ", ";
		}
		std::cout << std::endl << std::endl;

	} else if(method==hbm::streaming::META_METHOD_ALIVE) {
		// We do ignore this. We are using TCP keep alive in order to detect communication problems.
	} else if(method==hbm::streaming::META_METHOD_FILL) {
		if(params.empty()==false) {
			unsigned int fill = params[0u].asUInt();
			if(fill>25) {
				std::cout << stream.address() << ": ring buffer fill level is " << params[0u].asUInt() << "%" << std::endl;
			}
		}
	} else {
		std::cout << "Meta information: " << method << " " << Json::FastWriter().write(params) << std::endl;
	}
}