예제 #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);
}
void Enum_Drectory(void *cmd)
{
	Json::FastWriter fast_writer;
	Json::Value root;
	string Base64Result;
	cmdinfo *pci=(cmdinfo*)cmd;
	if (pci->cmd_content.compare("/")==0)
	{
		string utf8_drive;
		//Msg("获取驱动器\r\n");
		GetDirverInfo(&root);

		ANSIToUTF8(fast_writer.write(root).c_str(),&utf8_drive);
		Base64Encode(reinterpret_cast<const unsigned char*>(utf8_drive.c_str()),utf8_drive.length(),Base64Result);
		Replace_plus(Base64Result);
		SubmitResult(pci,Base64Result.c_str());
		Base64Result.erase();
		utf8_drive.erase();
		root.clear();
	}
	else
	{
		//Msg("获取文件夹列表\r\n");
		Enum_Current_Drectory((char *)pci->cmd_content.c_str(),&root);
		Base64Encode(reinterpret_cast<const unsigned char*>(fast_writer.write(root).c_str()),fast_writer.write(root).length(),Base64Result);
		Replace_plus(Base64Result);
		SubmitResult(pci,Base64Result.c_str());
		Base64Result.erase();
		root.clear();
	}
}
예제 #3
0
int main(int argc, char** argv)
{
  if (argc!=3)
  {
    printf("usage: c.out <gateway server> <gateway server port>");
    return 1;
  }
  try
  {
    cout<<"client test"<<endl;
    Json::Value root;
    root["req_type"] = "put";
    root["req_args"]["key"] = "ly232";
    root["req_args"]["value"] = "Lin Yang";
    root["sync"] = "true"; //tell server to ensure consistency before ack
                           //alternatively, if this field is not specified,
                           //server will be eventually consistent (i.e. default false)
    Json::StyledWriter writer;
    std::string outputConfig = writer.write(root);

    client clt(argv[1], atoi(argv[2]));
    std::string reply = clt.sendstring(outputConfig.c_str());
    std::cout<<"reply="<<reply<<std::endl;

    root.clear();
    root["req_type"] = "get";
    root["req_args"]["key"] = "ly232";
    outputConfig = writer.write(root);
    reply = clt.sendstring(outputConfig.c_str());
    std::cout<<"reply="<<reply<<std::endl;

    root.clear();
    root["req_type"] = "delete";
    root["req_args"]["key"] = "ly232";
    outputConfig = writer.write(root);
    reply = clt.sendstring(outputConfig.c_str());
    std::cout<<"reply="<<reply<<std::endl;

    root.clear();
    root["req_type"] = "get";
    root["req_args"]["key"] = "ly232";
    outputConfig = writer.write(root);
    reply = clt.sendstring(outputConfig.c_str());
    std::cout<<"reply="<<reply<<std::endl;

    root.clear();
    root["req_type"] = "exit"; 
    outputConfig = writer.write(root);
    reply = clt.sendstring(outputConfig.c_str());
    std::cout<<"reply="<<reply<<std::endl;

  }
  catch(int e)
  {
    cout<<"error code = "<<e<<endl;
  }
  return 0;
}
예제 #4
0
/**
 * @return json string
 * eg:
 *
 * {
 * 		"userNum":3,
 * 		"Users":
 * 		[
 * 			{
 * 				"m_strUserName":"******",
 * 				"m_strUserPhone":"15237872320",
 * 				"m_strUserDepartment":"software college"
 * 			},
 * 			{
 * 				"m_strUserName":"******",
 * 				"m_strUserPhone":"15237872320",
 * 				"m_strUserDepartment":"software college"
 * 			}
 * 		]
 * }
 *
 */
