Exemplo n.º 1
0
void JsonParser::parseCamera(Json::Value &root){
    LOG_DEBUG("Parsing Camera.");
    bool foundCamera = false;    
        // Options
    for( Json::ValueIterator itr = root.begin() ; itr != root.end() ; itr++ ) {
        std::string key = itr.key().asString();
        if (key == "renderCam") {
            foundCamera = true;
            
                // read all standard data
            double r_fieldOfView = getDoubleAttr("fov", *itr);
            Transform r_transform = getTransformAttr("transforms", *itr);

                // TODO: check for any ones we've skipped and warn the user
            
                // TODO: handle errors gracefully
            
                // apply read data
            (*renderEnv->globals)[FieldOfView] = r_fieldOfView;
            cameraTransform = new Transform(r_transform);

            LOG_DEBUG("Done parsing Camera.\n");
            break;
        }
    }
    if (!foundCamera) {
        LOG_WARNING("No render camera found in file " << filename << ".");
    }
}
Exemplo n.º 2
0
void JsonArchive::DumpJsonTree(Json::Value* root, int depth)
{
	if (root == NULL)
	{
		root = &m_Root;
	}

	depth += 1;
	printf( " {type=[%d], size=%d}", root->type(), root->size() );

	if( root->size() > 0 )
	{
		printf("\n");
		for( Json::ValueIterator itr = root->begin() ; itr != root->end() ; itr++ )
		{
			// Print depth.
			for( int tab = 0 ; tab < depth; tab++)
			{
			   printf("-");
			}
			printf(" subvalue(%s) -", itr.memberName());
			DumpJsonTree( &(*itr), depth);
		}
	}
	else
	{
		printf(" ");
		PrintJsonValue(root);
		printf( "\n" );
	}
}
Exemplo n.º 3
0
void JsonParser::parseMaterials(Json::Value &root){
    LOG_DEBUG("Parsing Materials.");
    bool foundMaterials = false;
    for( Json::ValueIterator itr = root.begin() ; itr != root.end() ; itr++ ) {
        std::string key = itr.key().asString();
        if (key == "materials") {
            foundMaterials = true;
            
                // loop through materials
            Json::Value objRoot = *itr;
            for( Json::ValueIterator objItr = objRoot.begin() ; objItr != objRoot.end() ; objItr++ ) {
                std::string matName = objItr.key().asString();
                LOG_DEBUG("Found material: " << matName);
                
                    // we first check if we're dealing with a light or mesh
                std::string matType = getStringAttr("type", *objItr);
                Material * mat = getMaterial(matType, matName, *objItr, renderEnv); 
            
                    // add to shading engine
                renderEnv->shadingEngine->registerMaterial(matName, mat);
            }       
            LOG_DEBUG("Done parsing materials.\n");
            break;
        }
    }
    if (!foundMaterials) {
        LOG_WARNING("No materials found in file " << filename << ".");
    }
}
Exemplo n.º 4
0
Translator::Langs Translator::getLangs() const
{
	_curlBuffer = "";
	Translator::Langs langs;
	std::string mylang = getMyLang();
	if(mylang.empty())
		mylang = "en";	// default

	std::string url = "https://translate.yandex.net/api/v1.5/tr.json/getLangs?key=";
	url += getApiKey();
	url += "&ui=";
	url += mylang;

	curl_easy_setopt(curl, CURLOPT_URL, url.c_str());;
	CURLcode res = curl_easy_perform(curl);
	if(res != CURLE_OK)
	{
		// error
	}


	Json::Reader reader;
	Json::Value root;
	reader.parse(_curlBuffer, root);

	for(Json::ValueIterator it = root["langs"].begin(); it != root["langs"].end(); it++)
	{
		langs.push_back(std::make_pair(	
										it.key().asString(),  	// key
										(*it).asString()		// value
									));
	}

	return langs;
}
Exemplo n.º 5
0
void Com::JsonParseOrder(Order_t* order){
    Json::Value root;   // will contains the root value after parsing.
    Json::Reader reader;
   
    bool parsingSuccessful = reader.parse( buffer, root );
    
    if ( !parsingSuccessful )
    {
        std::cout  << "Failed to parse configuration\n"
        << reader.getFormattedErrorMessages();
        return;
    }

    order->orderId = root["order_id"].asInt();

   for( Json::ValueIterator itr = root["recipe"].begin() ; itr != root["recipe"].end() ; itr++ ) {
#ifdef DEBUG
        std::cout << itr.key().asString() << " " << *itr;
#endif
        order->ingredients.push_back(makeIngredientItem(itr.key().asString(), (*itr).asInt()));
   }
#ifdef DEBUG
    printf("parsing passed\n");
#endif
}
Exemplo n.º 6
0
/**
 * Read a map of {list_name : class_list} from json
 */
