void FileMonitorClient::sendData(int command, const char *buf, ssize_t len) { Document d; d.SetObject(); rapidjson::Value data; data.SetString(buf, (SizeType)len); d.AddMember("command", command, d.GetAllocator()); d.AddMember("data", data, d.GetAllocator()); StringBuffer buffer; Writer<StringBuffer> writer(buffer); d.Accept(writer); std::string senddata = buffer.GetString(); len = senddata.size(); std::cout<<senddata<<std::endl; ssize_t send_len=0; char bufs[10]={0}; sprintf(bufs, "%09lu",senddata.size()); std::string buflen(bufs); buflen.append(senddata); while (send_len<len) { send_len = send(sokt, buflen.c_str(), buflen.size(), 0); int err = errno; if (err>0) { std::cout<<("send packet fail")<<strerror(err)<<std::endl; close_=false; break; } } }
//发送json命令的基础函数 Document Device::sendApi(CString &type, Value &method, Value ¶ms, Value &version) { CString actionurl = findActionListUrl(type); if (!actionurl || actionurl.IsEmpty()) { return NULL; } CString url = actionurl + "/" + type; Document requestJson; requestJson.SetObject(); Document::AllocatorType& allocator = requestJson.GetAllocator(); requestJson.AddMember("method", method, allocator); requestJson.AddMember("params", params, allocator); requestJson.AddMember("id", ++reqId, allocator); requestJson.AddMember("version", version, allocator); StringBuffer buffer; Writer<StringBuffer> writer(buffer); requestJson.Accept(writer); const char* output = buffer.GetString(); CString response = HttpClient::post(url, CString(output)); if (!response || response.IsEmpty()) { return NULL; } Document responseJson; responseJson.Parse(response); return responseJson; }
void AbstractWSServer::EnqueuePushData() { // Now give all the possibility to produce new data... which will never be sent if we closed but who cares! std::for_each(pushing.cbegin(), pushing.cend(), [this](const PushList &mangle) { using namespace rapidjson; for(asizei loop = 0; loop < mangle.active.size(); loop++) { Document send; if(mangle.active[loop]->pusher->Refresh(send)) { Document ret; ret.SetObject(); const std::string &ori(mangle.active[loop]->originator->name); ret.AddMember("pushing", StringRef(ori.c_str()), ret.GetAllocator()); if(mangle.active[loop]->originator->GetMaxPushing() > 1) ret.AddMember("stream", StringRef(mangle.active[loop]->name.c_str()), ret.GetAllocator()); ret.AddMember("payload", send, ret.GetAllocator()); auto sink = std::find_if(clients.cbegin(), clients.cend(), [&mangle](const ClientState &test) { return &test.conn.get() == mangle.dst && test.ws.get(); }); if(sink != clients.cend()) { rapidjson::StringBuffer pretty; #if _DEBUG rapidjson::PrettyWriter<rapidjson::StringBuffer> writer(pretty, nullptr); #else rapidjson::Writer<rapidjson::StringBuffer> writer(pretty, nullptr); #endif ret.Accept(writer); sink->ws->EnqueueTextMessage(pretty.GetString(), pretty.GetSize()); } } } }); }
Document JsonTransactionFactory::serialize( const Transaction &transaction) { Document document; auto& allocator = document.GetAllocator(); document.SetObject(); Value signatures; signatures.SetArray(); for (const auto &signature : transaction.signatures) { signatures.PushBack( Document(&allocator) .CopyFrom(serializeSignature(signature), allocator), allocator); } document.AddMember("signatures", signatures, allocator); document.AddMember("created_ts", transaction.created_ts, allocator); document.AddMember("creator_account_id", transaction.creator_account_id, allocator); document.AddMember("tx_counter", transaction.tx_counter, allocator); Value commands; commands.SetArray(); for (auto &&command : transaction.commands) { commands.PushBack( Document(&allocator) .CopyFrom(factory_.serializeAbstractCommand(command), allocator), allocator); } document.AddMember("commands", commands, allocator); return document; }
void ModbusService::render_GET(const http_request& req, http_response** res) { //api/modbus/holdings/{connectorname}/{devaddress}/{baseaddress}/{count} string connectorName = req.get_arg("connectorname"); string strDevAddress = req.get_arg("devaddress"); string strBaseAddress = req.get_arg("baseaddress"); string strCount = req.get_arg("value"); int devAddress = Converter::stoi(strDevAddress); int baseAddress = Converter::stoi(strBaseAddress); int count = Converter::stoi(strCount); Document document; StringBuffer buffer; PrettyWriter<StringBuffer> wr(buffer); Value jsonvalue; IModbus* modbus = mm->Find(connectorName); if (modbus!=NULL) { uint16_t* target = new uint16_t[count]; if (modbus->getHoldings(devAddress,baseAddress,count,target)) { document.SetArray(); for(int i=0;i<count;i++) { Value jsonvalue; jsonvalue.SetUint(target[i]); document.PushBack(jsonvalue, document.GetAllocator()); } } else { document.SetObject(); jsonvalue.SetObject(); jsonvalue.SetString("Error",document.GetAllocator()); document.AddMember("Result",jsonvalue,document.GetAllocator()); jsonvalue.SetString("Modbus getHoldings failed",document.GetAllocator()); document.AddMember("Message",jsonvalue,document.GetAllocator()); } delete[] target; target = NULL; } else { document.SetObject(); jsonvalue.SetString("Error",document.GetAllocator()); document.AddMember("Result",jsonvalue,document.GetAllocator()); jsonvalue.SetString("Connector not found",document.GetAllocator()); document.AddMember("Message",jsonvalue,document.GetAllocator()); } document.Accept(wr); std::string json = buffer.GetString(); *res = new http_response(http_response_builder(json, 200,"application/json").string_response()); }
void FCDevice::writeDevicePixels(Document &msg) { /* * Write pixels without mapping, from a JSON integer * array in msg["pixels"]. The pixel array is removed from * the reply to save network bandwidth. * * Pixel values are clamped to [0, 255], for convenience. */ const Value &pixels = msg["pixels"]; if (!pixels.IsArray()) { msg.AddMember("error", "Pixel array is missing", msg.GetAllocator()); } else { // Truncate to the framebuffer size, and only deal in whole pixels. int numPixels = pixels.Size() / 3; if (numPixels > NUM_PIXELS) numPixels = NUM_PIXELS; for (int i = 0; i < numPixels; i++) { uint8_t *out = fbPixel(i); const Value &r = pixels[i*3 + 0]; const Value &g = pixels[i*3 + 1]; const Value &b = pixels[i*3 + 2]; out[0] = std::max(0, std::min(255, r.IsInt() ? r.GetInt() : 0)); out[1] = std::max(0, std::min(255, g.IsInt() ? g.GetInt() : 0)); out[2] = std::max(0, std::min(255, b.IsInt() ? b.GetInt() : 0)); } writeFramebuffer(); } }
void Renderer::SaveState(std::string name) { Document doc; doc.Parse("{}"); Value state(kObjectType); state.AddMember("Volume", Value().SetString("volname", doc.GetAllocator()), doc.GetAllocator()); getCamera().saveState(doc, state); getRenderProperties().saveState(doc, state); getTransferFunction().saveState(doc, state); getColorMap().saveState(doc, state["TransferFunction"]); getSlices().saveState(doc, state); getIsos().saveState(doc, state); doc.AddMember("State", state, doc.GetAllocator()); StringBuffer sbuf; PrettyWriter<StringBuffer> writer(sbuf); doc.Accept(writer); std::ofstream out; out.open(name.c_str(), std::ofstream::out); out << sbuf.GetString() << "\n"; out.close(); }
int main(int argc, char **argv) { Document d; d.SetObject(); Value vElem; vElem.SetArray(); Document::AllocatorType & allocator = d.GetAllocator(); for(int i = 0; i < 10; ++i) { Value tmp;///(i); tmp.SetInt(i); // vElem.PushBack<int>(i, d.GetAllocator); vElem.PushBack(tmp, allocator); } d.AddMember("Data", vElem, allocator); StringBuffer buffer; Writer<StringBuffer> writer(buffer); d.Accept(writer); string json(buffer.GetString(), buffer.GetSize()); cout << json << endl; // Document::AllocatorType& a = d.GetAllocator(); // cout << d["test"].IsNull() << endl;// = 1; // Value v1("foo"); // Value v2(v1, a); }
rapidjson::Document SceneConvertor::Convert( const Scene* scene ) { Document json; json.SetObject(); Document::AllocatorType& al = json.GetAllocator(); json.AddMember( "FILE_TYPE", "SCENE", al ); Value stringNode; Value nullNode; nullNode.SetNull(); Material* skyboxMat = scene->GetSkyboxMaterial(); if (skyboxMat != NULL) { stringNode.SetString( skyboxMat->GetName().ToChar(), al ); json.AddMember( "skyboxMaterial", stringNode, al ); } else { json.AddMember( "skyboxMaterial", nullNode, al ); } json.AddMember( "skyboxSize", scene->GetSkyboxSize(), al ); Value vec3Node = _Vec3_to_JSON( scene->GetAmbientLight(), al ); json.AddMember( "ambientLight", vec3Node, al ); if ( scene->GetMainCamera() != NULL ) { stringNode.SetString( scene->GetMainCamera()->GetName().ToChar(), al ); json.AddMember( "mainCamera", stringNode, al ); } else { json.AddMember( "mainCamera", nullNode, al ); } Value arrayNode; arrayNode.SetArray(); for (uint i = 0; i < scene->GetGameObjectCount(); ++i) { GameObject* gameObject = scene->GetGameObjectAt(i); if ( gameObject->GetParentNode() == NULL && (_useAll || gameObject->IsSavable()) ) { arrayNode.PushBack( _GameObject_to_JSON(gameObject, al), al ); } } json.AddMember( "gameObjects", arrayNode, al ); return json; }
int main(int argc, const char* argv[]) { luaL_openlibs(L); luabridge::getGlobalNamespace(L) .beginClass<Entity>("Entity") .addConstructor<void(*)(void)>() .addFunction("say", &Entity::say) .addFunction("getComponent", &Entity::getComponent) .addFunction("addComponent", &Entity::addComponent) .endClass() .beginClass<Component>("Component") .addCFunction("getVariable", &Component::getVariable) .addCFunction("setVariable", &Component::setVariable) .addFunction("getParent", &Component::getParent) .addFunction("addMember", &Component::addMember) .endClass(); // -- LuaScript enemyLuaScript(L, "Enemy.lua"); LuaScript entityLuaScript(L, "Player.lua"); ComponentScript entityScript(&entityLuaScript); ComponentScript enemyScript(&enemyLuaScript); // -- Entity myEntity; myEntity.addComponent(&entityScript); myEntity.addComponent(&enemyScript); Entity myEntity2; myEntity2.addComponent(&enemyScript); // myEntity.onLoop(); // myEntity2.onLoop(); myEntity.getComponent("Player.lua")->getScript()->getReference("doPlayerStuff")->call(myEntity.getComponent("Player.lua"), myEntity2); // -- Document d; d.Parse("{}"); rapidjson::Value entityValue(rapidjson::kObjectType); myEntity.onSerialize(&entityValue, &d.GetAllocator()); myEntity2.onSerialize(&entityValue, &d.GetAllocator()); d.AddMember("entities", entityValue, d.GetAllocator()); rapidjson::StringBuffer sb; rapidjson::Writer<rapidjson::StringBuffer> writer(sb); d.Accept(writer); std::cout << sb.GetString() << "\n"; }
void ModbusService::render_PUT(const http_request& req, http_response** res) { string connectorName = req.get_arg("connectorname"); string strDevAddress = req.get_arg("devaddress"); string strBaseAddress = req.get_arg("baseaddress"); string strValue = req.get_arg("value"); int devAddress = Converter::stoi(strDevAddress); int baseAddress = Converter::stoi(strBaseAddress); int value = Converter::stoi(strValue); Document document; StringBuffer buffer; PrettyWriter<StringBuffer> wr(buffer); document.SetObject(); Value jsonvalue; IModbus* modbus = mm->Find(connectorName); if (modbus!=NULL) { if (modbus->setHolding(devAddress,baseAddress,value)) { jsonvalue.SetString("OK",document.GetAllocator()); document.AddMember("Result",jsonvalue,document.GetAllocator()); } else { jsonvalue.SetString("Error",document.GetAllocator()); document.AddMember("Result",jsonvalue,document.GetAllocator()); jsonvalue.SetString("Modbus setHolding failed",document.GetAllocator()); document.AddMember("Message",jsonvalue,document.GetAllocator()); } } else { jsonvalue.SetString("Error",document.GetAllocator()); document.AddMember("Result",jsonvalue,document.GetAllocator()); jsonvalue.SetString("Connector not found",document.GetAllocator()); document.AddMember("Message",jsonvalue,document.GetAllocator()); } document.Accept(wr); std::string json = buffer.GetString(); *res = new http_response(http_response_builder(json, 200,"application/json").string_response()); }
Document JsonBlockFactory::serialize(const Block &block) { Document document; auto &allocator = document.GetAllocator(); document.SetObject(); Value signatures; signatures.SetArray(); for (const auto &signature : block.sigs) { signatures.PushBack(serializeSignature(signature, allocator), allocator); } document.AddMember("signatures", signatures, allocator); document.AddMember("created_ts", block.created_ts, allocator); document.AddMember("hash", block.hash.to_hexstring(), allocator); document.AddMember( "prev_hash", block.prev_hash.to_hexstring(), allocator); document.AddMember("height", block.height, allocator); document.AddMember("txs_number", block.txs_number, allocator); Value commands; commands.SetArray(); for (auto &&transaction : block.transactions) { commands.PushBack( Document(&allocator) .CopyFrom(factory_.serialize(transaction), allocator), allocator); } document.AddMember("transactions", commands, allocator); return document; }
// Issue 226: Value of string type should not point to NULL TEST(Document, AssertAcceptInvalidNameType) { Document doc; doc.SetObject(); doc.AddMember("a", 0, doc.GetAllocator()); doc.FindMember("a")->name.SetNull(); // Change name to non-string type. OutputStringStream os; Writer<OutputStringStream> writer(os); ASSERT_THROW(doc.Accept(writer), AssertException); }
void do_read() { auto self(shared_from_this()); socket_.async_read_some(boost::asio::buffer(data_, max_length), [this, self](boost::system::error_code ec, std::size_t length) { if (!ec) { TMP_PACKET* packet = (TMP_PACKET*)(data_); Document d; d.Parse(packet->strdata); Value& ss = d["stars"]; ss.SetInt(ss.GetInt() + 1); OutputDebugString("recv packet"); Document sendJson; sendJson.SetObject(); Document::AllocatorType& allocator = sendJson.GetAllocator(); sendJson.AddMember("cmd", 1, allocator); sendJson.AddMember("ret", 1, allocator); // Convert JSON document to string rapidjson::StringBuffer strbuf; rapidjson::Writer<rapidjson::StringBuffer> writer(strbuf); sendJson.Accept(writer); static int totalcnt = 0; totalcnt++; TCP_PACKET_H hdr; hdr.PacketSize = strbuf.GetSize()+ 1 + sizeof(TCP_PACKET_H); memcpy_s(_sendData, sizeof(TCP_PACKET_H), (void*)&hdr, sizeof(TCP_PACKET_H)); std::cout << strbuf.GetString() << strbuf.GetSize() << " total:"<< totalcnt << std::endl; //std::cout << strbuf.GetSize() << std::endl; sprintf_s(_sendData + sizeof(TCP_PACKET_H), strbuf.GetSize()+1, "%s",strbuf.GetString()); // 오류코드 없으면, 패킷데이터 처리.. // 헤더검사 등의 예외처리 필요.. //TMP_PACKET sendPkt; //sendPkt.Header.PacketSize = strbuf.GetSize()+; do_write(hdr.PacketSize); do_read(); } }); }
int ConfigParser::SetField(const char* field, const char* value) { stringstream err; FILE* fpRead = fopen(configPath.c_str(), "rb"); if(!fpRead){ err << "Could not open file " << configPath << "!"; errors.push_back(err.str()); return -1; } char readBuffer[CONFIGPARSER_BUF_SIZE] = {}; FileReadStream configStream(fpRead, readBuffer, sizeof(readBuffer)); Document d; d.ParseStream(configStream); if(d.HasMember(field)){ Value& tmp(d[field]); tmp.SetString(StringRef(value)); } else { Value::AllocatorType& a(d.GetAllocator()); d.AddMember(StringRef(field), StringRef(value), a); if(!d.HasMember(field)){ fclose(fpRead); err << "Failed to set field '" << field << "'' in config file " << configPath << "!"; errors.push_back(err.str()); return -1; } } fclose(fpRead); FILE* fpWrite = fopen(configPath.c_str(), "wb"); if(!fpWrite){ err << "Could not open file " << configPath << "!"; errors.push_back(err.str()); return -1; } char writeBuffer[CONFIGPARSER_BUF_SIZE] = {}; FileWriteStream configWriteStream(fpWrite, writeBuffer, sizeof(writeBuffer)); PrettyWriter<FileWriteStream> writer(configWriteStream); d.Accept(writer); fclose(fpWrite); return 0; }
bool ZatData::WriteDataJson() { void* file; if (!(file = XBMC->OpenFileForWrite(data_file.c_str(), true))) { XBMC->Log(LOG_ERROR, "Save data.json failed."); return false; } Document d; d.SetObject(); Value a(kArrayType); Document::AllocatorType& allocator = d.GetAllocator(); for (auto const& item : recordingsData) { if (!item.second->stillValid) { continue; } Value r; r.SetObject(); Value recordingId; recordingId.SetString(item.second->recordingId.c_str(), item.second->recordingId.length(), allocator); r.AddMember("recordingId", recordingId, allocator); r.AddMember("playCount", item.second->playCount, allocator); r.AddMember("lastPlayedPosition", item.second->lastPlayedPosition, allocator); a.PushBack(r, allocator); } d.AddMember("recordings", a, allocator); StringBuffer buffer; Writer<StringBuffer> writer(buffer); d.Accept(writer); const char* output = buffer.GetString(); XBMC->WriteFile(file, output, strlen(output)); XBMC->CloseFile(file); return true; }
/** * Specialisation of Options::SetImpl to store strings. * This specialisation is necessary because the value must be copied. * rapidjson requires that (a.) it explicitly be copied, or that (b.) it will * retain a reference that is guaranteed to be valid for longer than itself. * @param key The key to the value. * @param val The value to be stored. */ void Options::Set(const char *key, const char *val) { Document *d = static_cast<Document*>(m_doc); Value *fi = static_cast<Value*>(m_family_inst); if (!fi) { //Family doesn't exist, so create it Value family_key(m_family.c_str(), d->GetAllocator()); Value family_val(Type::kObjectType); Value entry_key(key, d->GetAllocator()); Value entry_val(val, d->GetAllocator()); family_val.AddMember(entry_key, entry_val, d->GetAllocator()); d->AddMember(family_key, family_val, d->GetAllocator()); m_family_inst = &(*d)[m_family.c_str()]; } else { //We have the family Value *existing = LGetValue(fi, key); if (existing) { //The entry was already there, so just update value existing->SetString(val, d->GetAllocator()); } else { //Create the new entry Value entry_key(key, d->GetAllocator()); Value entry_val(val, d->GetAllocator()); fi->AddMember(entry_key, entry_val, d->GetAllocator()); } } }
int main(int, char*[]) { //////////////////////////////////////////////////////////////////////////// // 1. Parse a JSON text string to a document. const char json[] = " { \"hello\" : \"world\", \"t\" : true , \"f\" : false, \"n\": null, \"i\":123, \"pi\": 3.1416, \"a\":[1, 2, 3, 4] } "; printf("Original JSON:\n %s\n", json); Document document; // Default template parameter uses UTF8 and MemoryPoolAllocator. #if 0 // "normal" parsing, decode strings to new buffers. Can use other input stream via ParseStream(). if (document.Parse(json).HasParseError()) return 1; #else // In-situ parsing, decode strings directly in the source string. Source must be string. char buffer[sizeof(json)]; memcpy(buffer, json, sizeof(json)); if (document.ParseInsitu(buffer).HasParseError()) return 1; #endif printf("\nParsing to document succeeded.\n"); //////////////////////////////////////////////////////////////////////////// // 2. Access values in document. printf("\nAccess values in document:\n"); assert(document.IsObject()); // Document is a JSON value represents the root of DOM. Root can be either an object or array. assert(document.HasMember("hello")); assert(document["hello"].IsString()); printf("hello = %s\n", document["hello"].GetString()); // Since version 0.2, you can use single lookup to check the existing of member and its value: Value::MemberIterator hello = document.FindMember("hello"); assert(hello != document.MemberEnd()); assert(hello->value.IsString()); assert(strcmp("world", hello->value.GetString()) == 0); (void)hello; assert(document["t"].IsBool()); // JSON true/false are bool. Can also uses more specific function IsTrue(). printf("t = %s\n", document["t"].GetBool() ? "true" : "false"); assert(document["f"].IsBool()); printf("f = %s\n", document["f"].GetBool() ? "true" : "false"); printf("n = %s\n", document["n"].IsNull() ? "null" : "?"); assert(document["i"].IsNumber()); // Number is a JSON type, but C++ needs more specific type. assert(document["i"].IsInt()); // In this case, IsUint()/IsInt64()/IsUInt64() also return true. printf("i = %d\n", document["i"].GetInt()); // Alternative (int)document["i"] assert(document["pi"].IsNumber()); assert(document["pi"].IsDouble()); printf("pi = %g\n", document["pi"].GetDouble()); { const Value& a = document["a"]; // Using a reference for consecutive access is handy and faster. assert(a.IsArray()); for (SizeType i = 0; i < a.Size(); i++) // rapidjson uses SizeType instead of size_t. printf("a[%d] = %d\n", i, a[i].GetInt()); int y = a[0].GetInt(); (void)y; // Iterating array with iterators printf("a = "); for (Value::ConstValueIterator itr = a.Begin(); itr != a.End(); ++itr) printf("%d ", itr->GetInt()); printf("\n"); } // Iterating object members static const char* kTypeNames[] = { "Null", "False", "True", "Object", "Array", "String", "Number" }; for (Value::ConstMemberIterator itr = document.MemberBegin(); itr != document.MemberEnd(); ++itr) printf("Type of member %s is %s\n", itr->name.GetString(), kTypeNames[itr->value.GetType()]); //////////////////////////////////////////////////////////////////////////// // 3. Modify values in document. // Change i to a bigger number { uint64_t f20 = 1; // compute factorial of 20 for (uint64_t j = 1; j <= 20; j++) f20 *= j; document["i"] = f20; // Alternate form: document["i"].SetUint64(f20) assert(!document["i"].IsInt()); // No longer can be cast as int or uint. } // Adding values to array. { Value& a = document["a"]; // This time we uses non-const reference. Document::AllocatorType& allocator = document.GetAllocator(); for (int i = 5; i <= 10; i++) a.PushBack(i, allocator); // May look a bit strange, allocator is needed for potentially realloc. We normally uses the document's. // Fluent API a.PushBack("Lua", allocator).PushBack("Mio", allocator); } // Making string values. // This version of SetString() just store the pointer to the string. // So it is for literal and string that exists within value's life-cycle. { document["hello"] = "rapidjson"; // This will invoke strlen() // Faster version: // document["hello"].SetString("rapidjson", 9); } // This version of SetString() needs an allocator, which means it will allocate a new buffer and copy the the string into the buffer. Value author; { char buffer[10]; int len = sprintf(buffer, "%s %s", "Milo", "Yip"); // synthetic example of dynamically created string. author.SetString(buffer, static_cast<size_t>(len), document.GetAllocator()); // Shorter but slower version: // document["hello"].SetString(buffer, document.GetAllocator()); // Constructor version: // Value author(buffer, len, document.GetAllocator()); // Value author(buffer, document.GetAllocator()); memset(buffer, 0, sizeof(buffer)); // For demonstration purpose. } // Variable 'buffer' is unusable now but 'author' has already made a copy. document.AddMember("author", author, document.GetAllocator()); assert(author.IsNull()); // Move semantic for assignment. After this variable is assigned as a member, the variable becomes null. //////////////////////////////////////////////////////////////////////////// // 4. Stringify JSON printf("\nModified JSON with reformatting:\n"); StringBuffer sb; PrettyWriter<StringBuffer> writer(sb); document.Accept(writer); // Accept() traverses the DOM and generates Handler events. puts(sb.GetString()); return 0; }
// on "init" you need to initialize your instance bool HelloWorld::init() { ////////////////////////////// // 1. super init first if ( !Layer::init() ) { return false; } auto visibleSize = Director::getInstance()->getVisibleSize(); auto origin = Director::getInstance()->getVisibleOrigin(); ////////////////////////////////////////////////////////////////////////// /// 数据读取 SSIZE_T size; /* FILE* file1 = fopen("test.json", "wr");*/ unsigned char* ch = FileUtils::getInstance()->getFileData("test.json","r", &size); std::string data = std::string((const char* )ch, size); ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// /// 数据解析成json格式数据 Document doc; ///< 创建一个Document对象 rapidJson的相关操作都在Document类中 doc.Parse<0>(data.c_str()); ///< 通过Parse方法将Json数据解析出来 if (doc.HasParseError()) { CCLOG("GetParseError %s\n",doc.GetParseError()); } ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// /// Json数据读取和更改-----对值操作 rapidjson::Value& valString = doc["hello1"]; ///< 读取键“hello”的值,根据我们的json文档,是一个字符串 if (valString.IsString()) ///< 判断是否是字符串 { const char* ch = valString.GetString(); log(ch); log(valString.GetString()); valString.SetString("newString"); log(valString.GetString()); } rapidjson::Value& valArray = doc["a"]; ///< 读取键“a”值,根据我们的json文档,是一个数组 if (valArray.IsArray()) ///< 判断val的类型 是否为数组 我们的Tollgate键对应的value实际为数组 { for (int i = 0; i < valArray.Capacity(); ++i) { rapidjson::Value& first = valArray[i]; ///< 获取到val中的第i个元素 根据我们这里的json文件 val中共有4个元素 CCLOG("%f", first.GetDouble()); ///< 将value转换成Double类型打印出来 结果为0.5 first.SetDouble(10.f); CCLOG("%f", first.GetDouble()); ///< 将value转换成Double类型打印出来 结果为0.5S } } ////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// /// json数据操作---对键操作之添加成员对象 /// 添加一个String对象; rapidjson::Document::AllocatorType& allocator = doc.GetAllocator(); ///< 获取最初数据的分配器 rapidjson::Value strObject(rapidjson::kStringType); ///< 添加字符串方法1 strObject.SetString("love"); doc.AddMember("hello1", strObject, allocator); /* doc.AddMember("hello1", "love you", allocator); ///< 添加字符串方法2:往分配器中添加一个对象*/ /// 添加一个null对象 rapidjson::Value nullObject(rapidjson::kNullType); doc.AddMember("null", nullObject, allocator); ///< 往分配器中添加一个对象 /// 添加一个数组对象 rapidjson::Value array(rapidjson::kArrayType); ///< 创建一个数组对象 rapidjson::Value object(rapidjson::kObjectType); ///< 创建数组里面对象。 object.AddMember("id", 1, allocator); object.AddMember("name", "lai", allocator); object.AddMember("age", "12", allocator); object.AddMember("low", true, allocator); array.PushBack(object, allocator); doc.AddMember("player", array, allocator); ///< 将上述的数组内容添加到一个名为“player”的数组中 /// 在已有的数组中添加一个成员对象 rapidjson::Value& aArray1 = doc["a"]; aArray1.PushBack(2.0, allocator); ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// /// json数据操作---对键操作之删除成员对象 /// 删除数组成员对象里面元素 rapidjson::Value& aArray2 = doc["a"]; ///< 读取键“a”值,根据我们的json文档,是一个数组 aArray2.PopBack(); ///< 删除数组最后一个成员对象 if (doc.RemoveMember("i")) ///< 删除键为“i”的成员变量 { log("delet i member ok!"); } ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// /// 将json数据重新写入文件中---先将文件删除,再写入内容 rapidjson::StringBuffer buffer; rapidjson::Writer<rapidjson::StringBuffer> writer(buffer); doc.Accept(writer); #if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) system("del E:\cocos2d-x-3.2rc0\tests\cpp-empty-test\Resources\test.josn"); ///< 先将文件删除掉---之前重这个文件读取数据,因此确保这个文件存在了 FILE* file = fopen("test.json", "wb"); if (file) { fputs(buffer.GetString(), file); fclose(file); } #else if(CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) /// 原理差不多,就是先将文件清空,在写入。这里就不写了。 #endif ////////////////////////////////////////////////////////////////////////// return true; }
int main(int argc, char **argv) { string sha256("SHA256"); Poco::Crypto::DigestEngine engine(sha256); engine.update("test"); //string paylod_hash(engine.digest()); Poco::DigestEngine::Digest paylod_hash = engine.digest(); string payload((Poco::Crypto::DigestEngine::digestToHex(paylod_hash))); cout << payload << endl; //cout << paylod_hash << endl; Document doc; doc.SetObject(); Document::AllocatorType & allocator = doc.GetAllocator(); doc.AddMember("TableName", "patent", allocator); doc.AddMember("ProjectionExpression", "patent_id", allocator); // doc.AddMember("") string body = doc2str(doc); string key_id("AKIAIDN3KXQXTMEGVLXA"); string secret("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"); { string method("POST"); string service("dynamodb"); string host("dynamodb.us-east-1.amazonaws.com"); string uri("/"); string region("us-east-1"); string content_type("application/x-amz-json-1.0"); string amz_target("DynamoDB_20120810.Scan"); string query_string(""); string amz_date = getAmzDate(); string amz_stamp = getDateStamp(amz_date); string cannocial_header(""); cannocial_header += "content-type:" + content_type + "\n" + \ "host:" + host + "\n" + \ "x-amz-date:" + amz_date + "\n" + \ "x-amz-target:" + amz_target + "\n"; string signed_headers("content-type;host;x-amz-date;x-amz-target"); } //cout << body << endl; //doc.AddMember("Limit", 1000, allocator); string dbHost("192.168.6.170"); Poco::UInt16 dbPort(8000); HTTPClientSession session; setSession(session, dbHost, dbPort); HTTPRequest request; setRequestHeader(request); request.setContentLength(body.length()); ostream & os = session.sendRequest(request); os << body; HTTPResponse res; istream &is = session.receiveResponse(res); int statusCode = (int)res.getStatus(); string status = res.getReason(); // cout << status << endl; // cout << statusCode << endl; string uuid_str; is >> uuid_str; // cout << uuid_str << endl; //parse return Document uuid_doc; uuid_doc.Parse<0>(uuid_str.c_str()); Value& uuids = uuid_doc["Items"]; for(rapidjson::SizeType i = 0; i < uuids.Size();++i) { string id = uuids[i]["patent_id"]["S"].GetString(); //cout << id << endl; } // BSONBuilder buildObj; // string requestHeader = string("host:") + dbHost + '\n'; // requestHeader += string("x-amz-date:") + getAmzDate() +'\n'; // requestHeader += string("x-amz-target:") + "DynamoDB_20120810.CreateTable" +"\n"; // string requestStr = string("AWS4-HMAC-SHA256") + string("GET") + //HTTPRequest request(HTTPRequest::HTTP_POST, url.getPath(), HTTPRequest::HTTP_1_1); }
void TestParseBaaS::doAction(int tag) { std::function<void(int, std::string&)> callback = CC_CALLBACK_2(TestParseBaaS::onParseCallback, this); switch (tag) { case TAG_PF_SIGNUP: if (_protocolBaaS->isLoggedIn()) { _resultInfo->setString("Parse: please signout first"); } else { _resultInfo->setString("Signup with username: testuser & password: password"); map<string, string> userInfo; userInfo["username"] = "******"; userInfo["password"] = "******"; userInfo["email"] = "*****@*****.**"; _protocolBaaS->signUp(userInfo, callback); } break; case TAG_PF_LOGIN: { if (_protocolBaaS->isLoggedIn()) { _resultInfo->setString("Parse: login already."); } else { _protocolBaaS->login("testuser", "password", callback); } } break; case TAG_PF_LOGOUT: { if (_protocolBaaS->isLoggedIn()) { _protocolBaaS->logout(callback); } else { _resultInfo->setString("Parse: logout already."); } break; } case TAG_PF_WRITE_OBJECT: { srand((int) time(nullptr)); Document doc; doc.SetObject(); Document::AllocatorType &alloc = doc.GetAllocator(); int data = rand() % 100; string name = StringUtils::format("TestObject%d", data).c_str(); doc.AddMember("name", name.c_str(), alloc); doc.AddMember("data", data, alloc); StringBuffer buffer; Writer<StringBuffer, UTF8<> > writer(buffer); doc.Accept(writer); string sss(buffer.GetString(), buffer.GetString() + strlen(buffer.GetString())); _resultInfo->setString(StringUtils::format("Parse: writing object... %s", sss.c_str())); _protocolBaaS->saveObjectInBackground("testobject", buffer.GetString(), callback); break; } case TAG_PF_READ_OBJECT: { if (_lastObjectId.length() <= 0) { _resultInfo->setString("Please create an object to read"); } else { _protocolBaaS->getObjectInBackground("testobject", _lastObjectId, callback); } break; } case TAG_PF_UPDATE_OBJECT: { if (_lastObjectId.length() <= 0) { _resultInfo->setString("Please read an object."); } else { Document doc; doc.SetObject(); Document::AllocatorType &alloc = doc.GetAllocator(); int data = rand() % 100; doc.AddMember("data", data, alloc); StringBuffer buffer; Writer<StringBuffer, UTF8<> > writer(buffer); doc.Accept(writer); _protocolBaaS->updateObjectInBackground("testobject", _lastObjectId, buffer.GetString(), callback); } } default: break; } }
void Dlg_MemBookmark::ExportJSON() { if ( g_pCurrentGameData->GetGameID() == 0 ) { MessageBox( nullptr, _T("ROM not loaded: please load a ROM first!"), _T("Error!"), MB_OK ); return; } if ( m_vBookmarks.size() == 0) { MessageBox( nullptr, _T("No bookmarks to save: please create a bookmark before attempting to save."), _T("Error!"), MB_OK ); return; } std::string defaultDir = RA_DIR_BOOKMARKS; defaultDir.erase ( 0, 2 ); // Removes the characters (".\\") defaultDir = g_sHomeDir + defaultDir; IFileSaveDialog* pDlg = nullptr; HRESULT hr = CoCreateInstance( CLSID_FileSaveDialog, NULL, CLSCTX_ALL, IID_IFileSaveDialog, reinterpret_cast<void**>( &pDlg ) ); if ( hr == S_OK ) { hr = pDlg->SetFileTypes( ARRAYSIZE( c_rgFileTypes ), c_rgFileTypes ); if ( hr == S_OK ) { char defaultFileName[ 512 ]; sprintf_s ( defaultFileName, 512, "%s-Bookmarks.txt", std::to_string( g_pCurrentGameData->GetGameID() ).c_str() ); hr = pDlg->SetFileName( Widen( defaultFileName ).c_str() ); if ( hr == S_OK ) { PIDLIST_ABSOLUTE pidl; hr = SHParseDisplayName( Widen( defaultDir ).c_str(), NULL, &pidl, SFGAO_FOLDER, 0 ); if ( hr == S_OK ) { IShellItem* pItem = nullptr; SHCreateShellItem( NULL, NULL, pidl, &pItem ); hr = pDlg->SetDefaultFolder( pItem ); if ( hr == S_OK ) { pDlg->SetDefaultExtension( L"txt" ); hr = pDlg->Show( nullptr ); if ( hr == S_OK ) { hr = pDlg->GetResult( &pItem ); if ( hr == S_OK ) { LPWSTR pStr = nullptr; hr = pItem->GetDisplayName( SIGDN_FILESYSPATH, &pStr ); if ( hr == S_OK ) { Document doc; Document::AllocatorType& allocator = doc.GetAllocator(); doc.SetObject(); Value bookmarks( kArrayType ); for ( MemBookmark* bookmark : m_vBookmarks ) { Value item( kObjectType ); char buffer[ 256 ]; sprintf_s( buffer, Narrow( bookmark->Description() ).c_str(), sizeof( buffer ) ); Value s( buffer, allocator ); item.AddMember( "Description", s, allocator ); item.AddMember( "Address", bookmark->Address(), allocator ); item.AddMember( "Type", bookmark->Type(), allocator ); item.AddMember( "Decimal", bookmark->Decimal(), allocator ); bookmarks.PushBack( item, allocator ); } doc.AddMember( "Bookmarks", bookmarks, allocator ); _WriteBufferToFile( Narrow( pStr ), doc ); } pItem->Release(); ILFree( pidl ); } } } } } } pDlg->Release(); } }
int main(int argc, char** argv){ arma::wall_clock timer; //Keeps track of how much time my program is taking to run. timer.tic(); cout << "In this program I'm assuming that the given json model.adm file will follow a certain format, where keys will have an expected name." <<endl; //cout << "If no information is displaying after this line that means that you didn't input the two integer arguments for bodyID and constraintID." <<endl; //double constraintID = double(atof(argv[1])); cout << "Start of Assignment" <<endl; MyJsonDocument d = parseJSON("models/simplePend.acf"); string simulation = string(d["simulation"].GetString()); double tend = d["tend"].GetDouble(); double stepSize = d["stepSize"].GetDouble(); double outputSteps = d["outputSteps"].GetDouble(); cout << "Simulation = " + simulation <<endl; cout << "tend = "; cout << tend << endl; cout << "stepSize = "; cout << stepSize << endl; cout << "outputSteps = "; cout << outputSteps << endl; //static const char* kTypeNames[] = { "Null", "False", "True", "Object", "Array", "String", "Number" }; MyJsonDocument d4 = parseJSON("models/simplePend.adm"); cout << "parsing is fine" << endl; Model m(d4, simulation, tend,outputSteps,stepSize); /** vector<c_constraint*> constraints = m.getConstraints(); for(std::vector<int>::size_type i = 0; i != constraints.size(); i++) { constraints[i]->print(); }*/ m.solveK(); std::vector<arma::vec> q = m.getQList(); std::vector<arma::vec> qd = m.getQdList(); std::vector<arma::vec> qdd = m.getQddList(); double xAccPlot[2][(int)m.getOutputSteps()]; double trajectoryPlot[2][(int)m.getOutputSteps()]; Document doc; doc.SetObject(); rapidjson::Document::AllocatorType& allocator = doc.GetAllocator(); Value plot1(kArrayType); Value plot1X(kArrayType); Value plot1Y(kArrayType); Value plot2(kArrayType); Value plot2X(kArrayType); Value plot2Y(kArrayType); for(int i = 0; i <= m.getOutputSteps(); i++){ xAccPlot[0][i] = m.getStepSize()*i; xAccPlot[1][i] = qdd.at(i)(0); plot1X.PushBack(xAccPlot[0][i],allocator); plot1Y.PushBack(xAccPlot[1][i],allocator); trajectoryPlot[0][i] = q.at(i)(0); trajectoryPlot[1][i] = q.at(i)(1); plot2X.PushBack(trajectoryPlot[0][i],allocator); plot2Y.PushBack(trajectoryPlot[1][i],allocator); } plot1.PushBack(plot1X,allocator); plot1.PushBack(plot1Y,allocator); plot2.PushBack(plot2X,allocator); plot2.PushBack(plot2Y,allocator); doc.AddMember("Plot1",plot1,allocator); doc.AddMember("Plot2",plot2,allocator); StringBuffer strbuf; Writer<StringBuffer> writer(strbuf); doc.Accept(writer); std::string plotsData = strbuf.GetString(); ofstream dataFile ("plots/data.json"); if (dataFile.is_open()){ dataFile << plotsData; dataFile.close(); } else cout << "Unable to open file"; system( "python ../../repos/simEngine/python/plot2D.py" ); cout << "took " << timer.toc() << " seconds for part 2" << endl; return 0; }
rapidjson::Document SettingsConvertor::Convert() { using namespace rapidjson; Document json; json.SetObject(); Document::AllocatorType& al = json.GetAllocator(); #if (ME3D_BUILD == ME3D_BUILD_EDITOR) json.AddMember( "FILE_TYPE", "EDITOR_CONFIG", al ); json.AddMember( "editorWidth", EditorApp::Settings::width, al ); json.AddMember( "editorHeight", EditorApp::Settings::height, al ); json.AddMember( "editorPosX", EditorApp::Settings::posX, al ); json.AddMember( "editorPosY", EditorApp::Settings::posY, al ); Value objectNode; Value stringNode; { objectNode.SetObject(); EditorApp::WindowProperty wProp = EditorApp::Settings::windows[ Windows::Hierarchy ]; objectNode.AddMember( "visible", wProp.visible, al ); json.AddMember( "window_hierarchy", objectNode, al ); } { objectNode.SetObject(); EditorApp::WindowProperty wProp = EditorApp::Settings::windows[ Windows::Resources ]; objectNode.AddMember( "visible", wProp.visible, al ); json.AddMember( "window_resources", objectNode, al ); } { objectNode.SetObject(); EditorApp::WindowProperty wProp = EditorApp::Settings::windows[ Windows::Console ]; objectNode.AddMember( "visible", wProp.visible, al ); json.AddMember( "window_console", objectNode, al ); } { objectNode.SetObject(); EditorApp::WindowProperty wProp = EditorApp::Settings::windows[ Windows::Properties ]; objectNode.AddMember( "visible", wProp.visible, al ); json.AddMember( "window_properties", objectNode, al ); } { objectNode.SetObject(); EditorApp::WindowProperty wProp = EditorApp::Settings::windows[ Windows::Game ]; objectNode.AddMember( "visible", wProp.visible, al ); json.AddMember( "window_game", objectNode, al ); } { objectNode.SetObject(); EditorApp::WindowProperty wProp = EditorApp::Settings::windows[ Windows::Scene_1 ]; objectNode.AddMember( "visible", wProp.visible, al ); stringNode.SetString( wProp.renderer.ToChar(), al ); objectNode.AddMember( "renderer", stringNode, al ); objectNode.AddMember( "camera", wProp.camera, al ); json.AddMember( "window_scene_1", objectNode, al ); } { objectNode.SetObject(); EditorApp::WindowProperty wProp = EditorApp::Settings::windows[ Windows::Scene_2 ]; objectNode.AddMember( "visible", wProp.visible, al ); stringNode.SetString( wProp.renderer.ToChar(), al ); objectNode.AddMember( "renderer", stringNode, al ); objectNode.AddMember( "camera", wProp.camera, al ); json.AddMember( "window_scene_2", objectNode, al ); } { objectNode.SetObject(); EditorApp::WindowProperty wProp = EditorApp::Settings::windows[ Windows::Scene_3 ]; objectNode.AddMember( "visible", wProp.visible, al ); stringNode.SetString( wProp.renderer.ToChar(), al ); objectNode.AddMember( "renderer", stringNode, al ); objectNode.AddMember( "camera", wProp.camera, al ); json.AddMember( "window_scene_3", objectNode, al ); } { objectNode.SetObject(); EditorApp::WindowProperty wProp = EditorApp::Settings::windows[ Windows::Scene_4 ]; objectNode.AddMember( "visible", wProp.visible, al ); stringNode.SetString( wProp.renderer.ToChar(), al ); objectNode.AddMember( "renderer", stringNode, al ); objectNode.AddMember( "camera", wProp.camera, al ); json.AddMember( "window_scene_4", objectNode, al ); } { objectNode.SetObject(); EditorApp::WindowProperty wProp = EditorApp::Settings::windows[ Windows::Preview ]; objectNode.AddMember( "visible", wProp.visible, al ); json.AddMember( "window_preview", objectNode, al ); } stringNode.SetString( EditorApp::Settings::startScene.ToChar(), al ); json.AddMember( "startScene", stringNode, al ); #endif return json; }