bool CardsMoveStruct::tryParse(const Json::Value &arg) {
    if (!arg.isArray() || arg.size() != 8) return false;
    if ((!arg[0].isInt() && !arg[0].isArray()) ||
        !isIntArray(arg, 1, 2) || !isStringArray(arg, 3, 6)) return false;
    if (arg[0].isInt()) {
        int size = arg[0].asInt();
        for (int i = 0; i < size; i++)        
            card_ids.append(Card::S_UNKNOWN_CARD_ID);        
    } else if (!QSanProtocol::Utils::tryParse(arg[0], card_ids))
        return false;
    from_place = (Player::Place)arg[1].asInt();
    to_place = (Player::Place)arg[2].asInt();
    from_player_name = toQString(arg[3]);
    to_player_name = toQString(arg[4]);
    from_pile_name = toQString(arg[5]);
    to_pile_name = toQString(arg[6]);
    reason.tryParse(arg[7]);
    return true;
}
bool QSanProtocol::Countdown::tryParse(Json::Value val) {
    if (!val.isArray() || (val.size() != 2 && val.size() != 3) ||
        !val[0].isString() || val[0].asString() != S_COUNTDOWN_MAGIC)
        return false;
    if (val.size() == 3) {
        if (!Utils::isIntArray(val, 1, 2)) return false;
        m_current = (time_t)val[1].asInt();
        m_max = (time_t)val[2].asInt();
        m_type = S_COUNTDOWN_USE_SPECIFIED;
        return true;
    } else if (val.size() == 2) {
        CountdownType type = (CountdownType)val[1].asInt();
        if (type != S_COUNTDOWN_NO_LIMIT && type != S_COUNTDOWN_USE_DEFAULT)
            return false;
        else m_type = type;
        return true;
    } else
        return false;
}
Exemple #3
0
void PossibleRooms::Load( Json::Value const& possibleRooms )
{
    mRoomIds.clear();
    if (possibleRooms.isArray())
    {
        for (auto& possibleRoom : possibleRooms)
        {
            std::string roomIdStr;
            int32_t chance;
            if (Json::GetStr( possibleRoom["room_id"], roomIdStr ) && Json::GetInt( possibleRoom["weight"], chance ))
            {
                int32_t isBase = 1;
                Json::GetInt( possibleRoom["base"], isBase );
                AddPossibleRoom( AutoId( roomIdStr ), chance, isBase==1 );
            }
        }
    }
    mUniqueRoomIds = MakeRoomeIdsUnique( mRoomIds );
}
bool ParseTeamInfosJson(const std::string& team_infos_json, bool include_invalid_team, std::list<TeamInfo>& team_infos)
{
	Json::Value json;
	Json::Reader reader;
	if (reader.parse(team_infos_json, json) && json.isArray())
	{
		int len = json.size();
		for (int i = 0; i < len; i++)
		{
			TeamInfo info;
			ParseTeamInfoJson(json[i], info);
			if (info.IsValid() || (!info.IsValid() && include_invalid_team))
				team_infos.push_back(info);
		}
		return true;
	}

	return false;
}
Exemple #5
0
bool k8s_api_handler::handle_component(const Json::Value& json, const msg_data* data)
{
	m_error = false;
	if(!json.isNull())
	{
		if(json.isArray())
		{
			for(const auto& version : json)
			{
				if(version.isConvertibleTo(Json::stringValue))
				{
					m_extensions.push_back(version.asString());
				}
				else
				{
					g_logger.log("K8s API handler error: could not extract API versions or extensions from JSON.",
								 sinsp_logger::SEV_ERROR);
					m_error = true;
					return false;
				}
			}
		}
		else if(json.isConvertibleTo(Json::stringValue))
		{
			m_extensions.push_back(json.asString());
		}
		else
		{
			g_logger.log("K8s API handler error: could not extract API versions or extensions from JSON.",
						 sinsp_logger::SEV_ERROR);
			m_error = true;
			return false;
		}
		m_data_received = true;
	}
	else
	{
		g_logger.log("K8s API handler error: json is null.", sinsp_logger::SEV_ERROR);
		m_error = true;
		return false;
	}
	return true;
}
TEST_F(GetComponentsTest, PositiveExecute) {
    compute::json::GetComponents command_json;
    GetComponents* command = new GetComponents("");

    EXPECT_NO_THROW(command_json.set_command(command));

    Json::Value params;
    Json::Value result;

    params["id"] = "";

    EXPECT_NO_THROW(command_json.method(params, result));

    ASSERT_TRUE(result.isArray());
    ASSERT_EQ(result.size(), 10);
    for (std::uint32_t i = 0; i < 10; ++i) {
        ASSERT_EQ(result[i]["component"].asString(), std::to_string(i));
    }
}
Exemple #7
0
bool mesos_state_t::handle_groups(const Json::Value& root, marathon_group::ptr_t to_group, const std::string& framework_id)
{
	Json::Value groups = root["groups"];
	if(!groups.isNull() && groups.isArray())
	{
		for(const auto& group : groups)
		{
			to_group = add_group(group, to_group, framework_id);
			ASSERT(to_group);
			handle_groups(group, to_group, framework_id);
		}
	}
	else
	{
		g_logger.log("No groups found.", sinsp_logger::SEV_WARNING);
		return false;
	}
	return true;
}
Exemple #8
0
void jsonParser::setLaserPulses(Json::Value &document, EM_FIELD *emfield){
  std::string  name1 = _JSON_OBJ_ARRAY_LASER_;
  Json::Value lasers;

  if (setValue(lasers, document, name1.c_str())) {
    if (lasers.isArray()){
      std::string  name2;

      for (unsigned int index = 0; index < lasers.size(); index++){
        Json::Value myLaser = lasers[index];

        name2 = _JSON_BOOL_ENABLED;
        bool enabled = false;
        setBool(&enabled, myLaser, name2.c_str());
        if (enabled){
          laserPulse *pulse1 = new(laserPulse);

          laserPulseBoolFlags flags;

          flags.type = setLaserType(pulse1, myLaser);
          flags.pol = setLaserPolarization(pulse1, myLaser);
          flags.duration = setLaserDurationFWHM(pulse1, myLaser);
          flags.initialPosition = setLaserInitialPosition(pulse1, myLaser);
          flags.a = setLaserAmplitude(pulse1, myLaser);
          flags.waist = setLaserWaist(pulse1, myLaser);
          flags.focusPosition = setLaserFocusPosition(pulse1, myLaser);
          flags.rotation = setLaserRotation(pulse1, myLaser);
          flags.lambda = setLaserLambda(pulse1, myLaser);
          flags.riseTime = setLaserRiseTime(pulse1, myLaser);

          if (checkLaserBoolFlags(flags, pulse1)){
            emfield->addPulse(pulse1);
          }
          else if (isThisJsonMaster){
            std::cout << "warning: laser #" << index << " is incorrectly defined\n";
          }

          delete pulse1;
        }
      }
    }
  }
}
Exemple #9
0
void MapSystem::OnMapLoad( core::MapLoadEvent const& Evt )
{
    ClearMapElements();
    PathVect_t Paths;
    Filesys& FSys = Filesys::Get();
    FSys.GetFileNames( Paths, Evt.mMapName );
    for( PathVect_t::const_iterator i = Paths.begin(), e = Paths.end(); i != e; ++i )
    {
        boost::filesystem::path const& Path = *i;
        PathVect_t LevelPaths;
        FSys.GetFileNames( LevelPaths, Path );
        if( Path.extension().string() != ".json" )
        {
            continue;
        }
        AutoFile JsonFile = FSys.Open( *i );
        if( !JsonFile.get() )
        {
            continue;
        }
        JsonReader Reader( *JsonFile );
        if( !Reader.IsValid() )
        {
            continue;
        }
        Json::Value Root = Reader.GetRoot();
        if( !Root.isArray() )
        {
            continue;
        }
        for( Json::Value::iterator i = Root.begin(), e = Root.end(); i != e; ++i )
        {
            Json::Value& mapElementDesc = *i;
            if( !AddMapElementFromOneTextureDesc( mapElementDesc ) )
            {
                return;
            }
        }
    }
    EventServer<core::MapLoadedEvent>::Get().SendEvent( core::MapLoadedEvent() );

}
Exemple #10
0
	bool war_story::is_defeated_npc(int player_id, int map_id, int npc_id) const
	{
		na::file_system::json_value_map::const_iterator it = _maps.find(map_id);
		if(it!=_maps.end())
		{
			Json::Value progress = get_player_progress(player_id,map_id);
			Json::Value arr = progress[sg::story_def::defeated_list];
			if(!arr.isArray()) return false;
			for (Json::Value::iterator i = arr.begin();i!=arr.end();++i)
			{
				Json::Value defeated_info = *i;
				int _id = defeated_info[sg::army_def::army_id].asInt();
				if(npc_id==_id)
				{
					return true;
				}				
			}
		}
		return false;	
	}