string DBConn::Query_all_mysql(string sql, string ObjectName) {
    Json::Value root;
    Json::Value arrayObj;
    Json::Value item;
    int t = mysql_real_query(&mysql, sql.c_str(),
                             (unsigned int) strlen(sql.c_str()));
    if (t == -1) {
        cout << "query failed:%s\n" << mysql_errno(&mysql)
             << mysql_error(&mysql) << endl;
    } else {
        res = mysql_store_result(&mysql); //返回查询的全部结果集
        //获取表的列数
        //int numb=mysql_num_fields(res);
        //printf("name: %s   count: %d\n", namebuf[i], rows);

        //获取并输出表头
        field = mysql_fetch_fields(res);
        //int length=mysql_fetch_lengths(res);
        int length = mysql_num_rows(res);
        int userNum = 0;
        int i = 1;
        while (row = mysql_fetch_row(res)) {	//mysql_fetch_row取结果集的下一行
            for (t = 0; t < mysql_num_fields(res); t++) {	//结果集的列的数量
                item[field[t].name] = Json::Value(row[t]);
            }
            arrayObj.append(item);
            item.clear();
            userNum++;
        }
        root["Num"] = Json::Value(userNum);
        root[ObjectName] = arrayObj;
        return root.toStyledString();
    }
}
예제 #5
0
Options PipelineReaderJSON::extractOptions(Json::Value& node)
{
    Options options;

    for (const std::string& name : node.getMemberNames())
    {
        if (node[name].isString())
            options.add(name, node[name].asString());
        else if (node[name].isInt())
            options.add(name, node[name].asInt64());
        else if (node[name].isUInt())
            options.add(name, node[name].asUInt64());
        else if (node[name].isDouble())
            options.add(name, node[name].asDouble());
        else if (node[name].isBool())
            options.add(name, node[name].asBool());
        else if (node[name].isNull())
            options.add(name, "");
        else
            throw pdal_error("JSON pipeline: Value of stage option '" +
                name + "' cannot be converted.");
    }
    node.clear();
    return options;
}
bool GetValueFromDapiResponse(Json::Value& value, const DAPIResponse& response)
{
	bool bSuccess = true;
	
	// Conditionals to avoid unecessary assert
	if(value.type() == Json::nullValue ||
	   value.type() == Json::arrayValue ||
	   value.type() == Json::objectValue) {
		value.clear();
	}
	
	string valueString;
	DapiMgr::GetStringFromDapiResponse(valueString, response);
	uint64_t length = valueString.length();
	const char* c = valueString.c_str();
	
	if (length != 0)
	{
		Json::Reader reader;
		bool parsingSuccessful = reader.parse(c, c + length, value);
		if (!parsingSuccessful)
		{
			std::cout << "Failed to parse configuration\n" << reader.getFormattedErrorMessages();
			bSuccess = false;
		}
	}
	return bSuccess;
}
예제 #7
0
  void SliceOrdering::Format(Json::Value& result) const
  {
    result = Json::objectValue;
    result["Type"] = (isVolume_ ? "Volume" : "Sequence");
    
    Json::Value tmp = Json::arrayValue;
    for (size_t i = 0; i < GetInstancesCount(); i++)
    {
      tmp.append(GetBasePath(ResourceType_Instance, GetInstanceId(i)) + "/file");
    }

    result["Dicom"] = tmp;

    Json::Value slicesShort = Json::arrayValue;

    tmp.clear();
    for (size_t i = 0; i < GetInstancesCount(); i++)
    {
      std::string base = GetBasePath(ResourceType_Instance, GetInstanceId(i));
      for (size_t j = 0; j < GetFramesCount(i); j++)
      {
        tmp.append(base + "/frames/" + boost::lexical_cast<std::string>(j));
      }

      Json::Value tmp2 = Json::arrayValue;
      tmp2.append(GetInstanceId(i));
      tmp2.append(0);
      tmp2.append(GetFramesCount(i));
      
      slicesShort.append(tmp2);
    }

    result["Slices"] = tmp;
    result["SlicesShort"] = slicesShort;
  }
