JSONNode JSONNodeHelper::findKey(JSONNode jsonNode, std::string key) { JSONNode returnNode; for (JSONNode::const_iterator i = jsonNode.begin(); i != jsonNode.end(); i++){ if (i->name() == key){ returnNode = *i; } } // TODO: throw exception if the key is not found return returnNode; }
void Rig::loadDevices(JSONNode root) { JSONNode::const_iterator i = root.begin(); // for this we want to iterate through all children and have the device class // parse the sub-element. while (i != root.end()){ // get the node name and value as a string std::string nodeName = i->name(); // Node name is the Device id Device* device = new Device(nodeName, *i); addDevice(device); //increment the iterator ++i; } }
void SimulationAnimationPatch::loadJSON(const JSONNode data) { string patchName = data.name(); // Load options for raytracer application. (window, ray tracer, filter) JSONNode::const_iterator i = data.begin(); while (i != data.end()) { std::string nodeName = i->name(); if (nodeName == "frameDirectory") { JSONNode fileName = *i; m_file_frameManager = new ArnoldFileFrameManager(fileName.as_string()); } i++; } }
// parse json/config, get filename and tilesize void Tilemap::parseConfig(const JSONNode& n) { JSONNode::const_iterator it = n.begin(); while (it != n.end()) { string nodeName = it->name(); // might need stupid workaround, for some reason it->as_int() doesn't link! if (nodeName == "tilesize") tileSize = atoi((it->as_string()).c_str()); if (nodeName == "tilemap") { tilemapFile = it->as_string(); } ++it; } createTexture(); }
//------------------------------------------------------------------------------ // downloads recent trade data: std::string KClient::trades(const std::string& pair, const std::string& since, std::vector<KTrade>& output) { KInput ki; ki["pair"] = pair; ki["since"] = since; // download and parse data json_string data = libjson::to_json_string( public_method("Trades", ki) ); JSONNode root = libjson::parse(data); // throw an exception if there are errors in the JSON response if (!root.at("error").empty()) { std::ostringstream oss; oss << "Kraken response contains errors: "; // append errors to output string stream for (JSONNode::const_iterator it = root["error"].begin(); it != root["error"].end(); ++it) oss << std::endl << " * " << libjson::to_std_string(it->as_string()); throw std::runtime_error(oss.str()); } // throw an exception if result is empty if (root.at("result").empty()) { throw std::runtime_error("Kraken response doesn't contain result data"); } JSONNode &result = root["result"]; JSONNode &result_pair = result[0]; std::string last = libjson::to_std_string( result.at("last").as_string() ); std::vector<KTrade> buf; for (JSONNode::const_iterator it = result_pair.begin(); it != result_pair.end(); ++it) buf.push_back(KTrade(*it)); output.swap(buf); return last; }
/** * Reads the description from the string * @param json the json description as a string * @param kd the resulting knapsack data */ static void readJson(const std::string& json, KnapData< T >& kd) { struct { bool mNSet; bool mCSet; bool mWSet; bool mPSet; } checklist = {false, false, false, false}; JSONNode nd = libjson::parse(json); JSONNode::const_iterator i = nd.begin(); kd.mN = 0; kd.mTP = 0; kd.mTW = 0; kd.mCoe = NULL; while (i != nd.end()) { std::string name = i->name(); //std::cout << "node \"" << name << "\"\n"; if (name == JSON_KNAP_N) { kd.mN = i->as_int(); kd.mCoe = new KnapRecord<T>[kd.mN]; BNB_ASSERT(kd.mCoe); checklist.mNSet = true; } else if (name == JSON_KNAP_C) { kd.mC = i->as_int(); checklist.mCSet = true; } else if (name == JSON_KNAP_W) { BNB_ASSERT(kd.mCoe); parseW(*i, kd, checklist.mPSet); checklist.mWSet = true; } else if (name == JSON_KNAP_P) { BNB_ASSERT(kd.mCoe); parseP(*i, kd, checklist.mWSet); checklist.mPSet = true; } i++; } }
void Tilemap::load(char* fname) { // load tilemap.json (json) char* buffer = 0; long length; FILE* f = fopen("tilemap.json", "rb"); if (f) { fseek (f, 0, SEEK_END); length = ftell(f); fseek (f, 0, SEEK_SET); buffer = new char [length+1]; fread(buffer, 1, length, f); buffer[length] = 0; fclose(f); } JSONNode tilemap = libjson::parse(buffer); JSONNode::const_iterator it = tilemap.begin(); while (it != tilemap.end()) { string nodeName = it->name(); if (nodeName == "config") parseConfig(*it); else if (nodeName == "tiles") parseTiles(*it); //increment the iterator ++it; } // load tilemap w/ stbi_ // calc tilesperline=tilemap_width/tilesize delete buffer; }
// read through json/tiles // for each tile, calculate index, crestore in a std::vector(?) void Tilemap::parseTiles(const JSONNode& n) { JSONNode::const_iterator it = n.begin(); while (it != n.end()) { string textureId = it->name(); int idx = atoi((it->as_string()).c_str()); //it->as_int(); int x1 = idx%tilesPerLine * tileSize; int y1 = idx/tilesPerLine * tileSize; int x2 = x1+tileSize; int y2 = y1+tileSize; TilemapTexture textureInfo = {(float)x1/tilemapWidth, (float)y1/tilemapHeight, (float)x2/tilemapWidth, (float)y2/tilemapHeight}; tiles[idx] = textureInfo; tileMapping[textureId] = idx; ++it; } }
int main(){ JSONNode n = read_formatted("input.json"); JSONNode n1 = read_formatted("input1.json"); test *tst = new test(); int status; //n.set_name(abi::__cxa_demangle(typeid(*tst).name(), 0,0,&status )); n.push_back(JSONNode("FF::Node_Subclass", abi::__cxa_demangle(typeid(*tst).name(), 0,0,&status ))); if(n1.type()==JSON_NULL){ std::cout<<"null"<<std::endl; } JSONNode n2 (JSON_NODE); n2.set_name("Child1"); n2.push_back(JSONNode("id",1)); n.set_name("Parrent"); n.push_back(n2); JSONNode::iterator it =n.find_nocase("String Node"); if(it->as_string()=="-1"){std::cout<<it->as_int()<<std::endl;} it->as_int()!=-1 ? (std::cout<< "it is"<<std::endl) : (std::cout<<"Mapper Warning: processor id is -1"<<std::endl); if (n.at("String Node")==""){ std::cout<<"ha ha ha"<<std::endl; } std::cout<< "This is the name: "<<n.name()<<std::endl; n.at("String Node")=""; bool x =true; n.push_back(JSONNode("MyBOOLNODE", x)); n["String Node"]=x; //n.erase(n.find_nocase("String Node")); write_formatted(n1, "out1.json"); write_formatted(n, "out.json"); JSONNode::const_iterator i =n.find_nocase("ArrayOfNumbers"); std::string strLowerCase= "ARRAYOfNUMbers"; std::string myTest= "ff::ff_farm<adaptive_loadbalancer, ff::ff_gatherer>"; std::transform(myTest.begin(), myTest.end(), myTest.begin(), ::tolower); std::size_t found = myTest.find("adaptive_loadbalancer"); if (found!=std::string::npos) std::cout << "first 'needle' found at: " << found << '\n'; std::cout<< "here it is: " << myTest<< std::endl; JSONNode n_ar = n.at("ArrayOfNumbers"); std::cout<<"here :"<<n_ar[0].as_int()<< std::endl; // if (0 == strcasecmp("hello", "HELLO")) if(strcasecmp((i->name()).c_str(), strLowerCase.c_str()) == 0) //if(!(n2.empty())) std::cout<<"haha"<<i->size()<<std::endl; std::cout<<i->name()<<std::endl; std::cout<<((i->as_array()).begin()+1)->as_int()<<std::endl; std::cout<<((i->as_array()).at(1)).as_int()<<std::endl; std::cout<<((i->as_array())[1]).as_int()<<std::endl; //std::cout<<i->as_string()<<std::endl; //JSONNode c(JSON_ARRAY); //c=i->as_array(); //JSONNode nk= c.at(0); //JSONNode::const_iterator it = c.begin(); //std::cout <<nk.as_int()<<std::endl; return 0; }
int load_file(const string &filename, uid_user_map_t &uum, vector<msg_t> &msg_vec, log_t *log) { ifstream ifile; string line; string content; string home; long uid; int num = 0; ifile.open(filename.c_str()); if (ifile.is_open()) { while (getline(ifile, line)) { msg_t one_msg; user_t one_user = {-1, "", ""}; JSONNode node = libjson::parse(line); JSONNode::const_iterator jit = node.begin(); while (jit != node.end()) { string name = (string)jit->name(); if (name == "id") { one_msg.mid = atol(jit->as_string().c_str()); } else if (name == "user_id") { uid = atol(jit->as_string().c_str()); one_user.uid = uid; one_msg.uid = uid; } else if (name == "user_name") { one_user.name = jit->as_string(); } else if (name == "location") { one_user.home = jit->as_string(); } else if (name == "text") { one_msg.content = jit->as_string(); } ++jit; } check_user(one_user, uum); msg_vec.push_back(one_msg); ++num; } ifile.close(); } else { error(log, "open raw file %s error", filename.c_str()); } return num; }
const vector<uint64_t> JSONModelGetter::operator()(const string &rel_key){ vector<uint64_t> ret; JSONNode::const_iterator it = data->find(rel_key); if(it==data->end()){//||it->type()!=JSON_ARRAY) { return ret; } JSONNode fns_node = it->as_array(); if(fns_node.size()>0){ JSONNode::const_iterator stit = fns_node.begin(); while(stit!=fns_node.end()){ uint64_t fn = 0UL; if(stit->type()==JSON_NUMBER){ fn = stit->as_int(); }else if(it->type()==JSON_STRING){ string fs = it->as_string(); fn = strtoul(fs.c_str(), NULL, 10); } ret.push_back(fn); ++stit; } } return ret; }
/// Callback for the receiving loop when receiving valid json /// void SbrioDriver::_update_state(JSONNode& node, void* id) { SbrioDriver * driver_pointer = static_cast<SbrioDriver*>(id); // We got a node, get the name of the root node JSONNode::const_iterator root_iter = node.begin(); // Maybe there is no root. if (root_iter == node.end()) return; std::string root_name = root_iter->name(); boost::regex expression("(.*)_names"); boost::smatch regex_result; // Handle initialization messages. if(boost::regex_match(root_name, regex_result, expression)) { driver_pointer->_root_header = regex_result[1]; // If the sbRIO has already reported its names, we wil disregard it. if (! driver_pointer->initialized()) { JSONNode::const_iterator name_type = root_iter->begin(); for(; name_type != root_iter->end(); ++name_type) { // Get the position names of the joint (and initialize its velocity and effort). if (name_type->name() == "position") { boost::lock_guard<boost::mutex> state_guard(driver_pointer->state_mutex); for(JSONNode::const_iterator name_array = name_type->begin(); name_array != name_type->end(); ++name_array) { std::string joint_name = name_array->as_string(); driver_pointer->joint_names.push_back(joint_name); driver_pointer->joint_positions.push_back(0.0); driver_pointer->joint_velocities.push_back(0.0); driver_pointer->joint_efforts.push_back(0.0); driver_pointer->joint_setpoints.push_back(0.0); driver_pointer->joint_setpoints_mask.push_back(false); } } // Get the names of the joints that take setpoints, and enable them in the mask. if (name_type->name() == "setpoints") { boost::lock_guard<boost::mutex> state_guard(driver_pointer->state_mutex); for(JSONNode::const_iterator name_array = name_type->begin(); name_array != name_type->end(); ++name_array) { std::string joint_name = name_array->as_string(); for(size_t i = 0; i < driver_pointer->joint_names.size(); ++i) { if (joint_name == driver_pointer->joint_names[i]) { driver_pointer->joint_setpoints_mask[i] = true; break; } } } } // Get the names of the motors, for active state and enabling. if (name_type->name() == "motoractive") { boost::lock_guard<boost::mutex> state_guard(driver_pointer->state_mutex); for(JSONNode::const_iterator name_array = name_type->begin(); name_array != name_type->end(); ++name_array) { std::string motor_name = name_array->as_string(); driver_pointer->motor_names.push_back(motor_name); driver_pointer->motors_active.push_back(false); driver_pointer->motors_enabled.push_back(false); } } } driver_pointer->_initialized = true; } } // Handle state updates. else { boost::lock_guard<boost::mutex> state_guard(driver_pointer->state_mutex); JSONNode::const_iterator name_type = root_iter->begin(); for(; name_type != root_iter->end(); ++name_type) { std::string type = name_type->name(); if (type == "position") { size_t i = 0; for(JSONNode::const_iterator pos = name_type->begin(); pos != name_type->end(); ++pos) { double joint_pos = pos->as_float(); driver_pointer->joint_positions[i++] = joint_pos; } } else if (type == "velocity") { size_t i = 0; for(JSONNode::const_iterator vel = name_type->begin(); vel != name_type->end(); ++vel) { double joint_vel = vel->as_float(); driver_pointer->joint_velocities[i++] = joint_vel; } } else if (type == "effort") { size_t i = 0; for(JSONNode::const_iterator eff = name_type->begin(); eff != name_type->end(); ++eff) { double joint_eff = eff->as_float(); driver_pointer->joint_efforts[i++] = joint_eff; } } else if (type == "motoractive") { size_t i = 0; for(JSONNode::const_iterator act = name_type->begin(); act != name_type->end(); ++act) { bool motor_act = act->as_bool(); driver_pointer->motors_active[i++] = motor_act; } } } } }
bool GameMapEncounterAreaParser::Parse(std::string json, GameMapEncounterArea *encounterArea) { JSONNode assetListNode = libjson::parse(json); JSONNode::const_iterator i = assetListNode.begin(); while (i != assetListNode.end()) { if (i->name() == "mobs" && i->type() == JSON_ARRAY) { this->logger->debug() << "parsing mobs"; JSONNode::const_iterator j = i->begin(); while (j != i->end()) { if (j->type() == JSON_NODE) { JSONNode::const_iterator k = j->begin(); while (k != j->end()) { if (k->name() == "enemies") { this->logger->debug() << "parsing enemies for mob"; JSONNode::const_iterator l = k->begin(); std::string r = ""; std::vector<std::string> mob; while (l != k->end()) { this->logger->debug() << std::setfill ('0') << std::setw(sizeof(unsigned char)*2) << std::hex << l->type(); if (l->type() == JSON_STRING) { r += l->as_string() + ", "; mob.push_back(l->as_string()); } l++; } this->logger->debug() << "parsed mob [" << r << "]"; encounterArea->mobs.push_back(mob); } k++; } } j++; } } i++; } return true; }
Handle<Object> AtJsonParser::parse( const JSONNode &n ) { Isolate* isolate = Isolate::GetCurrent(); Handle<Object> ret = Object::New( isolate ); JSONNode::const_iterator i = n.begin(); while ( i != n.end() ) { std::string node_name = i->name(); if ( node_name == "serverTime" || node_name == "response" || node_name == "data" || node_name == "tick" || node_name == "ATBarHistory" || node_name == "ATSymbol" || node_name == "ATLoginResponse" || node_name == "time" || node_name == "open" || node_name == "high" || node_name == "low" || node_name == "close" || node_name == "ATTickHistory" || node_name == "offsetDatabaseDate" || node_name == "tradeLastPrice" || node_name == "quoteBidPrice" || node_name == "quoteAskPrice" || node_name == "ATMarketMoversDb" || node_name == "recordSymbol" || node_name == "itemSymbol" || node_name == "itemLastPrice" || node_name == "ATQuoteDb" || node_name == "priceData" || node_name == "dateTime" || node_name == "ATQuoteStream" || node_name == "lastPrice" || node_name == "bidPrice" || node_name == "askPrice" || node_name == "prevClose" || node_name == "afterMarketClose" || node_name == "lastUpdateTime" || node_name == "marketMovers" || node_name == "closePrice" || node_name == "lastDateTime" || node_name == "beginDateTime" || node_name == "endDateTime" ) { ret->Set( String::NewFromUtf8( isolate, node_name.c_str() ), parse( *i ) ); } else if ( filterAsString( node_name ) ) { ret->Set( String::NewFromUtf8( isolate, node_name.c_str() ), String::NewFromUtf8( isolate, i->as_string().c_str() ) ); } else if ( filterAsNumber( node_name ) ) { ret->Set( String::NewFromUtf8( isolate, node_name.c_str() ), Number::New( isolate, i->as_float() ) ); } else if ( filterAsInteger( node_name ) ) { ret->Set( String::NewFromUtf8( isolate, node_name.c_str() ), Integer::New( isolate, i->as_int() ) ); } else if ( filterAsBoolean( node_name ) ) { ret->Set( String::NewFromUtf8( isolate, node_name.c_str() ), Boolean::New( isolate, i->as_bool() ) ); } else if ( i->type() == JSON_ARRAY ) { JSONNode::const_iterator j = i->begin(); std::vector< Handle<Object> > vec; while ( j != i->end() ) { vec.push_back( parse( *j ) ); ++j; } Handle<Array> arr = Array::New( isolate, vec.size() ); for ( size_t idx = 0; idx < vec.size(); idx++ ) { arr->Set( idx, vec[idx] ); } ret->Set( String::NewFromUtf8( isolate, node_name.c_str() ), arr ); } ++i; } return ret; }
ResponseCode UpdateRepoTagOfTarball(std::string pathTarball, std::string repo, std::string tag, std::string &idImage) { TAR *tar = NULL; int ret = 0; int th_found = 0; int exitcode = 0; // char tmp_filepath[] = P_tmpdir "/libtar-tmpfile-XXXXXX"; //gen path to upload image char* tmp_imagepath = tempnam (FileUtils::GetPathDir(pathTarball).c_str(), "imageDirTmp_"); std::string pathTmpDir = tmp_imagepath; free(tmp_imagepath); std::cout << "path tmp dir: " << pathTmpDir << std::endl; int tmp_fd = -1; ret = tar_open(&tar, (char*)pathTarball.c_str(), NULL, O_RDONLY, 0, 0); if (ret != 0) { fprintf(stdout, "Fail to open file: %s\n", pathTarball.c_str()); // return FILE_ACTION_ERROR; exitcode = 2; } if (exitcode == 0) { if (tar_extract_all(tar, (char*)pathTmpDir.c_str()) != 0) { fprintf(stderr, "Fail to extract file: %s\n", pathTarball.c_str()); exitcode = 2; } } if (exitcode == 0) { ret = tar_close(tar); if (ret != 0) { perror("Failed to close tar file."); exitcode = 2; } tar = NULL; } //Modify repository file if (exitcode == 0) { char buf[BUFSIZ]; ssize_t n_buf = 0; FILE *tmpfile = NULL; std::ifstream in((pathTmpDir + "/" + REPOSITORIES_FILE).c_str(), std::ios::binary); std::string info((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>()); JSONNode n; try { n = libjson::parse(info); } catch(const std::invalid_argument& e) { std::cerr << "Invalid argument: " << e.what() << '\n'; // return FILE_ACTION_ERROR; exitcode = 1; } if(exitcode == 0){ JSONNode::const_iterator i = n.begin(); //if (i != n.end() && i -> name() == TAG_SERVICE_STR && i -> type() != JSON_ARRAY && i -> type() != JSON_NODE) if (i != n.end() && i -> type() == JSON_NODE){ JSONNode tag_id_node = i->as_node(); i = tag_id_node.begin(); if (i != n.end() && i -> type() != JSON_ARRAY && i -> type() != JSON_NODE){ idImage = i->as_string(); }else{ std::cout << "Tarball format error.\n"; // return FILE_ACTION_ERROR; exitcode = 1; } } }else{ std::cout << "Tarball format error.\n"; // return FILE_ACTION_ERROR; exitcode = 1; } } if(exitcode == 0){ JSONNode newRepoNode(JSON_NODE); newRepoNode.set_name(repo); newRepoNode.push_back(JSONNode(tag, idImage)); JSONNode newNode; newNode.push_back(newRepoNode); std::string content = newNode.write(); FILE * pFile; if (exitcode == 0) { pFile = fopen ((pathTmpDir + "/" + REPOSITORIES_FILE).c_str() , "w"); if (pFile == NULL) { printf("Error opening file %s\n", (pathTmpDir + "/" + REPOSITORIES_FILE).c_str()); // return FILE_ACTION_ERROR; exitcode = 1; } } if (exitcode == 0) { fwrite (content.c_str() , sizeof(char), content.size(), pFile); fclose (pFile); printf("content tmp file: %s\n", content.c_str()); } } if (exitcode == 0) { remove (pathTarball.c_str()); ret = tar_open(&tar, (char*)pathTarball.c_str(), NULL, O_WRONLY | O_CREAT, 0600, 0); if (ret != 0) { fprintf(stderr, "Fail to open file: %s\n", pathTarball.c_str()); // return FILE_ACTION_ERROR; exitcode = 2; } if (exitcode == 0) { if (tar_append_tree(tar, (char*)pathTmpDir.c_str(), "") != 0) { fprintf(stderr, "Fail to compress file: %s\n", pathTarball.c_str()); // return FILE_ACTION_ERROR; exitcode = 2; } } if (exitcode == 0) { ret = tar_close(tar); if (ret != 0) { perror("Failed to close tar file."); exitcode = 2; } else { tar = NULL; } } } std::cout << "delete_folder_tree: " << pathTmpDir.c_str() << std::endl; if (FileUtils::delete_folder_tree(pathTmpDir.c_str())) { fprintf(stderr, "Fail to delete temp dir: %s\n", pathTmpDir.c_str()); } if (exitcode == 0) { return FILE_ACTION_SUCCESS; } else if (exitcode == 1) { return FILE_ACTION_ERROR; } else { return DATA_ERROR; } }