/** 
* Returns Point3 structure for give input json array
*/
Eigen::Vector3f SkeletonRepresentationJSON::jsonGetPoint3(const Json::Value &jsonValue)
{
	Eigen::Vector3f point = Eigen::Vector3f::Zero();

	if (jsonValue.isNull()) return Eigen::Vector3f();

	if (jsonValue.isArray() && jsonValue.size() == 3)
	{
		Json::ValueIterator it = jsonValue.begin();
		point[0] = static_cast<float>((*it).asFloat());
		it++;
		point[1] = static_cast<float>((*it).asFloat());
		it++;
		point[2] = static_cast<float>((*it).asFloat());
	}
	else
		return point;//throw Exception("Error in PoseSet::jsonGetPoint3(): value size = %d", jsonValue.size());

	return point;
}
Exemple #12
0
void Game::renderFromJSON(const Json::Value &msgs) {
  invariant(msgs.isArray(), "json messages must be array");
  invariant(msgs.size() > 0, "messges must be nonempty");
  for (auto msg : msgs) {
    auto type = must_have_idx(msg, "type").asString();
    if (type == "render") {
      handleRenderMessage(msg);
    } else if (type == "start") {
      Renderer::get()->setGameTime(0.f);
      Renderer::get()->setTimeMultiplier(1.f);
    } else if (type == "game_over") {
      // TODO(zack/connor): do more here
      auto winning_team = toID(must_have_idx(msg, "winning_team"));
      LOG(DEBUG) << "Winning team : " << winning_team << '\n';
      running_ = false;
    } else {
      invariant_violation("unknown message type: " + type);
    }
  }
}
TEST_F(GetCollectionTest, PositiveExecute) {
    compute::json::GetCollection command_json;
    GetCollection* command = new GetCollection("TestModuleId", "TestName");

    EXPECT_NO_THROW(command_json.set_command(command));

    Json::Value params;
    Json::Value result;

    params["component"] = "TestModuleId";
    params["name"] = "TestName";

    EXPECT_NO_THROW(command_json.method(params, result));

    ASSERT_TRUE(result.isArray());
    ASSERT_EQ(result.size(), 10);
    for (std::uint32_t i = 0; i < 10; ++i) {
        ASSERT_EQ(result[i]["subcomponent"].asString(), std::to_string(i));
    }
}
Exemple #14
0
bool cMotion::LoadJson(const Json::Value& root)
{
	bool succ = true;
	if (!root[gLoopKey].isNull())
	{
		mLoop = root[gLoopKey].asBool();
	}

	if (!root[gFrameKey].isNull())
	{
		Json::Value frames = root.get(gFrameKey, 0);
		assert(frames.isArray());
		int num_frames = frames.size();

		int data_size = 0;
		if (num_frames > 0)
		{
			int idx0 = 0;
			Json::Value frame_json = frames.get(idx0, 0);
			data_size = frame_json.size();
			mFrames.resize(num_frames, data_size);
		}

		for (int f = 0; f < num_frames; ++f)
		{
			Eigen::VectorXd curr_frame;
			succ = ParseFrameJson(frames.get(f, 0), curr_frame);
			if (succ)
			{
				assert(mFrames.cols() == curr_frame.size());
				mFrames.row(f) = curr_frame;
			}
			else
			{
				mFrames.resize(0, 0);
				break;
			}
		}
	}
	return succ;
}
  void OrthancPeerParameters::FromJson(const Json::Value& peer)
  {
    if (!peer.isArray() ||
        (peer.size() != 1 && peer.size() != 3))
    {
      throw OrthancException(ErrorCode_BadFileFormat);
    }

    std::string url;

    try
    {
      url = peer.get(0u, "").asString();

      if (peer.size() == 1)
      {
        SetUsername("");
        SetPassword("");
      }
      else if (peer.size() == 3)
      {
        SetUsername(peer.get(1u, "").asString());
        SetPassword(peer.get(2u, "").asString());
      }
      else
      {
        throw OrthancException(ErrorCode_BadFileFormat);
      }
    }
    catch (...)
    {
      throw OrthancException(ErrorCode_BadFileFormat);
    }

    if (url.size() != 0 && url[url.size() - 1] != '/')
    {
      url += '/';
    }

    SetUrl(url);
  }