예제 #8
0
void Settings::ToJson(Json::Value& o_json)
{
    o_json.clear();
	o_json["defaults"] = Json::Value();
	
	o_json["SplitTunnel"] = Settings::SplitTunnel() ? TRUE : FALSE;
	o_json["defaults"]["SplitTunnel"] = SPLIT_TUNNEL_DEFAULT;
	
	o_json["VPN"] = (Settings::Transport() == TRANSPORT_VPN) ? TRUE : FALSE;
	o_json["defaults"]["VPN"] = FALSE;
	
	o_json["LocalHttpProxyPort"] = Settings::LocalHttpProxyPort();
	o_json["defaults"]["LocalHttpProxyPort"] = NULL_PORT;
	o_json["LocalSocksProxyPort"] = Settings::LocalSocksProxyPort();
	o_json["defaults"]["LocalSocksProxyPort"] = NULL_PORT;
	
	o_json["SkipUpstreamProxy"] = Settings::SkipUpstreamProxy() ? TRUE : FALSE;;
	o_json["defaults"]["SkipUpstreamProxy"] = SKIP_UPSTREAM_PROXY_DEFAULT;
	o_json["UpstreamProxyHostname"] = Settings::UpstreamProxyHostname();
	o_json["defaults"]["UpstreamProxyHostname"] = UPSTREAM_PROXY_HOSTNAME_DEFAULT;
	o_json["UpstreamProxyPort"] = Settings::UpstreamProxyPort();
	o_json["defaults"]["UpstreamProxyPort"] = NULL_PORT;
	
	o_json["EgressRegion"] = Settings::EgressRegion();
	o_json["defaults"]["EgressRegion"] = EGRESS_REGION_DEFAULT;
	
	o_json["SystrayMinimize"] = Settings::SystrayMinimize() ? TRUE : FALSE;;
	o_json["defaults"]["SystrayMinimize"] = SYSTRAY_MINIMIZE_DEFAULT;
}
예제 #9
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]);
        }
    }
예제 #10
0
Json::Value WebAPI::GetFriendList(std::string accessToken) {
    Debug("[DEBUG] Trying to get friend list");

    Json::Value result;
    Json::Reader reader;

    std::string url = "https://api.steampowered.com/ISteamUserOAuth/GetFriendList/v0001";
    url = url + "?access_token=" + accessToken + "&relationship=friend,requestrecipient";

    // Read the friend list of the bot
    WriteDataInfo pageInfo = this->GetPage(this->webAPIClient, url, USER_AGENT_APP, nullptr);

    // Valid result?
    if (!pageInfo.error.empty()) {
        result["success"] = false;
        result["error"] = "Failed to receive friend list. Error: '" + pageInfo.error + "'";
        return result;
    }

    result.clear();
    if (!reader.parse(pageInfo.content, result)) {
        result["success"] = false;
        result["error"] = "Failed to parse friend list. Error: '" + reader.getFormattedErrorMessages() + "'";
        return result;
    }

    Debug("[DEBUG] Got friend list");
    result["success"] = true;
    return result;
}
예제 #11
0
파일: File.cpp 프로젝트: onze/Steel
    bool File::readInto(Json::Value &root, bool keepComments) const
    {
        if(!exists())
        {
            Ogre::String msg = "could not open :" + fullPath() + ": file not found.";

            if(Debug::isInit)
                Debug::error(STEEL_METH_INTRO, msg).endl();
            else
                std::cerr << STEEL_METH_INTRO.c_str() << msg.c_str() << std::endl;

            return false;
        }

        Json::Reader reader;
        Ogre::String content = read(false);
        root.clear();

        if(!reader.parse(content, root, keepComments))
        {
            Ogre::String msg = "Could not parse content:" + reader.getFormatedErrorMessages() + "\non :" + content;

            if(Debug::isInit)
                Debug::error(STEEL_METH_INTRO, msg).endl();
            else
                std::cerr << STEEL_METH_INTRO.c_str() << msg.c_str() << std::endl;

            return false;
        }

        return true;
    }
