int array_to_json_reduction (stinger_t * S, rapidjson::Value& rtn, rapidjson::MemoryPoolAllocator<rapidjson::CrtAllocator>& allocator, const char * description_string, uint8_t * data, const char * algorithm_name ) { size_t off = 0; size_t len = strlen(description_string); char * tmp = (char *) xmalloc ((len+1) * sizeof(char)); strcpy(tmp, description_string); rapidjson::Value fields (rapidjson::kArrayType); /* the description string is space-delimited */ char * placeholder; char * ptr = strtok_r (tmp, " ", &placeholder); /* skip the formatting */ char * pch = strtok_r (NULL, " ", &placeholder); if (pch == NULL) { LOG_W_A ("pch is null :: %s :: %s", description_string, algorithm_name); } int64_t start = 0; int64_t end = S->max_nv; while (pch != NULL) { size_t pch_len = strlen(pch); switch (description_string[off]) { case 'f': { rapidjson::Value reduction (rapidjson::kObjectType); rapidjson::Value reduction_name, reduction_value; double sum = 0.0; for (int64_t i = start; i < end; i++) { double val = (double)((float *) data)[i]; if (val > 0.0) sum += val; } reduction_value.SetDouble(sum); reduction_name.SetString(pch, pch_len, allocator); reduction.AddMember("field", reduction_name, allocator); reduction.AddMember("value", reduction_value, allocator); fields.PushBack(reduction, allocator); break; } case 'd': { rapidjson::Value reduction (rapidjson::kObjectType); rapidjson::Value reduction_name, reduction_value; double sum = 0.0; for (int64_t i = start; i < end; i++) { double val = (double)((double *) data)[i]; if (val > 0.0) sum += val; } reduction_value.SetDouble(sum); reduction_name.SetString(pch, pch_len, allocator); reduction.AddMember("field", reduction_name, allocator); reduction.AddMember("value", reduction_value, allocator); fields.PushBack(reduction, allocator); break; } case 'i': { rapidjson::Value reduction (rapidjson::kObjectType); rapidjson::Value reduction_name, reduction_value; int64_t sum = 0; for (int64_t i = start; i < end; i++) { int64_t val = (int64_t)((int32_t *) data)[i]; if (val > 0) sum += val; } reduction_value.SetInt64(sum); reduction_name.SetString(pch, pch_len, allocator); reduction.AddMember("field", reduction_name, allocator); reduction.AddMember("value", reduction_value, allocator); fields.PushBack(reduction, allocator); break; } case 'l': { rapidjson::Value reduction (rapidjson::kObjectType); rapidjson::Value reduction_name, reduction_value; int64_t sum = 0; for (int64_t i = start; i < end; i++) { int64_t val = (int64_t)((int64_t *) data)[i]; if (val > 0) sum += val; } reduction_value.SetInt64(sum); reduction_name.SetString(pch, pch_len, allocator); reduction.AddMember("field", reduction_name, allocator); reduction.AddMember("value", reduction_value, allocator); fields.PushBack(reduction, allocator); break; } case 'b': { rapidjson::Value reduction (rapidjson::kObjectType); rapidjson::Value reduction_name, reduction_value; int64_t sum = 0; for (int64_t i = start; i < end; i++) { int64_t val = (int64_t)((uint8_t *) data)[i]; if (val > 0) sum += val; } reduction_value.SetInt64(sum); reduction_name.SetString(pch, pch_len, allocator); reduction.AddMember("field", reduction_name, allocator); reduction.AddMember("value", reduction_value, allocator); fields.PushBack(reduction, allocator); break; } default: LOG_W_A("Umm...what letter was that?\ndescription_string: %s", description_string); return json_rpc_error(-32603, rtn, allocator); } switch (description_string[off]) { case 'f': data += (S->max_nv * sizeof(float)); break; case 'd': data += (S->max_nv * sizeof(double)); break; case 'i': data += (S->max_nv * sizeof(int32_t)); break; case 'l': data += (S->max_nv * sizeof(int64_t)); break; case 'b': data += (S->max_nv * sizeof(uint8_t)); break; default: LOG_W_A("Umm...what letter was that?\ndescription_string: %s", description_string); return json_rpc_error(-32603, rtn, allocator); } off++; pch = strtok_r (NULL, " ", &placeholder); } free(tmp); rtn.AddMember(algorithm_name, fields, allocator); return 0; }
void ConvertToMsgPack(const rapidjson::Value& json, msgpack::object& object, msgpack::zone& zone) { switch (json.GetType()) { case rapidjson::kFalseType: object = false; break; case rapidjson::kTrueType: object = true; break; case rapidjson::kNumberType: { if (json.IsInt()) { object = json.GetInt(); } else if (json.IsUint()) { object = json.GetUint(); } else if (json.IsInt64()) { object = json.GetInt64(); } else if (json.IsUint64()) { object = json.GetUint64(); } else if (json.IsDouble()) { object = json.GetDouble(); } break; } case rapidjson::kStringType: // we allocate with 'zone', otherwise the std::string's raw pointer gets used, which won't work as it gets destructed later on object = msgpack::object(std::string(json.GetString(), json.GetStringLength()), zone); break; case rapidjson::kObjectType: { std::map<std::string, msgpack::object> list; for (auto it = json.MemberBegin(); it != json.MemberEnd(); it++) { msgpack::object newObject; ConvertToMsgPack(it->value, newObject, zone); list.insert({ it->name.GetString(), newObject }); } object = msgpack::object(list, zone); break; } case rapidjson::kArrayType: { std::vector<msgpack::object> list; for (auto it = json.Begin(); it != json.End(); it++) { msgpack::object newObject; ConvertToMsgPack(*it, newObject, zone); list.push_back(newObject); } object = msgpack::object(list, zone); break; } default: object = msgpack::type::nil(); break; } }
inline void push(lua_State* L, const rapidjson::Value& v) { ToLuaHandler handler(L); v.Accept(handler); }
void favorite::serialize(rapidjson::Value& _node, rapidjson_allocator& _a) { _node.AddMember("aimId", get_aimid(), _a); _node.AddMember("time", time_, _a); }
void ConvertToJSON(const msgpack::object& object, rapidjson::Value& value, rapidjson::MemoryPoolAllocator<>& allocator) { switch (object.type) { case msgpack::type::BOOLEAN: value.SetBool(object.as<bool>()); break; case msgpack::type::POSITIVE_INTEGER: case msgpack::type::NEGATIVE_INTEGER: value.SetInt(object.as<int>()); break; case msgpack::type::FLOAT: value.SetDouble(object.as<double>()); break; case msgpack::type::STR: { std::string string = object.as<std::string>(); value.SetString(string.c_str(), string.size(), allocator); break; } case msgpack::type::ARRAY: { auto list = object.as<std::vector<msgpack::object>>(); value.SetArray(); for (auto& entry : list) { rapidjson::Value inValue; ConvertToJSON(entry, inValue, allocator); value.PushBack(inValue, allocator); } break; } case msgpack::type::MAP: { auto list = object.as<std::map<std::string, msgpack::object>>(); value.SetObject(); for (auto& entry : list) { rapidjson::Value inValue; ConvertToJSON(entry.second, inValue, allocator); rapidjson::Value name; name.SetString(entry.first.c_str(), entry.first.size(), allocator); value.AddMember(name, inValue, allocator); } break; } default: value.SetNull(); break; } }
bool fromJson(const rapidjson::Value &v, Mat4f &dst) { if (v.IsArray()) { ASSERT(v.Size() == 16, "Cannot convert Json Array to 4x4 Matrix: Invalid size"); for (unsigned i = 0; i < 16; ++i) dst[i] = as<float>(v[i]); return true; } else if (v.IsObject()) { Vec3f x(1.0f, 0.0f, 0.0f); Vec3f y(0.0f, 1.0f, 0.0f); Vec3f z(0.0f, 0.0f, 1.0f); Vec3f pos(0.0f); fromJson(v, "position", pos); bool explicitX = false, explicitY = false, explicitZ = false; Vec3f lookAt; if (fromJson(v, "look_at", lookAt)) { z = lookAt - pos; explicitZ = true; } explicitY = fromJson(v, "up", y); explicitX = fromJson(v, "x_axis", x) || explicitX; explicitY = fromJson(v, "y_axis", y) || explicitY; explicitZ = fromJson(v, "z_axis", z) || explicitZ; int id = (explicitZ ? 4 : 0) + (explicitY ? 2 : 0) + (explicitX ? 1 : 0); switch (id) { case 0: gramSchmidt(z, y, x); break; case 1: gramSchmidt(x, z, y); break; case 2: gramSchmidt(y, z, x); break; case 3: gramSchmidt(y, x, z); break; case 4: gramSchmidt(z, y, x); break; case 5: gramSchmidt(z, x, y); break; case 6: gramSchmidt(z, y, x); break; case 7: gramSchmidt(z, y, x); break; } if (x.cross(y).dot(z) < 0.0f) { if (!explicitX) x = -x; else if (!explicitY) y = -y; else z = -z; } Vec3f scale; if (fromJson(v, "scale", scale)) { x *= scale.x(); y *= scale.y(); z *= scale.z(); } Vec3f rot; if (fromJson(v, "rotation", rot)) { Mat4f tform = Mat4f::rotYXZ(rot); x = tform*x; y = tform*y; z = tform*z; } dst = Mat4f( x[0], y[0], z[0], pos[0], x[1], y[1], z[1], pos[1], x[2], y[2], z[2], pos[2], 0.0f, 0.0f, 0.0f, 1.0f ); return true; } return false; }
// Create an ACR message from a JSON descriptor. Most AVPs are auto-created from the // contents parameter which should be a JSON object with keys named after AVPs. For example // this object could be the "event" part of the original HTTP request received by Ralf. AccountingRequest::AccountingRequest(const Dictionary* dict, Diameter::Stack* diameter_stack, const std::string& session_id, const std::string& dest_host, const std::string& dest_realm, const uint32_t& record_number, const rapidjson::Value& contents) : Diameter::Message(dict, dict->ACCOUNTING_REQUEST, diameter_stack) { LOG_DEBUG("Building an Accounting-Request"); // Fill in the default fields if (session_id == "") { add_new_session_id(); } else { add_session_id(session_id); } add_origin(); add_app_id(Dictionary::Application::ACCT, dict->RF); // Fill in contributed fields Diameter::Dictionary::AVP dest_host_dict("Destination-Host"); Diameter::AVP dest_host_avp(dest_host_dict); add(dest_host_avp.val_str(dest_host)); Diameter::Dictionary::AVP dest_realm_dict("Destination-Realm"); Diameter::AVP dest_realm_avp(dest_realm_dict); add(dest_realm_avp.val_str(dest_realm)); Diameter::Dictionary::AVP record_number_dict("Accounting-Record-Number"); Diameter::AVP record_number_avp(record_number_dict); add(record_number_avp.val_i32(record_number)); if (contents.GetType() != rapidjson::kObjectType) { LOG_ERROR("Cannot build ACR from JSON type %d", contents.GetType()); return; } // Fill in the dynamic fields for (rapidjson::Value::ConstMemberIterator it = contents.MemberBegin(); it != contents.MemberEnd(); ++it) { try { switch (it->value.GetType()) { case rapidjson::kFalseType: case rapidjson::kTrueType: case rapidjson::kNullType: LOG_ERROR("Invalid format (true/false) in JSON block, ignoring"); continue; case rapidjson::kStringType: case rapidjson::kNumberType: case rapidjson::kObjectType: { Diameter::Dictionary::AVP new_dict(VENDORS, it->name.GetString()); Diameter::AVP avp(new_dict); add(avp.val_json(VENDORS, new_dict, it->value)); } break; case rapidjson::kArrayType: for (rapidjson::Value::ConstValueIterator array_iter = it->value.Begin(); array_iter != it->value.End(); ++array_iter) { Diameter::Dictionary::AVP new_dict(VENDORS, it->name.GetString()); Diameter::AVP avp(new_dict); add(avp.val_json(VENDORS, new_dict, *array_iter)); } break; } } catch (Diameter::Stack::Exception e) { LOG_WARNING("AVP %s not recognised, ignoring", it->name.GetString()); } } }
template<> inline unsigned conf_getter<unsigned>(const rapidjson::Value & value) { return value.GetUint(); }
template<> inline double conf_getter<double>(const rapidjson::Value & value) { return value.GetDouble(); }
template<> inline int conf_getter<int>(const rapidjson::Value & value) { return value.GetInt(); }
template<> inline std::string conf_getter<std::string>(const rapidjson::Value & value) { return value.GetString(); }
template<> inline bool conf_getter<bool>(const rapidjson::Value & value) { return value.GetBool(); }
void NodeCom::initWithMap(rapidjson::Value& value) { auto visibleSize=Director::getInstance()->getVisibleSize(); node=cocos2d::Node::create(); if (value.HasMember("contentSize")) { auto size=cocos2d::SizeFromString(value["contentSize"].GetString()); if (size.width<0) size.width=visibleSize.width; if (size.height<0) size.height=visibleSize.height; node->setContentSize(size); } else { node->setContentSize(visibleSize); } if (value.HasMember("anchorPoint")) { node->setAnchorPoint(cocos2d::PointFromString(value["anchorPoint"].GetString())); } cocos2d::Point position=value.HasMember("position")?cocos2d::PointFromString(value["position"].GetString()):cocos2d::Point::ZERO; if (value.HasMember("anchor")) { node->setPosition(getRealPosition(cocos2d::Director::getInstance()->getVisibleSize(), position, cocos2d::PointFromString(value["anchor"].GetString()))); } else if (value.HasMember("position")) { node->setPosition(cocos2d::PointFromString(value["position"].GetString())); } if (value.HasMember("Node")) { int count=value["Node"].Size(); for (int i=0; i<count; i++) { rapidjson::Value& nodeValue=value["Node"][i]; if (!nodeValue.IsNull()&&nodeValue.HasMember("type")) { const char* type=nodeValue["type"].GetString(); cocos2d::Node* child=nullptr; if (strcmp("Label", type)==0) { child=initLabel(nodeValue); } else if (strcmp("Sprite", type)==0) { child=initSprite(nodeValue); } else if (strcmp("Layer", type)==0) { child=initLayer(nodeValue); } else if (strcmp("Button", type)==0) { child=initButton(nodeValue); } else if (strcmp("TableView", type)==0){ child=initTable(nodeValue); } else if (strcmp("ProgressTimer", type)==0){ child=initTimer(nodeValue); } if (child!=nullptr) { node->addChild(child); if (nodeValue.HasMember("name")) { const char* name= nodeValue["name"].GetString(); __nodeNames.insert(std::make_pair(name, child)); } if (nodeValue.HasMember("scale")) { cocos2d::Point point=cocos2d::PointFromString(nodeValue["scale"].GetString()); child->setScale(point.x, point.y); } if (nodeValue.HasMember("position")) { child->setPosition(cocos2d::PointFromString(nodeValue["position"].GetString())); } if (nodeValue.HasMember("anchorPoint")) { child->setAnchorPoint(cocos2d::PointFromString(nodeValue["anchorPoint"].GetString())); } if (nodeValue.HasMember("localZOrder")) { child->setLocalZOrder(nodeValue["localZOrder"].GetInt()); } if (nodeValue.HasMember("globalOrder")) { child->setGlobalZOrder(nodeValue["globalOrder"].GetInt()); } if (nodeValue.HasMember("visible")) { child->setVisible(nodeValue["visible"].GetBool()); } if (nodeValue.HasMember("tag")) { child->setTag(nodeValue["tag"].GetInt()); } //如果声明了anchor,则按照新的规则布局 cocos2d::Point position1=nodeValue.HasMember("position")? cocos2d::PointFromString(nodeValue["position"].GetString()):cocos2d::Point::ZERO; if (nodeValue.HasMember("anchor")) { child->setPosition(getRealPosition(node->getContentSize(), position1, cocos2d::PointFromString(nodeValue["anchor"].GetString()))); } else if (nodeValue.HasMember("position")) { child->setPosition(position1); } } } } } }
void jsonifyModuleType(const ModuleType& moduleType, rapidjson::Value& moduleTypeValue, rapidjson::Document& document){ //TODO assert moduleType.isComposite moduleTypeValue.SetObject(); moduleTypeValue.AddMember("name", moduleType.getName().c_str(), document.GetAllocator()); moduleTypeValue.AddMember("description", moduleType.getDescription().c_str(), document.GetAllocator()); //handle inputs rapidjson::Value inputs; inputs.SetArray(); for(unsigned int i=0; i<moduleType.numInputs(); ++i){ const ModuleInput* input = moduleType.getInput(i); rapidjson::Value inputValue; inputValue.SetObject(); inputValue.AddMember("name", input->getName().c_str(), document.GetAllocator()); int dimensionality = input->getSignalType().dimensionality; std::stringstream ss; ss << dimensionality << "f"; rapidjson::Value typeValue(ss.str().c_str(), document.GetAllocator()); inputValue.AddMember("type", typeValue, document.GetAllocator()); inputs.PushBack(inputValue, document.GetAllocator()); } moduleTypeValue.AddMember("inputs", inputs, document.GetAllocator()); //handle outputs rapidjson::Value outputs; outputs.SetArray(); for(unsigned int i=0; i<moduleType.numOutputs(); ++i){ const ModuleOutput* output = moduleType.getOutput(i); const Module* outputsModule = moduleType.getGraph()->getModule("outputs"); rapidjson::Value outputValue; outputValue.SetObject(); outputValue.AddMember("name", output->getName().c_str(), document.GetAllocator()); auto inputLink = outputsModule->getInput(i); auto outputLink = outputsModule->getInput(i)->getOutputLink(); if(outputLink!=nullptr){ std::string sourceString = outputLink->getOwner().getName() + "." + outputLink->getModuleOutput().getName(); rapidjson::Value sourceStringValue(sourceString.c_str(),document.GetAllocator()); outputValue.AddMember("source", sourceStringValue, document.GetAllocator()); } else { rapidjson::Value vectorValue; vectorValue.SetArray(); auto unlinkedValue = inputLink->getUnlinkedValue(); for(int j=0; j<unlinkedValue.getSignalType().dimensionality; ++j){ vectorValue.PushBack(unlinkedValue[j], document.GetAllocator()); } outputValue.AddMember("source", vectorValue, document.GetAllocator()); } outputs.PushBack(outputValue, document.GetAllocator()); } moduleTypeValue.AddMember("outputs", outputs, document.GetAllocator()); //handle internal modules rapidjson::Value modulesValue; modulesValue.SetArray(); auto graph = moduleType.getGraph(); graph->traverseModulesTopological([&](const Module& module){ //skip input/output modules if(module.getType().isGraphInput() || module.getType().isGraphOutput())return; rapidjson::Value moduleValue; jsonifyModule(module, moduleValue, document); modulesValue.PushBack(moduleValue, document.GetAllocator()); }); moduleTypeValue.AddMember("modules", modulesValue, document.GetAllocator()); }
bool RequestMessage::parsePayload(rapidjson::Value& value, IceServalBridge* bridge) { this->requests.clear(); if (false == value.IsArray()) { _log->error("Payload could not be parsed: Is not an array"); return false; } std::string entity, entityType, scope, rep, relatedEntity; int count = 0; for (auto it = value.Begin(); it != value.End(); ++it) { if (false == it->IsArray()) { _log->error("Payload could not be parsed: Id is not an array"); return false; } count = 0; for (auto it2 = it->Begin(); it2 != it->End(); ++it2) { if (false == it2->IsString()) { _log->error("Payload could not be parsed: Field is not a string"); return false; } switch(count) { case 0: entity = it2->GetString(); break; case 1: entityType = it2->GetString(); break; case 2: scope = it2->GetString(); break; case 3: rep = it2->GetString(); break; case 4: relatedEntity = it2->GetString(); break; } ++count; } if (count != 5) { _log->error("Payload could not be parsed: Wrong number of fields for offer"); return false; } auto spec = std::make_shared<InformationSpecification>(entity, entityType, scope, rep, relatedEntity); this->requests.push_back(spec); } return true; }
virtual bool initialize(const rapidjson::Value &config) { daemonize(); if (!m_elliptics.initialize(config, logger())) return false; m_async.initialize(logger()); if (config.HasMember("noauth")) { m_noauth_allowed = std::string(config["noauth"].GetString()) == "allowed"; } if (config.HasMember("cache")) { m_cache = std::make_shared<rift::cache>(); if (!m_cache->initialize(config["cache"], m_elliptics.node(), logger(), &m_async, m_elliptics.metadata_groups())) return false; } if (config.HasMember("bucket")) { m_bucket = std::make_shared<rift::bucket>(); if (!m_bucket->initialize(config["bucket"], m_elliptics, &m_async)) return false; } else { m_noauth_allowed = true; } if (config.HasMember("redirect-port")) { m_redirect_port = config["redirect-port"].GetInt(); } else { m_redirect_port = -1; } if (config.HasMember("https")) { m_secured_http = config["https"].GetBool(); } else { m_secured_http = false; } on<rift::index::on_update<example_server>>( options::exact_match("/update"), options::methods("POST") ); on<rift::index::on_find<example_server>>( options::exact_match("/find"), options::methods("GET") ); on<rift::io::on_redirectable_get<example_server>>( options::exact_match("/redirect"), options::methods("GET") ); on<rift::io::on_get<example_server>>( options::exact_match("/get"), options::methods("GET") ); on<rift::io::on_buffered_get<example_server>>( options::exact_match("/get-big"), options::methods("GET") ); on<rift::io::on_upload<example_server>>( options::exact_match("/upload"), options::methods("POST") ); on<rift::io::on_buffered_upload<example_server>>( options::exact_match("/upload-big"), options::methods("POST") ); on<rift::io::on_download_info<example_server>>( options::exact_match("/download-info"), options::methods("GET") ); on<rift::common::on_ping<example_server>>( options::exact_match("/ping"), options::methods("GET") ); on<rift::common::on_echo<example_server>>( options::exact_match("/echo"), options::methods("GET") ); return true; }
Item::Item(const rapidjson::Value &json) : location_(ItemLocation(json)), name_(correct_name(json["name"].GetString())), typeLine_(correct_name(json["typeLine"].GetString())), corrupted_(json["corrupted"].GetBool()), w_(json["w"].GetInt()), h_(json["h"].GetInt()), frameType_(json["frameType"].GetInt()), icon_(json["icon"].GetString()), sockets_cnt_(0), links_cnt_(0), sockets_({ 0, 0, 0, 0 }), has_mtx_(false) { for (auto &mod_type : ITEM_MOD_TYPES) { text_mods_[mod_type] = std::vector<std::string>(); if (json.HasMember(mod_type.c_str())) { auto &mods = text_mods_[mod_type]; for (auto &mod : json[mod_type.c_str()]) mods.push_back(mod.GetString()); } } if (json.HasMember("properties")) { for (auto prop_it = json["properties"].Begin(); prop_it != json["properties"].End(); ++prop_it) { auto &prop = *prop_it; std::string name = prop["name"].GetString(); if (name == "Уровень карты") name = "Уровень"; if (name == "Урон от стихий") { for (auto value_it = prop["values"].Begin(); value_it != prop["values"].End(); ++value_it) elemental_damage_.push_back(std::make_pair((*value_it)[0].GetString(), (*value_it)[1].GetInt())); } else { if (prop["values"].Size()) properties_[name] = prop["values"][0][0].GetString(); } ItemProperty property; property.name = name; property.display_mode = prop["displayMode"].GetInt(); for (auto &value : prop["values"]) property.values.push_back(value[0].GetString()); text_properties_.push_back(property); } } if (json.HasMember("requirements")) { for (auto &req : json["requirements"]) { std::string name = req["name"].GetString(); std::string value = req["values"][0][0].GetString(); requirements_[name] = std::atoi(value.c_str()); text_requirements_.push_back({ name, value }); } } if (json.HasMember("sockets")) { ItemSocketGroup current_group = { 0, 0, 0, 0 }; sockets_cnt_ = json["sockets"].Size(); int counter = 0, prev_group = -1; for (auto &socket : json["sockets"]) { ItemSocket current_socket = { static_cast<unsigned char>(socket["group"].GetInt()), socket["attr"].GetString()[0] }; text_sockets_.push_back(current_socket); if (prev_group != current_socket.group) { counter = 0; socket_groups_.push_back(current_group); current_group = { 0, 0, 0, 0 }; } prev_group = current_socket.group; ++counter; links_cnt_ = std::max(links_cnt_, counter); switch (current_socket.attr) { case 'S': sockets_.r++; current_group.r++; break; case 'D': sockets_.g++; current_group.g++; break; case 'I': sockets_.b++; current_group.b++; break; case 'G': sockets_.w++; current_group.w++; break; } } socket_groups_.push_back(current_group); } std::string hashes[3]; for (int i = 0; i < 3; i++) { std::string unique(name_ + "~" + typeLine_ + "~"); if (i == 2) { // Strip off last "~" (a mistake from 0.3) unique = unique.substr(0, unique.length() - 1); } if (json.HasMember("explicitMods")) for (auto mod_it = json["explicitMods"].Begin(); mod_it != json["explicitMods"].End(); ++mod_it) unique += std::string(mod_it->GetString()) + "~"; if (json.HasMember("implicitMods")) for (auto mod_it = json["implicitMods"].Begin(); mod_it != json["implicitMods"].End(); ++mod_it) unique += std::string(mod_it->GetString()) + "~"; unique += item_unique_properties(json, "properties") + "~"; unique += item_unique_properties(json, "additionalProperties") + "~"; if (json.HasMember("sockets")) for (auto socket_it = json["sockets"].Begin(); socket_it != json["sockets"].End(); ++socket_it) unique += std::to_string((*socket_it)["group"].GetInt()) + "~" + (*socket_it)["attr"].GetString() + "~"; // This will only effect corrupted item's new hashes... if (i == 1 && corrupted()) unique += "corrupted"; hashes[i] = Util::Md5(unique); } old_hash_ = hashes[0]; hash_ = hashes[1]; broken_hash_ = hashes[2]; count_ = 1; if (properties_.find("Размер стопки") != properties_.end()) { std::string size = properties_["Размер стопки"]; if (size.find("/") != std::string::npos) { size = size.substr(0, size.find("/")); count_ = std::stoi(size); } } has_mtx_ = json.HasMember("cosmeticMods"); GenerateMods(json); }
cocos2d::Value JsonUtils::json2Value(rapidjson::Value &json) { JsonValueConverter converter; json.Accept(converter); return converter.getValue(); }
/*! * \brief Run servers by json configuration * * Example: * \code{.json} * { * "srw": true, * "path": "/tmp/elliptics-test", * "servers": [ * { * "group": 1, * "srw_config": "/tmp/srw.conf" * } * ] * } * \endcode * * Possible options are: * \li If \c srw is set to true elliptics will be started with Cocaine runtime. * \li All logs and blobs' data is written to \c path. * \li \c server is a list of key-value maps of servers configurations. Each entry \ * contains options which must overwrite default values in configuration file. */ static int run_servers(const rapidjson::Value &doc) { bool srw = false; #ifdef HAVE_COCAINE if (doc.HasMember("srw")) { if (!doc["srw"].IsBool()) { std::cout << "Field \"srw\" must be boolean" << std::endl; return 1; } srw = doc["srw"].GetBool(); } #else if (doc.HasMember("srw")) { std::cerr << "There is no srw support" << std::endl; return 1; } #endif if (!doc.HasMember("servers")) { std::cerr << "Field \"servers\" is missed" << std::endl; return 1; } if (!doc.HasMember("path")) { std::cerr << "Field \"path\" is missed" << std::endl; return 1; } const rapidjson::Value &path = doc["path"]; if (!path.IsString()) { std::cout << "Field \"path\" must be string" << std::endl; return 1; } const rapidjson::Value &servers = doc["servers"]; if (!servers.IsArray()) { std::cerr << "Field \"servers\" must be an array" << std::endl; return 1; } std::vector<tests::config_data> configs; configs.resize(servers.Size(), srw ? tests::config_data::default_srw_value() : tests::config_data::default_value()); for (rapidjson::SizeType i = 0; i < servers.Size(); ++i) { const rapidjson::Value &server = servers[i]; tests::config_data &config = configs[i]; for (auto it = server.MemberBegin(); it != server.MemberEnd(); ++it) { const std::string name(it->name.GetString(), it->name.GetStringLength()); const rapidjson::Value &value = it->value; if (value.IsNull()) { config(name, tests::NULL_VALUE); } else if (value.IsNumber()) { config(name, value.GetInt()); } else if (value.IsString()) { config(name, std::string(value.GetString(), value.GetStringLength())); } else { std::cerr << "Field \"servers[" << i << "]." << name << "\" has unknown type" << std::endl; return 1; } } } try { global_data = tests::start_nodes(std::cerr, configs, std::string(path.GetString(), path.GetStringLength())); } catch (std::exception &err) { std::cerr << "Error during startup: " << err.what() << std::endl; return 1; } #ifdef HAVE_COCAINE if (srw) { try { tests::upload_application(global_data->locator_port, global_data->directory.path()); } catch (std::exception &exc) { std::cerr << "Can not upload application: " << exc.what() << std::endl; global_data.reset(); return 1; } } #endif { rapidjson::Document info; info.SetObject(); rapidjson::Value servers; servers.SetArray(); for (auto it = global_data->nodes.begin(); it != global_data->nodes.end(); ++it) { const tests::server_node &node = *it; rapidjson::Value server; server.SetObject(); server.AddMember("remote", node.remote().c_str(), info.GetAllocator()); server.AddMember("monitor", node.monitor_port(), info.GetAllocator()); rapidjson::Value remote(node.remote().c_str(), node.remote().size(), info.GetAllocator()); servers.PushBack(remote, info.GetAllocator()); } info.AddMember("servers", servers, info.GetAllocator()); rapidjson::StringBuffer buffer; rapidjson::Writer<rapidjson::StringBuffer> writer(buffer); info.Accept(writer); std::cout << buffer.GetString() << std::endl; } setup_signals(); while (global_data) sleep(1); return 0; }
int32_t my_info::unserialize(const rapidjson::Value& _node) { auto iter_aimid = _node.FindMember("aimId"); if (iter_aimid != _node.MemberEnd() && iter_aimid->value.IsString()) aimId_ = iter_aimid->value.GetString(); auto iter_displayId = _node.FindMember("displayId"); if (iter_displayId != _node.MemberEnd() && iter_displayId->value.IsString()) displayId_ = iter_displayId->value.GetString(); auto iter_friendlyName = _node.FindMember("friendly"); if (iter_friendlyName != _node.MemberEnd() && iter_friendlyName->value.IsString()) friendlyName_ = iter_friendlyName->value.GetString(); auto iter_state = _node.FindMember("state"); if (iter_state != _node.MemberEnd() && iter_state->value.IsString()) state_ = iter_state->value.GetString(); auto iter_userType = _node.FindMember("userType"); if (iter_userType != _node.MemberEnd() && iter_userType->value.IsString()) userType_ = iter_userType->value.GetString(); auto iter_phoneNumber = _node.FindMember("attachedPhoneNumber"); if (iter_phoneNumber != _node.MemberEnd() && iter_phoneNumber->value.IsString()) phoneNumber_ = iter_phoneNumber->value.GetString(); auto iter_flags = _node.FindMember("globalFlags"); if (iter_flags != _node.MemberEnd() && iter_flags->value.IsUint()) flags_ = iter_flags->value.GetUint(); if (state_ == "occupied" || state_ == "na" || state_ == "busy") state_ = "dnd"; else if (state_ != "offline" && state_ != "invisible") state_ = "online"; return 0; }
void set(const rapidjson::Value& object) { using std::isnormal; if (not object.HasMember("save-mhd-n")) { throw std::invalid_argument( std::string(__FILE__ "(") + std::to_string(__LINE__) + "): " + "JSON data doesn't have a save-mhd-n key." ); } save_mhd_n = object["save-mhd-n"].GetDouble(); if (not object.HasMember("time-start")) { throw std::invalid_argument( std::string(__FILE__ "(") + std::to_string(__LINE__) + "): " + "JSON data doesn't have a time-start key." ); } time_start = object["time-start"].GetDouble(); if (not object.HasMember("time-length")) { throw std::invalid_argument( std::string(__FILE__ "(") + std::to_string(__LINE__) + "): " + "JSON data doesn't have a time-length key." ); } time_length = object["time-length"].GetDouble(); if (not object.HasMember("time-step-factor")) { throw std::invalid_argument( std::string(__FILE__ "(") + std::to_string(__LINE__) + "): " + "JSON data doesn't have a time-step-factor key." ); } time_step_factor = object["time-step-factor"].GetDouble(); if (not object.HasMember("remove-div-B-n")) { throw std::invalid_argument( std::string(__FILE__ "(") + std::to_string(__LINE__) + "): " + "JSON data doesn't have a remove-div-B-n key." ); } remove_div_B_n = object["remove-div-B-n"].GetDouble(); if (not object.HasMember("poisson-norm-stop")) { throw std::invalid_argument( std::string(__FILE__ "(") + std::to_string(__LINE__) + "): " + "JSON data doesn't have a poisson-norm-stop key." ); } poisson_norm_stop = object["poisson-norm-stop"].GetDouble(); if (not object.HasMember("poisson-norm-increase-max")) { throw std::invalid_argument( std::string(__FILE__ "(") + std::to_string(__LINE__) + "): " + "JSON data doesn't have a poisson-norm-increase-max key." ); } poisson_norm_increase_max = object["poisson-norm-increase-max"].GetDouble(); if (not object.HasMember("adiabatic-index")) { throw std::invalid_argument( std::string(__FILE__ "(") + std::to_string(__LINE__) + "): " + "JSON data doesn't have a adiabatic-index key." ); } adiabatic_index = object["adiabatic-index"].GetDouble(); if (not isnormal(adiabatic_index) or adiabatic_index < 0) { throw std::invalid_argument( std::string(__FILE__ "(") + std::to_string(__LINE__) + "): " + "Invalid adiabatic index: " + std::to_string(adiabatic_index) + ", should be > 0" ); } if (not object.HasMember("vacuum-permeability")) { throw std::invalid_argument( std::string(__FILE__ "(") + std::to_string(__LINE__) + "): " + "JSON data doesn't have a vacuum-permeability key." ); } vacuum_permeability = object["vacuum-permeability"].GetDouble(); if (not isnormal(vacuum_permeability) or vacuum_permeability < 0) { throw std::invalid_argument( std::string(__FILE__ "(") + std::to_string(__LINE__) + "): " + "Invalid vacuum permeability: " + std::to_string(vacuum_permeability) + ", should be > 0" ); } if (not object.HasMember("proton-mass")) { throw std::invalid_argument( std::string(__FILE__ "(") + std::to_string(__LINE__) + "): " + "JSON data doesn't have a proton-mass key." ); } proton_mass = object["proton-mass"].GetDouble(); if (not isnormal(proton_mass) or proton_mass < 0) { throw std::invalid_argument( std::string(__FILE__ "(") + std::to_string(__LINE__) + "): " + "Invalid proton_mass: " + std::to_string(proton_mass) + ", should be > 0" ); } if (not object.HasMember("solver-mhd")) { throw std::invalid_argument( std::string(__FILE__ "(") + std::to_string(__LINE__) + "): " + "JSON data doesn't have a solver-mhd key." ); } solver = object["solver-mhd"].GetString(); if ( solver != "rusanov" and solver != "hll-athena" and solver != "hlld-athena" and solver != "roe-athena" ) { throw std::invalid_argument( std::string(__FILE__ "(") + std::to_string(__LINE__) + "): " + "Invalid mhd solver: " + solver + ", should be one of rusanov, hll-athena, hlld-athena, roe-athena." ); } if (object.HasMember("output-directory")) { output_directory = object["output-directory"].GetString(); } if (not object.HasMember("load-balancer")) { throw std::invalid_argument( std::string(__FILE__ "(") + std::to_string(__LINE__) + "): " + "JSON data doesn't have a load-balancer key." ); } lb_name = object["load-balancer"].GetString(); if (not object.HasMember("minimum-pressure")) { throw std::invalid_argument( std::string(__FILE__ "(") + std::to_string(__LINE__) + "): " + "JSON data doesn't have a minimum-pressure key." ); } const auto& min_pressure_json = object["minimum-pressure"]; if (not min_pressure_json.IsNumber()) { throw std::invalid_argument( std::string(__FILE__ "(") + std::to_string(__LINE__) + "): " + "JSON item minimum-pressure is not a number." ); } min_pressure = min_pressure_json.GetDouble(); }
int32_t fetch::parse_response_data(const rapidjson::Value& _data) { try { bool have_webrtc_event = false; auto iter_events = _data.FindMember("events"); if (iter_events != _data.MemberEnd() && iter_events->value.IsArray()) { for (auto iter_evt = iter_events->value.Begin(); iter_evt != iter_events->value.End(); iter_evt++) { auto iter_type = iter_evt->FindMember("type"); auto iter_event_data = iter_evt->FindMember("eventData"); if (iter_type != iter_evt->MemberEnd() && iter_event_data != iter_evt->MemberEnd() && iter_type->value.IsString()) { std::string event_type = iter_type->value.GetString(); if (event_type == "buddylist") push_event(std::make_shared<fetch_event_buddy_list>())->parse(iter_event_data->value); else if (event_type == "presence") push_event(std::make_shared<fetch_event_presence>())->parse(iter_event_data->value); else if (event_type == "histDlgState") push_event(std::make_shared<fetch_event_dlg_state>())->parse(iter_event_data->value); else if (event_type == "webrtcMsg") have_webrtc_event = true; else if (event_type == "hiddenChat") push_event(std::make_shared<fetch_event_hidden_chat>())->parse(iter_event_data->value); else if (event_type == "diff") push_event(std::make_shared<fetch_event_diff>())->parse(iter_event_data->value); else if (event_type == "myInfo") push_event(std::make_shared<fetch_event_my_info>())->parse(iter_event_data->value); else if (event_type == "userAddedToBuddyList") push_event(std::make_shared<fetch_event_user_added_to_buddy_list>())->parse(iter_event_data->value); else if (event_type == "typing") push_event(std::make_shared<fetch_event_typing>())->parse(iter_event_data->value); else if (event_type == "sessionEnded") session_ended_ = true; else if (event_type == "permitDeny") push_event(std::make_shared<fetch_event_permit>())->parse(iter_event_data->value); /* else if (event_type == L"mchat") PushEvent(std::make_shared<fetch_event_mchat>())->Parse(wr); */ } } } if (!session_ended_) { auto iter_next_fetch_url = _data.FindMember("fetchBaseURL"); if (iter_next_fetch_url == _data.MemberEnd() || !iter_next_fetch_url->value.IsString()) return wpie_http_parse_response; next_fetch_url_ = iter_next_fetch_url->value.GetString(); next_fetch_time_ = std::chrono::system_clock::now(); auto iter_time_to_next_fetch = _data.FindMember("timeToNextFetch"); if (iter_time_to_next_fetch != _data.MemberEnd() && iter_time_to_next_fetch->value.IsUint()) { time_t fetch_timeout = iter_time_to_next_fetch->value.GetUint(); next_fetch_time_ += std::chrono::milliseconds(fetch_timeout); } auto iter_ts = _data.FindMember("ts"); if (iter_ts == _data.MemberEnd() || !iter_ts->value.IsUint()) return wpie_http_parse_response; ts_ = iter_ts->value.GetUint(); time_offset_ = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now()) - ts_; } if (have_webrtc_event) { auto we = std::make_shared<webrtc_event>(); if (!!we) { // sorry... the simplest way we->parse(response_str()); push_event(we); } else { assert(false); } } } catch (const std::exception&) { } return 0; }
int32_t fetch_event_dlg_state::parse(const rapidjson::Value& _node_event_data) { auto iter_sn = _node_event_data.FindMember("sn"); auto iter_last_msg_id = _node_event_data.FindMember("lastMsgId"); if ( iter_sn == _node_event_data.MemberEnd() || iter_last_msg_id == _node_event_data.MemberEnd() || !iter_sn->value.IsString() || !iter_last_msg_id->value.IsInt64()) { __TRACE( "delivery", "%1%", "failed to parse incoming dlg state event"); return wpie_error_parse_response; } aimid_ = iter_sn->value.GetString(); state_.set_last_msgid(iter_last_msg_id->value.GetInt64()); auto iter_unread_count = _node_event_data.FindMember("unreadCnt"); if (iter_unread_count != _node_event_data.MemberEnd() && iter_unread_count->value.IsUint()) state_.set_unread_count(iter_unread_count->value.GetUint()); auto iter_yours = _node_event_data.FindMember("yours"); if (iter_yours != _node_event_data.MemberEnd() && iter_yours->value.IsObject()) { auto iter_last_read = iter_yours->value.FindMember("lastRead"); if (iter_last_read != iter_yours->value.MemberEnd() && iter_last_read->value.IsInt64()) state_.set_yours_last_read(iter_last_read->value.GetInt64()); } auto iter_theirs = _node_event_data.FindMember("theirs"); if (iter_theirs != _node_event_data.MemberEnd() && iter_theirs->value.IsObject()) { auto iter_last_read = iter_theirs->value.FindMember("lastRead"); if (iter_last_read != iter_theirs->value.MemberEnd() && iter_last_read->value.IsInt64()) state_.set_theirs_last_read(iter_last_read->value.GetInt64()); auto iter_last_delivered = iter_theirs->value.FindMember("lastDelivered"); if (iter_last_delivered != iter_theirs->value.MemberEnd() && iter_last_delivered->value.IsInt64()) state_.set_theirs_last_delivered(iter_last_delivered->value.GetInt64()); } int64_t older_msg_id = -1; auto iter_older_msgid = _node_event_data.FindMember("olderMsgId"); if (iter_older_msgid != _node_event_data.MemberEnd() && iter_older_msgid->value.IsInt64()) { older_msg_id = iter_older_msgid->value.GetInt64(); } auto iter_patch_version = _node_event_data.FindMember("patchVersion"); if (iter_patch_version != _node_event_data.MemberEnd()) { const std::string patch_version = iter_patch_version->value.GetString(); assert(!patch_version.empty()); state_.set_dlg_state_patch_version(patch_version); } auto iter_del_up_to = _node_event_data.FindMember("delUpto"); if ((iter_del_up_to != _node_event_data.MemberEnd()) && iter_del_up_to->value.IsInt64()) { state_.set_del_up_to(iter_del_up_to->value.GetInt64()); } core::archive::persons_map persons; if (!parse_history_messages_json(_node_event_data, older_msg_id, aimid_, *messages_, persons)) { __TRACE( "delivery", "%1%", "failed to parse incoming dlg state messages"); return wpie_error_parse_response; } auto iter_person = persons.find(aimid_); if (iter_person != persons.end()) { state_.set_friendly(iter_person->second.friendly_); state_.set_official(iter_person->second.official_); } if (::build::is_debug()) { __INFO( "delete_history", "incoming dlg state event\n" " contact=<%1%>\n" " dlg-patch=<%2%>\n" " del-up-to=<%3%>", aimid_ % state_.get_dlg_state_patch_version() % state_.get_del_up_to() ); __TRACE( "delivery", "parsed incoming dlg state event\n" " size=<%1%>\n" " last_msgid=<%2%>", messages_->size() % state_.get_last_msgid()); for (const auto &message : *messages_) { __TRACE( "delivery", "parsed incoming dlg state message\n" " id=<%1%>", message->get_msgid()); } } return 0; }
static void parseValue(SettingValue &value, const rapidjson::Value &json_val) { if (json_val.IsInt()) value = json_val.GetInt(); else if (json_val.IsString()) value = std::string(json_val.GetString(), json_val.GetStringLength()); else if (json_val.IsBool()) value = json_val.GetBool(); else if (json_val.IsArray()) { SettingList value_list; for (auto it = json_val.Begin(); it != json_val.End(); ++it) { SettingValue child_val; parseValue(child_val, *it); value_list.push_back(child_val); } value = value_list; } else if (json_val.IsObject()) { SettingMap value_map; for (auto it = json_val.MemberBegin(); it != json_val.MemberEnd(); ++it) { SettingValue child_val; parseValue(child_val, it->value); value_map[it->name.GetString()] = child_val; } value = value_map; } else throw std::runtime_error("Unexpected JSON value type."); }
QueryError OnStats(const rapidjson::Value &p_Args, std::string *p_Result) { auto name = p_Args.FindMember("playerName"); if (name == p_Args.MemberEnd() || !name->value.IsString()) { *p_Result = "Bad query: A \"playerName\" argument is required and must be a string"; return QueryError_BadQuery; } auto session = Blam::Network::GetActiveSession(); if (!session || !session->IsEstablished()) { *p_Result = "Cannot get stat data when there is not an active session."; return QueryError_BadQuery; } int playerIdx = session->MembershipInfo.FindFirstPlayer(); while (playerIdx != -1) { auto player = session->MembershipInfo.PlayerSessions[playerIdx]; if (strcmp(Utils::String::ThinString(player.Properties.DisplayName).c_str(), name->value.GetString()) == 0) { rapidjson::StringBuffer buffer; rapidjson::Writer<rapidjson::StringBuffer> writer(buffer); auto playerStats = Blam::Players::GetStats(playerIdx); auto pvpStats = Blam::Players::GetPVPStats(playerIdx); writer.StartObject(); writer.Key("playerkilledplayer"); writer.StartArray(); for (int i = 0; i < 16; i++) { if (pvpStats.StatsAgainstEachPlayer[i].Kills > 0) { auto p = session->MembershipInfo.PlayerSessions[i]; writer.StartObject(); writer.Key("PlayerName"); writer.String(Utils::String::ThinString(p.Properties.DisplayName).c_str()); writer.Key("Kills"); writer.Int(pvpStats.StatsAgainstEachPlayer[i].Kills); writer.EndObject(); } } writer.EndArray(); writer.Key("playerkilledby"); writer.StartArray(); for (int i = 0; i < 16; i++) { if (pvpStats.StatsAgainstEachPlayer[i].KilledBy > 0) { auto p = session->MembershipInfo.PlayerSessions[i]; writer.StartObject(); writer.Key("PlayerName"); writer.String(Utils::String::ThinString(p.Properties.DisplayName).c_str()); writer.Key("Kills"); writer.Int(pvpStats.StatsAgainstEachPlayer[i].KilledBy); writer.EndObject(); } } writer.EndArray(); writer.Key("medals"); writer.StartObject(); for (int medal = 0; medal < Blam::Tags::Objects::MedalType::MedalCount; medal++) { writer.Key(Blam::Tags::Objects::MedalTypeNames[medal].c_str()); writer.Int(playerStats.Medals[medal]); } writer.EndObject(); writer.Key("weapons"); writer.StartObject(); for (int weapon = 0; weapon < Blam::Tags::Objects::DamageReportingType::DamageCount; weapon++) { writer.Key(Blam::Tags::Objects::DamageReportingTypeNames[weapon].c_str()); writer.StartObject(); auto wep = playerStats.WeaponStats[weapon]; writer.Key("BetrayalsWith"); writer.Int(wep.BetrayalsWith); writer.Key("HeadshotsWith"); writer.Int(wep.HeadshotsWith); writer.Key("KilledBy"); writer.Int(wep.KilledBy); writer.Key("Kills"); writer.Int(wep.Kills); writer.Key("SuicidesWith"); writer.Int(wep.SuicidesWith); writer.EndObject(); } writer.EndObject(); writer.EndObject(); *p_Result = buffer.GetString(); return QueryError_Ok; } playerIdx = session->MembershipInfo.FindNextPlayer(playerIdx); } *p_Result = "Could not find player."; return QueryError_BadQuery; }
UnitType::UnitType(const rapidjson::Value &json) : name{}, plural{}, moves{1}, initiative{0}, hp{1}, minDmg{0}, maxDmg{0}, minDmgRanged{0}, maxDmgRanged{0}, growth{1}, traits{}, spell{nullptr}, baseImg{}, reverseImg{}, imgMove{}, reverseImgMove{}, sndMove{}, animAttack{}, reverseAnimAttack{}, attackFrames{}, animRanged{}, reverseAnimRanged{}, rangedFrames{}, projectile{}, sndAttack{}, sndRanged{}, imgDefend{}, reverseImgDefend{}, sndDefend{}, animDie{}, reverseAnimDie{}, dieFrames{}, sndDie{} { bool hasRangedAttack = false; if (json.HasMember("name")) { name = json["name"].GetString(); } if (json.HasMember("plural")) { plural = json["plural"].GetString(); } if (json.HasMember("initiative")) { initiative = json["initiative"].GetInt(); } if (json.HasMember("hp")) { hp = json["hp"].GetInt(); } if (json.HasMember("img")) { loadImages(json, "img", baseImg, reverseImg); } if (json.HasMember("img-move")) { loadImages(json, "img-move", imgMove, reverseImgMove); } if (json.HasMember("img-defend")) { loadImages(json, "img-defend", imgDefend, reverseImgDefend); } if (json.HasMember("anim-attack") && json.HasMember("attack-frames")) { loadAnimation(json, "anim-attack", animAttack, reverseAnimAttack, "attack-frames", attackFrames); } if (json.HasMember("anim-ranged") && json.HasMember("ranged-frames")) { loadAnimation(json, "anim-ranged", animRanged, reverseAnimRanged, "ranged-frames", rangedFrames); } if (json.HasMember("damage")) { const auto &damageList = json["damage"]; minDmg = damageList[0u].GetInt(); maxDmg = damageList[1u].GetInt(); } if (json.HasMember("damage-ranged")) { hasRangedAttack = true; const auto &damageList = json["damage-ranged"]; minDmgRanged = damageList[0u].GetInt(); maxDmgRanged = damageList[1u].GetInt(); } if (json.HasMember("growth")) { growth = json["growth"].GetInt(); } if (json.HasMember("projectile")) { projectile = sdlLoadImage(json["projectile"].GetString()); } if (json.HasMember("sound-move")) { sndMove = sdlLoadSound(json["sound-move"].GetString()); } if (json.HasMember("sound-attack")) { sndAttack = sdlLoadSound(json["sound-attack"].GetString()); } if (json.HasMember("sound-ranged")) { sndRanged = sdlLoadSound(json["sound-ranged"].GetString()); } if (json.HasMember("sound-defend")) { sndDefend = sdlLoadSound(json["sound-defend"].GetString()); } if (json.HasMember("sound-die")) { sndDie = sdlLoadSound(json["sound-die"].GetString()); } if (json.HasMember("anim-die") && json.HasMember("die-frames")) { loadAnimation(json, "anim-die", animDie, reverseAnimDie, "die-frames", dieFrames); } if (json.HasMember("traits")) { auto tlist = parseTraits(json["traits"]); traits.insert(std::end(traits), std::begin(tlist), std::end(tlist)); } if (json.HasMember("spell")) { spell = getSpell(json["spell"].GetString()); if (spell) { traits.push_back(Trait::SPELLCASTER); } else { std::cerr << "WARNING: unrecognized spell for " << name << '\n'; } } if (hasRangedAttack) { traits.push_back(Trait::RANGED); if (!projectile) { std::cerr << "WARNING: projectile not specified for " << name << '\n'; projectile = sdlLoadImage("missile.png"); } } if (contains(traits, Trait::MOUNTED)) { moves = 2; } sort(std::begin(traits), std::end(traits)); }
bool gui_settings::unserialize(const rapidjson::Value& _node) { auto iter_show_in_taskbar = _node.FindMember(settings_show_in_taskbar); if (iter_show_in_taskbar != _node.MemberEnd() && iter_show_in_taskbar->value.IsBool()) { tools::binary_stream bs; bs.write<bool>(iter_show_in_taskbar->value.GetBool()); set_value(settings_show_in_taskbar, bs); } auto iter_enable_sounds = _node.FindMember(settings_sounds_enabled); if (iter_enable_sounds != _node.MemberEnd() && iter_enable_sounds->value.IsBool()) { tools::binary_stream bs; bs.write<bool>(iter_enable_sounds->value.GetBool()); set_value(settings_sounds_enabled, bs); } auto iter_autosave_files = _node.FindMember(settings_download_files_automatically); if (iter_autosave_files != _node.MemberEnd() && iter_autosave_files->value.IsBool()) { tools::binary_stream bs; bs.write<bool>(iter_autosave_files->value.GetBool()); set_value(settings_download_files_automatically, bs); } auto iter_download_folder = _node.FindMember(settings_download_directory); if (iter_download_folder != _node.MemberEnd() && iter_download_folder->value.IsString()) { tools::binary_stream bs; std::string folder = iter_download_folder->value.GetString(); bs.write(folder.c_str(), folder.length() + 1); set_value(settings_download_directory, bs); } auto iter_send_hotkey = _node.FindMember(settings_key1_to_send_message); if (iter_send_hotkey != _node.MemberEnd() && iter_send_hotkey->value.IsInt()) { tools::binary_stream bs; bs.write<int32_t>(iter_send_hotkey->value.GetInt()); set_value(settings_key1_to_send_message, bs); } auto iter_enable_preview = _node.FindMember(settings_show_video_and_images); if (iter_enable_preview != _node.MemberEnd() && iter_enable_preview->value.IsBool()) { tools::binary_stream bs; bs.write<bool>(iter_enable_preview->value.GetBool()); set_value(settings_show_video_and_images, bs); } auto iter_language = _node.FindMember(settings_language); if (iter_language != _node.MemberEnd() && iter_language->value.IsString()) { tools::binary_stream bs; std::string folder = iter_language->value.GetString(); bs.write(folder.c_str(), folder.length() + 1); set_value(settings_language, bs); } auto iter_notify = _node.FindMember(settings_notify_new_messages); if (iter_notify != _node.MemberEnd() && iter_notify->value.IsBool()) { tools::binary_stream bs; bs.write<bool>(iter_notify->value.GetBool()); set_value(settings_notify_new_messages, bs); } return true; }
std::string PersonManager::handlePlatformMessage(const rapidjson::Value& content) { std::string operation = content[minius::Protocol::OPERATION.c_str()].GetString(); if (operation == "loadModule") { std::string result = SUCC; if (content.HasMember("INIT_DATA")) { const rapidjson::Value& initData = content["INIT_DATA"]; for (rapidjson::SizeType i = 0; i < initData.Size(); ++i) { std::string resultTemp = this->handlePlatformMessage(initData[i]); assert(resultTemp == SUCC); /* if (resultTemp != SUCC) result = resultTemp;*/ } } return result; } else if (operation == "performAction") { return this->handlePerformAction(content); } else if (operation == "expandPersonMenu") { return this->handleExpandPersonMenu(content); } else if (operation == "dressFigure") { return this->handleDressFigure(content); } else if (operation == "updateSpouseScene") { return this->handleUpdateSpouseScene(content); } else if (operation == "setSpouseMessage") { if (content.HasMember("MESSAGE") == false) { return "missing MESSAGE"; } else { std::string message = content["MESSAGE"].GetString(); mSpouseMessage.setValue(message); mSpouseMessage.notify(); return SUCC; } } else if (operation == "setFigureResourceDir") { assert(content.HasMember("DIRECTORY")); std::string resourceDir = content["DIRECTORY"].GetString(); FigureResourceManager::getInstance()->setResourceDir(resourceDir); return SUCC; } else { return std::string("invalid OPERATION: ") + operation; } }
/* * Irregularly spaced sequence */ MultiEchoFlexSequence::MultiEchoFlexSequence(const rapidjson::Value &json) { if (json.IsNull()) QI::Fail("Could not read sequence: {}", name()); TR = GetMember(json, "TR").GetDouble(); TE = ArrayFromJSON(json, "TE"); }
QString Util::RapidjsonSerialize(const rapidjson::Value &val) { rapidjson::StringBuffer buffer; rapidjson::Writer<rapidjson::StringBuffer> writer(buffer); val.Accept(writer); return buffer.GetString(); }