Exemple #16
0
Result FriendsAPI::get(const string &sessionKey, int page, int count, QVector<UID> &list)
{
//    char pageBuf[10];
//    sprintf_s(pageBuf, 10, "%d", page);
    string pageBuf;
    pageBuf = QString::number(page).toStdString();

//    char countBuf[10];
//    sprintf_s(countBuf, 10, "%d", count);
    string countBuf;
    countBuf = QString::number(count).toStdString();

	RequestParam params;
	params.addParam("api_key",		Config::m_apiKey);
    params.addParam("method",		Method::FRIENDS_GET);
	params.addParam("call_id",		Utility::getCallId());
	params.addParam("v",			Config::m_apiVersion);
	params.addParam("session_key",	sessionKey);
	params.addParam("format",		Config::m_resultFormat);
    params.addParam("page",         pageBuf);
    params.addParam("count",        countBuf);
	params.addParam("sig",			Utility::stringToUTF8(Utility::getSignature(params)));

	Response response;
	m_request->syncRequest(Config::m_RESTServerURL, Request::Post, params, &response);

	Json::Value root;
	Json::Reader reader;
    if(reader.parse(response.getRawData(), root, false))
	{
        if(!root.isArray() && !root["error_code"].isNull())
            return root["error_code"].asUInt();

        for(unsigned int i = 0; i < root.size(); i++)
            list.push_back(root[i].asUInt());

        return RESULT_OK;
	}
	else
		return RESULT_JSON_INVALID;
}
Exemple #17
0
Space::Space(Game *game, RefCountedPtr<Galaxy> galaxy, const Json::Value &jsonObj, double at_time)
	: m_starSystemCache(galaxy->NewStarSystemSlaveCache())
	, m_game(game)
	, m_frameIndexValid(false)
	, m_bodyIndexValid(false)
	, m_sbodyIndexValid(false)
	, m_bodyNearFinder(this)