std::unordered_map<std::string, std::vector<std::string> > ConfigFiles::load_class_lists() {
  std::unordered_map<std::string, std::vector<std::string> > lists;
  std::string class_lists_filename;
  this->m_json.get("class_lists", "", class_lists_filename);

  if (class_lists_filename.empty()) {
    return lists;
  }

  std::ifstream input(class_lists_filename);
  Json::Reader reader;
  Json::Value root;
  bool parsing_succeeded = reader.parse(input, root);
  always_assert_log(parsing_succeeded, "Failed to parse class list json from file: %s\n%s",
                    class_lists_filename.c_str(),
                    reader.getFormattedErrorMessages().c_str());

  for (Json::ValueIterator it = root.begin(); it != root.end(); ++it) {
    std::vector<std::string> class_list;
    Json::Value current_list = *it;
    for (Json::ValueIterator list_it = current_list.begin(); list_it != current_list.end(); ++list_it) {
      lists[it.key().asString()].push_back((*list_it).asString());
    }
  }

  lists["secondary_dex_head.list"] = get_coldstart_classes();

  return lists;
}
Exemplo n.º 7
0
std::map<std::string, std::string>
jsonValueToAccount(Json::Value& value, const std::string& accountId) {
    auto idPath_ = fileutils::get_data_dir() + DIR_SEPARATOR_STR + accountId;
    fileutils::check_dir(idPath_.c_str(), 0700);
    auto detailsMap = DRing::getAccountTemplate(value[DRing::Account::ConfProperties::TYPE].asString());

    for( Json::ValueIterator itr = value.begin() ; itr != value.end() ; itr++ ) {
        if (itr->asString().empty())
            continue;
        if (itr.key().asString().compare(DRing::Account::ConfProperties::TLS::CA_LIST_FILE) == 0) {
            std::string fileContent(itr->asString());
            fileutils::saveFile(idPath_ + DIR_SEPARATOR_STR "ca.key", {fileContent.begin(), fileContent.end()}, 0600);

        } else if (itr.key().asString().compare(DRing::Account::ConfProperties::TLS::PRIVATE_KEY_FILE) == 0) {
            std::string fileContent(itr->asString());
            fileutils::saveFile(idPath_ + DIR_SEPARATOR_STR "dht.key", {fileContent.begin(), fileContent.end()}, 0600);

        } else if (itr.key().asString().compare(DRing::Account::ConfProperties::TLS::CERTIFICATE_FILE) == 0) {
            std::string fileContent(itr->asString());
            fileutils::saveFile(idPath_ + DIR_SEPARATOR_STR "dht.crt", {fileContent.begin(), fileContent.end()}, 0600);
        } else
            detailsMap[itr.key().asString()] = itr->asString();
    }

    return detailsMap;
}
Exemplo n.º 8
0
Objects::Object::Object(Json::Value data) :
 self_data( data ), self_x(0), self_y(0), self_w(0), self_h(0)
{
  Json::Value dimensions = data["dimensions"];
  if ( dimensions.isObject() )
  {
    // Coordinates are stored as doubles, but interpretted as either
    // pixel coordinates or fractional. If ANY dimension is a double, then
    // they all should be (why would you use a double coordinate otherwise?)

    self_coordType = Objects::NON_NORM;

    for ( Json::ValueIterator itr  = dimensions.begin();
                              itr != dimensions.end();
                              itr ++ )
    {
      string key = itr.key().asString();

      if (dimensions[ key ] . isDouble() )
      {
        self_coordType = Objects::NORM;
        break;
      }
    }

    self_x = dimensions["x"].asDouble();
    self_y = dimensions["y"].asDouble();

  }
}
Exemplo n.º 9
0
void ItemEquipper::deserializeEquippedItems(Json::Value& root) {
	Item* item;
	
    for (Json::ValueIterator it = root.begin(); it != root.end(); it++) {
		item = new Item();
		item->deserialize(*it);
        _equippedItems[it.key().asInt()] = item;
    }
}
Exemplo n.º 10
0
bool CannyReader::readFromFile()
{
	Timer aTimer;
	std::ifstream cannyFile(srcFile);
	cannyFile.precision(20);
	if (cannyFile.is_open()) {
		std::stringstream buffer;
		buffer << cannyFile.rdbuf();

		std::string contents(buffer.str());
		cout << "Time to Read: " << aTimer.elapsed() << endl;
		aTimer.restart();

		Json::Value root;
		Json::Reader reader;
		bool parsingSuccessful = reader.parse( contents, root );
		cout << "Time to parse: " << aTimer.elapsed() << endl;
		aTimer.restart();
		if (parsingSuccessful)
		{
			for( Json::ValueIterator outer = root.begin() ; outer != root.end() ; outer++ ) {
				int camNum = outer.key().asInt();

				Json::Value oneCam = root[camNum];

				for( Json::ValueIterator itr = oneCam.begin() ; itr != oneCam.end() ; itr++ ) {
					vector<Line_Segment *>* lineSegments = new vector<Line_Segment *>();

					int key = atoi(itr.key().asCString());

					Json::Value jsonSegments = oneCam[itr.key().asCString()];
					for( Json::ValueIterator itr2 = jsonSegments.begin() ; itr2 != jsonSegments.end() ; itr2++ ) {
						Json::Value jsonSeg = jsonSegments[itr2.key().asInt()];
						Line_Segment* seg = (Line_Segment *) malloc(sizeof(Line_Segment));
						seg->row1 = jsonSeg["r1"].asInt();
						seg->col1 = jsonSeg["c1"].asInt();
						seg->row2 = jsonSeg["r2"].asInt();
						seg->col2 = jsonSeg["c2"].asInt();

						lineSegments->push_back(seg);
					}
					precomputedCannySegments[camNum][key] = lineSegments;
				}
			}
			cannyFile.close();
			cout << "Time to reconstruct: " << aTimer.elapsed() << endl;

			return true;
		}
		else {
			return false;
		}
	}
	return false;
}
Exemplo n.º 11
0
std::list<std::string> CJSONHandler::ParseAvailLanguagesTX(std::string strJSON, bool bIsXBMCCore, std::string strURL)
{
  Json::Value root;   // will contains the root value after parsing.
  Json::Reader reader;
  std::string lang;
  std::list<std::string> listLangs;

  bool parsingSuccessful = reader.parse(strJSON, root );
  if ( !parsingSuccessful )
  {
    CLog::Log(logERROR, "CJSONHandler::ParseAvailLanguagesTX: no valid JSON data");
    return listLangs;
  }

  const Json::Value langs = root;
  std::string strLangsToFetch;
  std::string strLangsToDrop;
  std::string strLangsBlacklisted;

  for(Json::ValueIterator itr = langs.begin() ; itr != langs.end() ; itr++)
  {
    lang = itr.key().asString();
    if (lang == "unknown")
      CLog::Log(logERROR, "JSONHandler: ParseLangs: no language code in json data. json string:\n %s", strJSON.c_str());

    Json::Value valu = *itr;
    std::string strCompletedPerc = valu.get("completed", "unknown").asString();
    std::string strModTime = valu.get("last_update", "unknown").asString();

    bool bLangBlacklisted = g_LCodeHandler.CheckIfLangCodeBlacklisted(lang);

    // we only add language codes to the list which has a minimum ready percentage defined in the xml file
    // we make an exception with all English derived languages, as they can have only a few srings changed
    if (lang.find("en_") != std::string::npos || strtol(&strCompletedPerc[0], NULL, 10) > g_Settings.GetMinCompletion()-1 || !bIsXBMCCore)
    {
      if (!bLangBlacklisted)
      {
        strLangsToFetch += lang + ": " + strCompletedPerc + ", ";
        listLangs.push_back(lang);
        g_Fileversion.SetVersionForURL(strURL + "translation/" + lang + "/?file", strModTime);
      }
      else
      {
	strLangsBlacklisted += lang + ": " + strCompletedPerc + ", ";
      }
    }
    else
      strLangsToDrop += lang + ": " + strCompletedPerc + ", ";
  };
  CLog::Log(logINFO, "JSONHandler: ParseAvailLangs: Languages to be Fetcehed: %s", strLangsToFetch.c_str());
  CLog::Log(logINFO, "JSONHandler: ParseAvailLangs: Languages to be Dropped (not enough completion): %s", strLangsToDrop.c_str());
  CLog::Log(logINFO, "JSONHandler: ParseAvailLangs: Languages to be Dropped due they are blacklisted: %s",strLangsBlacklisted.c_str());
  return listLangs;
};
Exemplo n.º 12
0
string HandlerChat::getChatId(string remitente,string destinatario){
	/**Busca el chat id de la conversacion sino existe lo crea.**/
	Json::Value chatsId=getChatsIdValueFromDestinatario(destinatario);
	string id="";
	for( Json::ValueIterator itr = chatsId.begin() ; itr != chatsId.end() ; itr++ ){
		if((*itr).asString()==remitente){
			id=itr.key().asString();
		}
	}
	return id;
}
Exemplo n.º 13
0
bool updateRegistry(Json::Value &jsonRoot, Json::Value &outputRoot)
{
	bool success = true;
	for (Json::ValueIterator iter = jsonRoot.begin(); iter != jsonRoot.end(); iter++) {
		Json::Value solutionsRoot = jsonRoot.get(iter.memberName(), Json::Value());
		Json::Value solutionsOutput;
		for(Json::ValueIterator itr = solutionsRoot["settings"].begin() ; itr != solutionsRoot["settings"].end() ; itr++ )
		{
			bool missingValue = false;
			Json::Value currentOption;
			const char * path = solutionsRoot["options"]["path"].asCString();
			const char * valueName = itr.memberName();
			long valueToSet = solutionsRoot["settings"][valueName].asUInt();
			
		    wstring updatedPath = toWideChar(path);
			wstring updatedValueName = toWideChar(valueName);
			long value = -1;
			try
			{
				value = getDwordValue(hKeyFromString(solutionsRoot["options"]["hKey"].asCString()), updatedPath.c_str(), updatedValueName.c_str());
			} catch (int exCode)
			{
				currentOption["statusCode"] = exCode;
				currentOption["oldValue"] = Json::Value();
				currentOption["newValue"] = Json::Value();
				success = false;
				missingValue = true;
			}

			bool valueSet = setDwordValue(hKeyFromString(solutionsRoot["options"]["hKey"].asCString()), updatedPath.c_str(), updatedValueName.c_str(), valueToSet);
			if (missingValue)
			{
				currentOption["oldValue"] = Json::Value();
			} else {
				currentOption["oldValue"] = value;
			}
			try
			{
				currentOption["newValue"] = getDwordValue(hKeyFromString(solutionsRoot["options"]["hKey"].asCString()), updatedPath.c_str(), updatedValueName.c_str());
			} catch (int exceptionCode) {
				// TODO Handle gracefully.
			}
			if (!valueSet)
			{
				success = false;
				currentOption["newValue"] = value;
			}
		
			solutionsOutput[valueName] = currentOption;
		}
		outputRoot[iter.memberName()]["results"] = solutionsOutput;
	}
	return success;
}
Exemplo n.º 14
0
void ofApp::record(){
    ofFile newfile(ofToDataPath("coordinates.json"), ofFile::WriteOnly);
    string time = ofToString(ofGetElapsedTimef());
    for(Json::ValueIterator i = untimedData.begin() ; i != untimedData.end(); i++) {
        string id = i.key().asString();
        data[id][time]["position"] = untimedData[id]["position"];
        data[ofToString(id)][time]["rotation"] = untimedData[id]["rotation"];
        cout << data;
    }
    if (data != ofxJSONElement::null)
        newfile << data;
    sound.play();
}
Exemplo n.º 15
0
qpid::types::Variant::Map agocontrol::jsonToVariantMap(Json::Value value) {
	Variant::Map map;
	try {
		for (Json::ValueIterator it = value.begin(); it != value.end(); it++) {
			// printf("%s\n",it.key().asString().c_str());
			// printf("%s\n", (*it).asString().c_str());
			if ((*it).size() > 0) {
				// cout << "JSON Type: " << (*it).type() << endl;
				// cout << "Key: " << it.key().asString() << endl;
				if ((*it).type() == 6) {
					map[it.key().asString()] = jsonToVariantList((*it));
				} else if ((*it).type() == 7) {
					map[it.key().asString()] = jsonToVariantMap((*it));
				}
			} else {
				if ((*it).isString()) map[it.key().asString()] = (*it).asString();
				if ((*it).isBool()) map[it.key().asString()] = (*it).asBool();
				if ((*it).isInt()) map[it.key().asString()] = (*it).asInt();
				if ((*it).isUInt()) map[it.key().asString()] = (*it).asUInt();
				if ((*it).isDouble()) map[it.key().asString()] = (*it).asDouble();
			}
		}	
	} catch (const std::exception& error) {
		cout << "ERROR! Exception during JSON->Variant::Map conversion!" << endl;
		stringstream errorstring;
		errorstring << error.what();
		cout << "EXCEPTION: " << errorstring.str() << endl;
	}
	return map;
}
Exemplo n.º 16
0
void Objects::StringDisplay::update()
{
  // Make sure repeated calls to this function don't simply add strings
  self_displayStrings.clear();

  Json::Value strings;
  strings = self_data["strings"];

  if (self_data["external"].isBool())
    if (self_data["external"] == true)
    {
      string resource = self_data["resource"].asString();
      string node     = self_data["node"].asString();
      strings = Resources::getResourceNode(resource, node);
    }
  

  //Create array of human readable strings. New entry every "self_maxLines"
  //lines
  stringstream outputStream;
  int lineN = 0;
  for (Json::ValueIterator itr = strings.begin(); 
       itr != strings.end(); 
       itr++)
  {
    //Stored as "key" : "value", so extract these
    string key = itr.key().asString();
    Json::Value value = strings[key];
 
    //buffer key and do appropriate thing for value
    outputStream << key << self_delimiter;
    if (value.type() == Json::stringValue)
      outputStream << value.asString();
    else if (value.isNumeric())
      outputStream << value.asDouble();
    outputStream << "\n";

    lineN++;
    if ( lineN == self_maxLines )
    {
      self_displayStrings.push_back(outputStream.str());
      lineN = 0;
      outputStream.str("");
    }

  }
  //Add remaining string
  self_displayStrings.push_back( outputStream.str() );
}
void SiteLanguagePackage::decode_from_json_object(const Json::Value &root)
{
    Json::Value tmp;
    
    if ( root.isObject() && root.isMember("LanguageMap") ) {
        const Json::Value map_LanguageMap = root["LanguageMap"];
        if ( !map_LanguageMap.isNull() ) {
            for( Json::ValueIterator it = map_LanguageMap.begin(); it != map_LanguageMap.end(); ++it ) {
            
                std::string key = it.key().asString();
                LanguageMap[key] = map_LanguageMap[key].asString();
            }
        }
    }   
}
Exemplo n.º 18
0
string HandlerChat::readChat(string chatString,string user,string messageId,string conversationId){
	/**Leo la CANT_MENSAJES desde mensajeId del chat desde la vista del usuario.Actualiza los estados con los
	 * ultimos mensajes leidos en la conversacion.**/
	Json::Value chat=jsonParse.stringToValue(chatString);
	Json::Value lastsMessages;
	Json::Value lastsMessagesMsg= Json::Value(Json::arrayValue);
	LOG(DEBUG)<<chatString;
	int lastMessageRead;
	int lastMessageId=chat["message_id"].asInt();
	if(chat["User1"].asString()==user){
		lastMessageRead=chat["LastMessage2"].asInt();
		chat["LastMessage1"]=0;
	}else{
		lastMessageRead=chat["LastMessage1"].asInt();
		chat["LastMessage2"]=0;
	}
	Json::Value messages=chat["Messages"];
	int messageIdSearch=atoi(messageId.c_str());
	for( Json::ValueIterator itr = messages.begin() ; itr != messages.end() ; itr++ ){
		LOG(INFO)<<"id "<<itr.key().asString();
		int currentMessageId=atoi(itr.key().asString().c_str());
		int min=messageIdSearch-CANT_MESSAGES;
		if((currentMessageId<=messageIdSearch)&&(currentMessageId>=(min))){
			Json::Value Message=*itr;
			if(currentMessageId>=(lastMessageId-lastMessageRead)){
				Message["status"]="D";
			}else{
				Message["status"]="R";
			}
			Message["message_id"]=itr.key().asString();
			lastsMessagesMsg.append(Message);
		}
	}
	lastsMessages["messages"]=lastsMessagesMsg;
	int bottomMessageId=messageIdSearch-CANT_MESSAGES;
	if(bottomMessageId<0){
		bottomMessageId=0;
	}
	lastsMessages["LastMessageId"]=bottomMessageId;
	string lastsMessagesString=this->jsonParse.valueToString(lastsMessages);
	chatString=this->jsonParse.valueToString(chat);
	LOG(DEBUG)<<chatString;
	DBtuple putChat("chat_"+conversationId,chatString);
	DB->put(putChat);
	return lastsMessagesString;
}
Exemplo n.º 19
0
void JsonParser::parseOptions(Json::Value &root){
    LOG_DEBUG("Parsing Options.");
    bool foundOptions = false;
        // Options
    for( Json::ValueIterator itr = root.begin() ; itr != root.end() ; itr++ ) {
        std::string key = itr.key().asString();
        if (key == "options") {
            foundOptions = true;
            
                // read all standard data
            int r_pixelSamples =   getIntAttr("pixelsamples", *itr);
            int r_lightSamples =   getIntAttr("lightsamples", *itr);
            int r_mindepth =       getIntAttr("mindepth", *itr);
            int r_maxdepth =       getIntAttr("maxdepth", *itr);
            int r_resolution[2];   getIntArrayAttr("resolution", *itr, 2, r_resolution);
            std::string r_fileName = getStringAttr("filename", *itr);
            r_fileName = stringTemplate(r_fileName);
                // TODO: check for any ones we've skipped and warn the user
            
                // TODO: handle errors gracefully
            
                // apply to globals
            LOG_DEBUG("Setting pixel samples to: " << r_pixelSamples);
            (*renderEnv->globals)[PixelSamples] = (double)r_pixelSamples;
            LOG_DEBUG("Setting light samples to: " << r_lightSamples);
            (*renderEnv->globals)[LightSamples] = (double)r_lightSamples;
            LOG_DEBUG("Setting min trace depth to: " << r_mindepth);
            (*renderEnv->globals)[MinDepth] = (double)r_mindepth;
            LOG_DEBUG("Setting max trace depth to: " << r_maxdepth);
            (*renderEnv->globals)[MaxDepth] = (double)r_maxdepth;
            LOG_DEBUG("Setting resolution to: " << r_resolution[0] << " * " << r_resolution[1]);
            (*renderEnv->globals)[ResolutionX] = r_resolution[0];
            (*renderEnv->globals)[ResolutionY] = r_resolution[1];
            LOG_DEBUG("Setting file output to: " << r_fileName);
            (*renderEnv->stringGlobals)["fileName"] = r_fileName;
            
            // We're done, so we exit out of root iterator loop
            LOG_DEBUG("Done parsing Options.\n");
            break;
        }
    }
    if (!foundOptions) {
        LOG_WARNING("No options found in file " << filename << ".");
    }
}
Exemplo n.º 20
0
void BuyCountData::decode_from_json_object(const Json::Value &root)
{
    Json::Value tmp;

    

    
    if ( root.isObject() && root.isMember("buyCountMap") ) {
        const Json::Value map_buyCountMap = root["buyCountMap"];
        if ( !map_buyCountMap.isNull() ) {
            for( Json::ValueIterator it = map_buyCountMap.begin(); it != map_buyCountMap.end(); ++it ) {
            
                std::string key = it.key().asString();
                buyCountMap[key] = map_buyCountMap[key].asString();
            }
        }
    }   
}
Exemplo n.º 21
0
void GetBuyedListRequestData::decode_from_json_object(const Json::Value &root)
{
    Json::Value tmp;

    

    
    if ( root.isObject() && root.isMember("contentUuidMap") ) {
        const Json::Value map_contentUuidMap = root["contentUuidMap"];
        if ( !map_contentUuidMap.isNull() ) {
            for( Json::ValueIterator it = map_contentUuidMap.begin(); it != map_contentUuidMap.end(); ++it ) {
            
                std::string key = it.key().asString();
                contentUuidMap[key] = map_contentUuidMap[key].asString();
            }
        }
    }   
}
Exemplo n.º 22
0
void CPlayerLevels::AddLevel( const FData& level, const std::string& levelId, std::list<CLevel>& levelList )
{
	FData value;
	value = level.get("PlayerId",value);
	if(!value.isString())
	{
		return;
	}
	std::string playerId(value.asString());
	value = level.get("PlayerName",value);
	std::string playerName(value.asString());
	value = level.get("PlayerSource",value);
	std::string playerSource(value.asString());
	value = level.get("Name",value);
	std::string name(value.asString());
	value = level.get("Data",value);
	std::string ldata(value.asString());
	value = level.get("thumb",value);
	std::string lthumb(value.asString());
	value = level.get("RDate",value);
	std::string relativeDate(value.asString());
	value = level.get("SDate",value);
	std::string date(value.asString());
	value = level.get("Plays",value);
	int plays = value.asInt();
	value = level.get("Votes",value);
	int votes = value.asInt();
	value = level.get("Score",value);
	int score = value.asInt();
	value = level.get("Rating",value);
	float rating = value.asFloat();
	value = level.get("CustomData",value);

	CustomData	customData;
	Json::ValueIterator it = value.begin();
	for(; it != value.end(); it++)
	{
		customData.insert(std::make_pair(it.key().asString(), (*it).asString()));
	}
	
	levelList.push_back( CLevel(name, playerName, playerId,
						playerSource, ldata, lthumb, votes, plays,
						rating, score, date, relativeDate, customData, levelId));
}
/*
 * Parse JSON match data
 */