예제 #12
0
파일: jsontest.cpp 프로젝트: bymzy/forfun
int main(int argv,char *argc[])
{
    int err = 0 ;
    ifstream s;
    ofstream out;
    Json::Value root;
    do {
        if ( 3 != argv ) {
            cout<<"please check you argument"<<endl;
            Usage();
            err = 1; 
            break;
        }
        s.open(argc[1],ifstream::in);
        s>>root;
        Parse(root);
    } while (0);
    
    root.clear();

    root["firstname"]="zhengying";
    root["lastname"]="ming";
    root["age"]=22;
    root["path"]=Json::Value();
    out.open(argc[2],ofstream::out);
    out<<root.toStyledString();

    out.close();
    s.close();
    return err;
}
예제 #13
0
void leave_test_case(int line, const char* file, const char* test_name)
{
	executing = false;

	for (auto &id : test_data.getMemberNames())
		test_case[id] = test_data[id];

	test_data.clear();

	test_case["result"] = current_result;
	test_case["result_ex"] = current_result_ex;
	test_case["line_exit"] = line;

	data["cases"].append(test_case);

	test_case.clear();
}
예제 #14
0
파일: test.cpp 프로젝트: jasp00/signTextJS
static void protocol_test(FILE *bei, FILE *beo) {
	Json::Value req;
	Json::Value res;

	req["command"] = "initialize";
	req["debug"] = true;

	write_request(req, bei);
	read_response(res, beo);

	if (res["version"].asString() != WEB_EXTENSION_VERSION) {
		std::cerr << "Version mismatch" << std::endl;
		exit(EXIT_FAILURE);
	}

	req.clear();
	res.clear();

	req["command"] = "get_certificates";

	write_request(req, bei);
	read_response(res, beo);

	if (!res["certificates"][0].isMember("der")) {
		std::cerr << "Failed to get certificate" << std::endl;
		exit(EXIT_FAILURE);
	}
	std::string der = res["certificates"][0]["der"].asString();

	req.clear();
	res.clear();

	req["command"] = "sign_data";
	req["certificate"] = der;
	req["data"] = "SGVsbG8sIHdvcmxkIQo=";

	write_request(req, bei);
	read_response(res, beo);

	static const char ERROR[] = "error:";
	if (!res["result"].asString().compare(0, strlen(ERROR), ERROR)) {
		std::cerr << "Signature error" << std::endl;
		exit(EXIT_FAILURE);
	}
	std::cout << "Test passed" << std::endl;
}
예제 #15
0
    void create_request(Json::Value &request, const string &method, int id = 1) {
        request.clear();

        request["jsonrpc"] = "2.0";
        request["id"] = id;
        request["method"] = method;

    }
예제 #16
0
int CRuleItem::writeJson(Json::Value &root)
{
    Json::Value item;
    Json::Value childNode;
    Json::Value parentNode;
    for(unsigned int i = 0; i < m_obtainCode.size(); i++)
    {
        CObtainCode unitObtainCode = m_obtainCode[i];
        unitObtainCode.writeJson(item);
        childNode.append(item);
        item.clear();
    }
    parentNode["obtainCode"] = childNode;
    root[m_childRuleName]  = parentNode;
    childNode.clear();
    return 0;
}
예제 #17
0
void leave_test_step(int line, const char* file, const char* test_name)
{
	executing = false;


	for (auto &id : test_data.getMemberNames())
		test_step[id] = test_data[id];

	test_data.clear();


	test_step["result"] = current_result;
	test_step["result_ex"] = current_result_ex;
	test_step["line_exit"] = line;

	test_sequence["steps"] = test_step;

	test_step.clear();
}
예제 #18
0
void leave_test_sequence(int line, const char* file, const char* test_name)
{
	test_sequence["result"] 	= current_result;
	test_sequence["result_ex"]	= current_result_ex;
	test_sequence["line_exit"]	= line;

	data["sequences"].append(test_sequence);
	test_sequence.clear();

}
예제 #19
0
  bool RestApiGetCall::ParseJsonRequest(Json::Value& result) const
  {
    result.clear();

    for (IHttpHandler::Arguments::const_iterator 
           it = getArguments_.begin(); it != getArguments_.end(); ++it)
    {
      result[it->first] = it->second;
    }

    return true;
  }