#ifndef NDEBUG
	, m_processingFinalizationQueue(false)
#endif
{
	if (!jsonObj.isMember("space")) throw SavedGameCorruptException();
	Json::Value spaceObj = jsonObj["space"];

	m_starSystem = StarSystem::FromJson(galaxy, spaceObj);

	const SystemPath &path = m_starSystem->GetPath();
	Uint32 _init[5] = { path.systemIndex, Uint32(path.sectorX), Uint32(path.sectorY), Uint32(path.sectorZ), UNIVERSE_SEED };
	Random rand(_init, 5);
	m_background.reset(new Background::Container(Pi::renderer, rand));

	RebuildSystemBodyIndex();

	CityOnPlanet::SetCityModelPatterns(m_starSystem->GetPath());

	m_rootFrame.reset(Frame::FromJson(spaceObj, this, 0, at_time));
	RebuildFrameIndex();

	if (!spaceObj.isMember("bodies")) throw SavedGameCorruptException();
	Json::Value bodyArray = spaceObj["bodies"];
	if (!bodyArray.isArray()) throw SavedGameCorruptException();
	for (Uint32 i = 0; i < bodyArray.size(); i++)
		m_bodies.push_back(Body::FromJson(bodyArray[i], this));
	RebuildBodyIndex();

	Frame::PostUnserializeFixup(m_rootFrame.get(), this);
	for (Body* b : m_bodies)
		b->PostLoadFixup(this);

	GenSectorCache(galaxy, &path);
}
Exemple #18
0
void MemEd::openFile(const char* filename) {
  Json::Value root;

  ifstream ifs;
  ifs.open(filename);
  if (ifs.fail()) {
    throw MedException(string("Open JSON: Fail to open file ") + filename);
  }
  ifs >> root;
  ifs.close();

  storeMutex.lock();
  getStore()->clear();
  if (root.isArray()) {
    loadLegacyJson(root);
  }
  else {
    loadJson(root);
  }
  storeMutex.unlock();
}
BtcAddressBalances BtcJsonLegacy::ListReceivedByAddress(const int32_t &minConf, const bool &includeEmpty, const bool &includeWatchonly)
{
    Json::Value params = Json::Value();
    params.append(minConf);
    params.append(includeEmpty);

    Json::Value result = Json::Value();
    if(!ProcessRpcString(this->modules->btcRpc->SendRpc(CreateJsonQuery(METHOD_LISTRECEIVEDBYADDRESS, params)), result))
        return BtcAddressBalances();     // error

    if(!result.isArray())
        return BtcAddressBalances();

    BtcAddressBalances addressBalances;
    for (Json::Value::ArrayIndex i = 0; i < result.size(); i++)
    {
        addressBalances.push_back(BtcAddressBalancePtr(new BtcAddressBalance(result[i])));
    }

    return addressBalances;
}
Exemple #20
0
thruster_vector parse_thrusters(const Json::Value& arr)
{
    if (!arr.isArray()) {
        throw std::runtime_error("Expected array of thrusters.");
    }

    thruster_vector ts;
    for (unsigned int i = 0; i < arr.size(); i++) {
        Json::Value root = arr[i];
        if (!root.isObject()) {
            throw std::runtime_error("Expected thruster object.");
        }
        PARSE_STRING(name);
        PARSE_VECTOR3(pos);
        PARSE_TWO_DOUBLES(hp, yaw, pitch);
        thruster t { name, pos, yaw, pitch };
        ts.push_back(t);
    }

    return ts;
}
Exemple #21
0
void AsyncScriptExecutor::GetElementIdList(const Json::Value& json_object) {
  LOG(TRACE) << "Entering AsyncScriptExecutor::GetElementIdList";
  if (json_object.isArray()) {
    for (unsigned int i = 0; i < json_object.size(); ++i) {
      GetElementIdList(json_object[i]);
    }
  } else if (json_object.isObject()) {
    if (json_object.isMember(JSON_ELEMENT_PROPERTY_NAME)) {
      // Capture the ID of any element in the arg list, and 
      std::string element_id;
      element_id = json_object[JSON_ELEMENT_PROPERTY_NAME].asString();
      this->element_id_list_.push_back(element_id);
    } else {
      std::vector<std::string> property_names = json_object.getMemberNames();
      std::vector<std::string>::const_iterator it = property_names.begin();
      for (; it < property_names.end(); ++it) {
        GetElementIdList(json_object[*it]);
      }
    }
  }
}
Json::Value                 fetchJsonValue(const std::string &url,
		std::vector<std::string> *extra_headers) {

	HTTPFetchRequest fetchrequest;
	HTTPFetchResult fetchresult;
	fetchrequest.url = url;
	fetchrequest.caller = HTTPFETCH_SYNC;

	if (extra_headers != NULL)
		fetchrequest.extra_headers = *extra_headers;

	httpfetch_sync(fetchrequest,fetchresult);

	if (!fetchresult.succeeded) {
		return Json::Value();
	}
	Json::Value root;
	Json::Reader reader;
	std::istringstream stream(fetchresult.data);

	if (!reader.parse( stream, root ) )
	{
		errorstream << "URL: " << url << std::endl;
		errorstream << "Failed to parse json data " << reader.getFormattedErrorMessages();
		errorstream << "data: \"" << fetchresult.data << "\"" << std::endl;
		return Json::Value();
	}

	if (root.isArray()) {
		return root;
	}
	if ((root["list"].isArray())) {
		return root["list"];
	}
	else {
		return root;
	}

	return Json::Value();
}
Exemple #23
0
Frame *Frame::FromJson(const Json::Value &jsonObj, Space *space, Frame *parent, double at_time)
{
	Frame *f = new Frame();
	f->m_parent = parent;

	if (!jsonObj.isMember("frame")) throw SavedGameCorruptException();
	Json::Value frameObj = jsonObj["frame"];

	if (!frameObj.isMember("flags")) throw SavedGameCorruptException();
	if (!frameObj.isMember("radius")) throw SavedGameCorruptException();
	if (!frameObj.isMember("label")) throw SavedGameCorruptException();
	if (!frameObj.isMember("pos")) throw SavedGameCorruptException();
	if (!frameObj.isMember("ang_speed")) throw SavedGameCorruptException();
	if (!frameObj.isMember("init_orient")) throw SavedGameCorruptException();
	if (!frameObj.isMember("index_for_system_body")) throw SavedGameCorruptException();
	if (!frameObj.isMember("index_for_astro_body")) throw SavedGameCorruptException();

	f->m_flags = frameObj["flags"].asInt();
	f->m_radius = StrToDouble(frameObj["radius"].asString());
	f->m_label = frameObj["label"].asString();
	JsonToVector(&(f->m_pos), frameObj, "pos");
	f->m_angSpeed = StrToDouble(frameObj["ang_speed"].asString());
	matrix3x3d orient;
	JsonToMatrix(&orient, frameObj, "init_orient");
	f->SetInitialOrient(orient, at_time);
	f->m_sbody = space->GetSystemBodyByIndex(frameObj["index_for_system_body"].asUInt());
	f->m_astroBodyIndex = frameObj["index_for_astro_body"].asUInt();
	f->m_vel = vector3d(0.0); // m_vel is set to zero.

	if (!frameObj.isMember("child_frames")) throw SavedGameCorruptException();
	Json::Value childFrameArray = frameObj["child_frames"];
	if (!childFrameArray.isArray()) throw SavedGameCorruptException();
	for (unsigned int i = 0; i < childFrameArray.size(); ++i) {
		f->m_children.push_back(FromJson(childFrameArray[i], space, f, at_time));
	}
	SfxManager::FromJson(frameObj, f);

	f->ClearMovement();
	return f;
}
bool ShopItemInfoFromServer::parseShopBuyInfoFromServer()
{
    m_mapBuyShopInfo.clear();
    const char* pMessage = m_strShopBuyList.c_str();

    CCLOG("download step m_strShopBuyList %s",pMessage);
    if (pMessage == NULL || pMessage == "" || pMessage == "error")
    {
        return false;
    }

    Json::Value jsonValue;
    if (!parseJsonStr(pMessage, jsonValue)) 
    {
        CCLOGERROR("UpdateInfoFromServer Error: %s",pMessage);
        return false;
    }

    bool isArray = jsonValue.isArray();
    if (isArray)
    {
        unsigned int arraySize = jsonValue.size();
        for (int i = 0; i < arraySize; i++)
        {
            const Json::Value jProduct_id = jsonValue[i]["id"];
            const Json::Value jAmount = jsonValue[i]["count"];

            if (false == jProduct_id.isNull() &&
                false == jAmount.isNull())
            {
                int id = atoi(jProduct_id.asCString());
                int amount = atoi(jAmount.asCString());

                m_mapBuyShopInfo.insert(std::make_pair(id, amount));
            }
        }
    }

    return true;
}
Exemple #25
0
//解释搜索结果以生成搜索目录树
void CSearchDlg::ParserSearchTree(std::string searchResp)
{
	try
	{
		Json::Reader reader;
		Json::Value root;
		if(!reader.parse(searchResp,root,false))
		{
			return ;
		}
		if(!root.isArray())
		{
			return;
		}

		std::string RoomID,RoomName,UserCount;		
		int rootsize = root.size();
		for(int i=0;i<rootsize;++i)
		{
			hallNode* newNode = new hallNode;
			
			RoomID = root[i][SEARCH_RESULTS_ROOMITEM_ROOMID].asString();
			RoomName = root[i][SEARCH_RESULTS_ROOMITEM_ROOMNAME].asString();			
			UserCount = root[i][SEARCH_RESULTS_ROOMITEM_USERCOUNT].asString();

			newNode->m_RoomID = atoi(RoomID.c_str());			
			newNode->m_Name.Format(_T("%s(%s)"),common::utility::stringhelper::UTF8ToUnicode(RoomName).c_str(),common::utility::stringhelper::UTF8ToUnicode(RoomID).c_str());	
			newNode->m_PeopleNum.Format(_T("%s人"),common::utility::stringhelper::UTF8ToUnicode(UserCount).c_str());			
			newNode->m_pngNormalExpand = m_pngNormal;
			newNode->m_pngSelectContract = m_pngNormal;
			m_SearchNode.push_back(newNode);
		}
	}
	catch (...)
	{
		return;
	}
	
	
}
Exemple #26
0
std::vector<ProbeAPI::CountryInfo> ProbeAPI::ParseCountries(const std::string& sJson)
{
	Json::Reader reader;
	Json::Value root;
	const bool parsedOK = reader.parse(sJson, root);
	if (!parsedOK)
	{
		throw PException(eRetCode::ApiParsingFail) << "Failed parsing json: " << reader.getFormattedErrorMessages();
	}

	// {
	//   "GetCountriesResult": [
	//     {
	//       "CountryCode": "AF",
	//       "CountryFlag": "http://speedcheckerapi.blob.core.windows.net/bsc-img-country-logos/af.png",
	//       "CountryName": "Afghanistan",
	//       "ProbesCount": 5
	//     },
	//     {
	//       "CountryCode": "AL",
	//       "CountryFlag": "http://speedcheckerapi.blob.core.windows.net/bsc-img-country-logos/al.png",
	//       "CountryName": "Albania",
	//       "ProbesCount": 14
	//     },

	const Json::Value items = root["GetCountriesResult"];

	assert(items.isArray());
	const Json::ArrayIndex n = items.size();
	std::vector<CountryInfo> res;
	res.reserve(n);

	for (Json::ArrayIndex index = 0; index < n; ++index)
	{
		const Json::Value item = items[index];
		res.emplace_back(item);		// create CountryInfo()
	}

	return res;
}
Exemple #27
0
std::vector<ServerListSpec> getOnline()
{
    //不要每次都获取
    static std::vector<ServerListSpec> serverlist;
    if (serverlist.size() > 0) {
        return serverlist;
    }
    
    
	Json::Value root = fetchJsonValue((g_settings->get("serverlist_url")+"/list").c_str(),0);

	if (root.isArray()) {
		for (unsigned int i = 0; i < root.size(); i++)
		{
			if (root[i].isObject()) {
				serverlist.push_back(root[i]);
			}
		}
	}

	return serverlist;
}
Exemple #28
0
    DimTypeList schemaToDims(const Json::Value& json)
    {
        DimTypeList output;

        // XYZ might be natively stored as integral values, typically when the
        // disk-storage for Entwine is scaled/offset.  Since we're abstracting
        // this out, always ask for XYZ as doubles.
        auto isXyz([](Dimension::Id id)
        {
            return
                id == Dimension::Id::X ||
                id == Dimension::Id::Y ||
                id == Dimension::Id::Z;
        });

        if (!json.isNull() && json.isArray())
        {
            for (const auto& jsonDim : json)
            {
                const Dimension::Id id(
                        Dimension::id(jsonDim["name"].asString()));

                const int baseType(
                        Utils::toNative(
                            Dimension::fromName(jsonDim["type"].asString())));

                const int size(jsonDim["size"].asUInt64());

                const Dimension::Type type(
                        isXyz(id) ?
                            Dimension::Type::Double :
                            static_cast<Dimension::Type>(baseType | size));

                output.emplace_back(id, type);
            }
        }

        return output;
    }