void Engine::ParseSnapshotData(const std::vector<uint8_t> &data) {
  LOGI("Parsing snapshot data");
  if (data.size() == 0) {
    LOGI("Game data not found");
    return;
  }

  std::string str(data.begin(), data.end());
  LOGI("Data: %s", str.c_str());

  Json::Value root;
  Json::Reader reader;
  bool parsingSuccessful = reader.parse(str, root);
  if (!parsingSuccessful) {
    LOGI("Data parse error");
    return;
  }

  std::string version = root[JSON_KEY_VERSION].asString();
  if (version != JSON_VERSION) {
    LOGI("Data version mismatch");
    return;
  }

  //Reset existing data
  for (int32_t i = 0; i < NUM_GAME_WORLD; ++i)
    for (int32_t j = 0; j < NUM_GAME_STAGES; ++j)
      scores_[i][j] = 0;

  //Level data
  const Json::Value levels = root[JSON_KEY_LEVELS];
  Json::ValueIterator it = levels.begin();
  Json::ValueIterator itEnd = levels.end();
  while (it != itEnd) {
    std::string stage = it.key().asString();
    int32_t score = (*it).asInt();
    LOGI("stage:%s score:%d", stage.c_str(), score);

    if (map_scores_.find(stage) != map_scores_.end())
      *map_scores_[stage] = score;
    ++it;
  }
}
Exemplo n.º 24
0
void JsonParser::parseGeometry(Json::Value &root){
    LOG_DEBUG("Parsing Geometry.");
    bool foundGeometry = false;
    for( Json::ValueIterator itr = root.begin() ; itr != root.end() ; itr++ ) {
        std::string key = itr.key().asString();
        if (key == "objects") {
            foundGeometry = true;
            
                // find object
            Json::Value objRoot = *itr;
            for( Json::ValueIterator objItr = objRoot.begin() ; objItr != objRoot.end() ; objItr++ ) {
                LOG_DEBUG("Found object: " << objItr.key().asString());
                
                    // check if we're dealing with a light or mesh
                std::string objType = getStringAttr("type", *objItr);
                if (objType == "geometry"){
                    std::tr1::shared_ptr<AuroraObject> geo = getGeometry(*cameraTransform, *objItr, renderEnv);
                    objects.push_back(geo);
                }
                else if (objType == "light"){
                    Light* light = getLight(*cameraTransform, *objItr, (*renderEnv->globals)[LightSamples], renderEnv);
                    lights.push_back(light);
                }
                else if (objType == "envlight"){
                    Light* light = getEnvLight(*cameraTransform, *objItr, (*renderEnv->globals)[LightSamples], renderEnv);
                    lights.push_back(light);
                }
                else {
                    LOG_WARNING("Unknown object type found: " << objType);
                }
            
            }
                // apply to globals
            LOG_DEBUG("Done parsing Geometry.\n");
            break;

        }
    }
    if (!foundGeometry) {
        LOG_WARNING("No geometry found in file " << filename << ".");
    }

}
Exemplo n.º 25
0
void BuyedListRequestData::decode_from_json_object(const Json::Value &root)
{
    Json::Value tmp;

    
    if ( root.isObject() && root.isMember("total") ) {
        tmp = root["total"];
        if ( !tmp.isNull() )
        {
            total = tmp.asString();
        }
    }

    

    

    
    
    if ( root.isObject() && root.isMember("contentUuid") ) {
        const Json::Value map_contentUuid = root["contentUuid"];
        if ( !map_contentUuid.isNull() ) {
            for( Json::ValueIterator it = map_contentUuid.begin(); it != map_contentUuid.end(); ++it ) {
            
                std::string key = it.key().asString();
                contentUuid[key] = map_contentUuid[key].asString();
            }
        }
    }   
    
    if ( root.isObject() && root.isMember("buyCount") ) {
        const Json::Value map_buyCount = root["buyCount"];
        if ( !map_buyCount.isNull() ) {
            for( Json::ValueIterator it = map_buyCount.begin(); it != map_buyCount.end(); ++it ) {
            
                std::string key = it.key().asString();
                buyCount[key] = map_buyCount[key].asInt();
            }
        }
    }   
}
Exemplo n.º 26
0
bool cStatSerializer::LoadStatFromJSON(const Json::Value & a_In)
{
	m_Manager->Reset();

	for (Json::ValueIterator it = a_In.begin() ; it != a_In.end() ; ++it)
	{
		AString StatName = it.key().asString();

		eStatistic StatType = cStatInfo::GetType(StatName);

		if (StatType == statInvalid)
		{
			LOGWARNING("Invalid statistic type \"%s\"", StatName.c_str());
			continue;
		}

		Json::Value & Node = *it;

		if (Node.isInt())
		{
			m_Manager->SetValue(StatType, Node.asInt());
		}
		else if (Node.isObject())
		{
			StatValue Value = Node.get("value", 0).asInt();

			// TODO 2014-05-11 xdot: Load "progress"

			m_Manager->SetValue(StatType, Value);
		}
		else
		{
			LOGWARNING("Invalid statistic value for type \"%s\"", StatName.c_str());
		}
	}

	return true;
}
Exemplo n.º 27
0
void BuyRequestData::decode_from_json_object(const Json::Value &root)
{
    Json::Value tmp;

    

    
    if ( root.isObject() && root.isMember("afCoin") ) {
        tmp = root["afCoin"];
        if ( !tmp.isNull() )
        {
            afCoin = tmp.asString();
        }
    }

    
    if ( root.isObject() && root.isMember("countAdd") ) {
        tmp = root["countAdd"];
        if ( !tmp.isNull() )
        {
            countAdd = tmp.asString();
        }
    }

    
    if ( root.isObject() && root.isMember("contentUuid") ) {
        const Json::Value map_contentUuid = root["contentUuid"];
        if ( !map_contentUuid.isNull() ) {
            for( Json::ValueIterator it = map_contentUuid.begin(); it != map_contentUuid.end(); ++it ) {
            
                std::string key = it.key().asString();
                contentUuid[key] = map_contentUuid[key].asString();
            }
        }
    }   
    
    
}
Exemplo n.º 28
0
void JsonParser::parseShaders(Json::Value &root){
    LOG_DEBUG("Parsing Shaders.");
    bool foundShaders = false;
    for( Json::ValueIterator itr = root.begin() ; itr != root.end() ; itr++ ) {
        std::string key = itr.key().asString();
        if (key == "shaders") {
            foundShaders = true;
                // loop through shaders
            Json::Value objRoot = *itr;
            for( Json::ValueIterator objItr = objRoot.begin() ; objItr != objRoot.end() ; objItr++ ) {
                std::string shdName = objItr.key().asString();
                LOG_DEBUG("Found shader: " << shdName);

                    // find attribute type
                std::string attributeType = getStringAttr("attributetype", *objItr);
                
                if (attributeType == "color"){
                    Shader<Color> *newShd = getColorShader(shdName, *objItr);
                    renderEnv->shadingEngine->registerShaderColor(shdName, newShd);
                } else if (attributeType == "float"){
                    Shader<float> *newShd = getFloatShader(shdName, *objItr);
                    renderEnv->shadingEngine->registerShaderFloat(shdName, newShd);
                }
                else{
                    LOG_ERROR("Unable to parse shader for attribute type: " << attributeType);
                }
                

            }
            LOG_DEBUG("Done parsing shaders.\n");
            break;
        }
    }
    if (!foundShaders) {
        LOG_WARNING("No shaders found in file " << filename << ".");
    }

}
Exemplo n.º 29
0
	bool Level::ReadLevelFile(std::string path)
	{
		FileIO fio;
		
		if( !fio.LoadFile("Assets/Levels/"+path) || fio.RootKey != "Level" )
			return false;

		Json::Value types = fio.GetChildren(fio.Root);

		for( Json::ValueIterator i = types.begin(); i != types.end(); ++i )
		{
			std::string type = i.key().asString();

			Entity* arch = Factory::BuildArchetype("Assets/Objects/"+type);

			if( arch == nullptr )
				continue;

			Json::Value objects = (*i)["Entities"];
			for( Json::ValueIterator j = objects.begin(); j != objects.end(); ++j )
			{
				Json::Value components = *j;
				for( Json::ValueIterator k = components.begin(); k != components.end(); ++k )
				{
					std::string key = k.key().asString();
			
				}

				// Stores Entity name and Json value with components
				STATIC_LIST.push_back( std::pair<std::string,Json::Value>(type,*j) );
			}			
		}


		return true;
	}
Exemplo n.º 30
0
bool util::PrintJSONTree( Json::Value &root, unsigned short depth /* = 0 */) {
	depth += 1;
	printf( " {type=[%d], size=%d}", root.type(), root.size() ); 

	if( root.size() > 0 ) {
		printf("\n");
		for( Json::ValueIterator itr = root.begin() ; itr != root.end() ; itr++ ) {
			// Print depth. 
			for( int tab = 0 ; tab < depth; tab++) {
			   printf("-"); 
			}
			printf(" subvalue(");
			PrintJSONValue(itr.key());
			printf(") -");
			PrintJSONTree( *itr, depth); 
		}
		return true;
	} else {
		printf(" ");
		PrintJSONValue(root);
		printf( "\n" ); 
	}
	return true;
}