Json::Value SpecificationWriter::toJsonValue            (const vector<Procedure> &procedures)
{
    Json::Value result;
    Json::Value row;
    for(unsigned int i=0; i < procedures.size(); i++)
    {
        procedureToJsonValue(procedures.at(i), row);
        result[i] = row;
        row.clear();
    }
    return result;
}
예제 #21
0
int CRuleMatchInfo::writeJson(Json::Value &root)
{
    Json::Value item;
    item["matchFlag"]      = m_matchFlag;
    item["urlInclude"]     = m_urlInclude;
    item["urlNotInclude"]  = m_urlNotInclude;
    item["codeInclude"]    = m_codeInclude;
    item["codeNotInclude"] = m_codeNotInclude;
    root["ruleMatchInfo"]  = item;
    item.clear();
    return 0;
}
예제 #22
0
파일: locale.cpp 프로젝트: d07RiV/SNOParser
void ListStrings(json::Value& value, json::Value& data) {
  for (auto& kv : value.getMap()) {
    if (kv.second.type() == json::Value::tObject) {
      for (auto& skv : kv.second.getMap()) {
        data["stringlist"][kv.first][skv.first]["text"] = skv.first;
      }
    } else {
      data["stringlist"]["Global"][kv.first]["text"] = kv.first;
    }
  }
  value.clear();
}
bool		MasterModuleRequestHandler::operator()(Json::Value const &request, Json::Value &response) {
  static JsonValidator	requestValidator = {{"cmd", &JsonValidator::isNonEmptyString}};
  bool			ret = requestValidator(request);

  response.clear();
  if (ret) {
    ret = this->commandHandler(request, response);
  }
  if (ret) {
    this->returnCode(response, Ok);
  }
  return (ret);
}
예제 #24
0
CTrustListError CFileStorage::insert(BaseUid const& uid)
{
   LOG4CPLUS_TRACE_METHOD(msLogger, __PRETTY_FUNCTION__);
   // if (!isReady())
   //    return CTrustListError(CTrustListError::ERROR_STORAGE, gsModuleName, "file is not ready");

   Json::Value root;
   if (!reopen(ios::in) || !read(file, root))
   {
      //return CTrustListError(CTrustListError::ERROR_STORAGE, gsModuleName, "unable to parse file");
      LOG4CPLUS_WARN(msLogger, "unable to parse file");
   }

   std::set<BaseUid> uids;
   Json::Value trusted = root[gsTrustedTag];
   
   if (!trusted.isNull())
   {
      for (size_t i = 0; i < trusted.size(); ++i)
      {
         uids.insert(trusted[i].asString());
      }
   }

   uids.insert(uid);

   
   // if (trusted.isNull())
   // {
   //    trusted = Json::Value();
   // }
   // else
   // {
      trusted.clear();   
   // }
   
   for (std::set<BaseUid>::const_iterator it = uids.begin(); it != uids.end(); ++it)
   {
      trusted.append(it->value());
   }

   root[gsTrustedTag] = trusted;

   if (!reopen(ios::in | ios::out | ios::trunc))
      return CTrustListError(CTrustListError::ERROR_STORAGE, gsModuleName, "unable to reopen file");
   
   if (!write(file, root))
      return CTrustListError(CTrustListError::ERROR_STORAGE, gsModuleName, "unable to write file");

   return CTrustListError::NoTLError(gsModuleName);;
}
 Json::Value SpecificationWriter::toJsonValue(procedurelist_t& procedures)
 {
     procedurelist_t::iterator it;
     Json::Value result;
     Json::Value row;
     int i=0;
     for(it = procedures.begin(); it != procedures.end(); it++)
     {
         Procedure* proc = it->second;
         procedureToJsonValue(proc, row);
         result[i] = row;
         i++;
         row.clear();
     }
     return result;
 }
예제 #26
0
bool JsonTransf::StringToJsonCpp(Json::Value& jsonValue, const char* sJsonStr)
{
	if(!sJsonStr)
		return false; 

	Json::Reader reader(Json::Features::strictMode()); 
	try
	{
		jsonValue.clear(); 
		return reader.parse(sJsonStr, jsonValue); 
	}
	catch(...)
	{
		return false; 		
	}
}
예제 #27
0
        /**
         * \brief Test batched call.
         */
        void testBatchedCall()
        {
          const std::string str = "[{\"id\":1, \"jsonrpc\":\"2.0\", \"method\":\"print\"}, {\"id\":2, \"jsonrpc\":\"2.0\", \"method\":\"system.describe\"}]";
          const std::string str2 = "[{\"id\":1, \"jsonrpc\":\"2.0\", \"method\":\"print\"}, {\"jsonrpc\":\"2.0\", \"method\":\"notify\"}]";
          TestRpc obj;
          Json::Value response;

          m_handler->AddMethod(new Json::Rpc::RpcMethod<TestRpc>(obj, &TestRpc::Print, std::string("print")));
          m_handler->AddMethod(new Json::Rpc::RpcMethod<TestRpc>(obj, &TestRpc::Notify, std::string("notify")));

          CPPUNIT_ASSERT(m_handler->Process(str, response) == true);
          CPPUNIT_ASSERT(response.size() == 2);

          response.clear();
          CPPUNIT_ASSERT(m_handler->Process(str2, response) == true);
          CPPUNIT_ASSERT(response.size() == 1);
        }