BtcTransactions BtcJsonLegacy::ListTransactions(const std::string &account, const int32_t &count, const int32_t &from, const bool &includeWatchonly)
{
    Json::Value params = Json::Value();
    params.append(account);
    params.append(count);
    params.append(from);

    Json::Value result = Json::Value();
    if(!ProcessRpcString(this->modules->btcRpc->SendRpc(CreateJsonQuery(METHOD_LISTTRANSACTIONS, params)), result))
        return BtcTransactions();     // error

    if(!result.isArray())
        return BtcTransactions();

    BtcTransactions transactions;
    for (Json::Value::ArrayIndex i = 0; i < result.size(); i++)
    {
        transactions.push_back(BtcTransactionPtr(new BtcTransaction(result[i])));
    }

    return transactions;
}
Exemple #30
0
drag_plane_vector parse_drag_planes(const Json::Value& arr)
{
    if (!arr.isArray()) {
        throw std::runtime_error("Expected array of drag planes.");
    }

    drag_plane_vector dps;
    for (unsigned int i = 0; i < arr.size(); i++) {
        Json::Value root = arr[i];
        if (!root.isObject()) {
            throw std::runtime_error("Expected drag plane object.");
        }
        PARSE_VECTOR3(pos);
        PARSE_VECTOR3(normal);
        PARSE_DOUBLE(cD);
        PARSE_DOUBLE(area);
        drag_plane dp { pos, normal, cD, area };
        dps.push_back(dp);
    }

    return dps;
}