예제 #28
0
SError SData::LoadChannels()
{
  XBMC->Log(LOG_DEBUG, "%s", __FUNCTION__);

  SError ret;
  Json::Value parsed;
  int iGenre = 10;
  uint32_t iCurrentPage = 1;
  uint32_t iMaxPages = 1;

  //TODO merge with LoadData() when multiple PVR clients are properly supported
  //TODO replace with auth check
  if (!IsInitialized() && SERROR_OK != (ret = Initialize()))
    return ret;

  if (!SAPI::GetAllChannels(m_identity, parsed) || !ParseChannels(parsed)) {
    XBMC->Log(LOG_ERROR, "%s: GetAllChannels failed", __FUNCTION__);
    return SERROR_LOAD_CHANNELS;
  }

  parsed.clear();

  while (iCurrentPage <= iMaxPages) {
    XBMC->Log(LOG_DEBUG, "%s: iCurrentPage: %d", __FUNCTION__, iCurrentPage);

    if (!SAPI::GetOrderedList(iGenre, iCurrentPage, m_identity, parsed) || !ParseChannels(parsed)) {
      XBMC->Log(LOG_ERROR, "%s: GetOrderedList failed", __FUNCTION__);
      return SERROR_LOAD_CHANNELS;
    }

    if (iCurrentPage == 1) {
      int iTotalItems = Utils::GetIntFromJsonValue(parsed["js"]["total_items"]);
      int iMaxPageItems = Utils::GetIntFromJsonValue(parsed["js"]["max_page_items"]);

      if (iTotalItems > 0 && iMaxPageItems > 0)
        iMaxPages = static_cast<uint32_t>(ceil((double)iTotalItems / iMaxPageItems));
      
      XBMC->Log(LOG_DEBUG, "%s: iTotalItems: %d | iMaxPageItems: %d | iMaxPages: %d",
        __FUNCTION__, iTotalItems, iMaxPageItems, iMaxPages);
    }

    iCurrentPage++;
  }

  return SERROR_OK;
}
예제 #29
0
static bool receiveControlMessage(Json::Value& root, MessageProtocol& line)
{
	root.clear();
	Message recvd;
	line.readMessage(recvd);

	uint32_t incomingMessageType = recvd.get<uint32_t>(0);
	REQUIRE(incomingMessageType == (int)goldmine::MessageType::Control);

	auto json = recvd.get<std::string>(1);
	Json::Reader reader;
	bool parseOk = reader.parse(json, root);
	if(!parseOk)
		return false;

	return true;
}
예제 #30
0
Json::Value WebAPI::LoginWebAPI(std::string accessToken) {
    Debug("[DEBUG] Trying to login to the web API");

    Json::Value result;
    Json::Reader reader;

    // Login to get UMQID
    WriteDataInfo pageInfo = this->GetPage(this->webAPIClient, "https://api.steampowered.com/ISteamWebUserPresenceOAuth/Logon/v0001",
                                           USER_AGENT_APP, "access_token=%s", accessToken.c_str());

    // Valid result?
    if (!pageInfo.error.empty()) {
        result["success"] = false;
        result["error"] = "Failed to receive UMQID. Error: '" + pageInfo.error + "'";
        return result;
    }

    result.clear();
    if (!reader.parse(pageInfo.content, result)) {
        result["success"] = false;
        result["error"] = "Failed to parse UMQID. Error: '" + reader.getFormattedErrorMessages() + "'";
        return result;
    }

    std::string error = result.get("error", "").asString();
    if (error != "OK") {
        result["success"] = false;
        result["error"] = "Failed to get UMQID. Error: '" + error + "'";
        return result;
    }

    // Parse UMQID
    std::string umqid = result.get("umqid", "").asString();
    if (umqid.empty()) {
        std::string json = result.toStyledString();

        result["success"] = false;
        result["error"] = "Got empty UMQID. JSON: '" + json + "'";
        return result;
    }

    Debug("[DEBUG] Got UMQID");
    result["success"] = true;
    return result;
}