コード例 #1
0
      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;
      }
コード例 #2
0
ファイル: sio_packet.cpp プロジェクト: 4ker/CamFiQt
 void accept_binary_message(binary_message const& msg,Value& val,Document& doc,vector<shared_ptr<const string> >& buffers)
 {
     val.SetObject();
     Value boolVal;
     boolVal.SetBool(true);
     val.AddMember(kBIN_PLACE_HOLDER, boolVal, doc.GetAllocator());
     Value numVal;
     numVal.SetInt((int)buffers.size());
     val.AddMember("num", numVal, doc.GetAllocator());
     //FIXME can not avoid binary copy here.
     shared_ptr<string> write_buffer = make_shared<string>();
     write_buffer->reserve(msg.get_binary()->size()+1);
     char frame_char = packet::frame_message;
     write_buffer->append(&frame_char,1);
     write_buffer->append(*(msg.get_binary()));
     buffers.push_back(write_buffer);
 }
コード例 #3
0
Document Device::setShootMode(const CString &shootMode)
{
	Document d;
	CString type = "camera";
	Value method;
	method = "setShootMode";
	Value params;
	params.SetArray();
	if (shootMode == "still")
	params.PushBack("still", d.GetAllocator());
	if (shootMode == "movie")
		params.PushBack("movie", d.GetAllocator());
	Value version;
	version = "1.0";
	return sendApi(type, method, params, version);

}
コード例 #4
0
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());
}
コード例 #5
0
ファイル: sio_packet.cpp プロジェクト: 4ker/CamFiQt
 void accept_array_message(array_message const& msg,Value& val,Document& doc,vector<shared_ptr<const string> >& buffers)
 {
     val.SetArray();
     for (vector<message::ptr>::const_iterator it = msg.get_vector().begin(); it!=msg.get_vector().end(); ++it) {
         Value child;
         accept_message(*(*it), child, doc,buffers);
         val.PushBack(child, doc.GetAllocator());
     }
 }
コード例 #6
0
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;
}
コード例 #7
0
// 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);
}
コード例 #8
0
Document Device::actZoom(CString direction, CString movement)
{
	Document d;
	CString type = "camera";
	Value method;
	method = "actZoom";

	Value params;
	params.SetArray();
	//direction
	Value s;
	s.SetString(direction, d.GetAllocator());
	params.PushBack(s, d.GetAllocator());
	//movement
	s.SetString(movement, d.GetAllocator());
	params.PushBack(s, d.GetAllocator());

	Value version;
	version = "1.0";
	return sendApi(type, method, params, version);
}
コード例 #9
0
Document Device::setPostviewImageSize(){
	Document d;
	CString type = "camera";
	Value method;
	method = "setPostviewImageSize";
	Value params;
	params.SetArray();
	params.PushBack("Original", d.GetAllocator());

	Value version;
	version = "1.0";
	return sendApi(type, method, params, version);

}
コード例 #10
0
ファイル: main.cpp プロジェクト: ak47-nexon/asioserver
	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();

			}
		});
	}
コード例 #11
0
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;
}
コード例 #12
0
ファイル: stream.cpp プロジェクト: alexeyche/alexeyche-junk
void Stream::writeObject(SerializableBase *b) {
	if (!isOutput()) {
		throw dnnException()<< "Stream isn't open in output mode. Need output stream\n";
	}

	vector<ProtoMessage> messages = b->getSerialized();

	if (getRepr() == Text) {
		vector<string> buff;
		Document d;
		Value o(kObjectType);		
		string temps = b->name();
		if(!Factory::inst().isProtoType(temps)) {
			Value sub_o(kObjectType);
			for (auto &m : messages) {
				if(m->GetTypeName() != "Protos.ClassName") {
					Document *sub_d = Json::parseProtobuf(m);
					buff.push_back(m->GetTypeName());
					sub_o.AddMember(StringRef(buff.back().c_str()), *sub_d, d.GetAllocator());
				}
			}
			o.AddMember(StringRef(temps.c_str()), sub_o, d.GetAllocator());
		} else {
			assert(messages.size() == 2);
			Document *sub_d = Json::parseProtobuf(messages[1]);
			o.AddMember(StringRef(temps.c_str()), *sub_d, d.GetAllocator());
		}

		(*_output_str) << Json::stringify(o);
	} else if (getRepr() == Binary) {
		for (auto &m : messages) {
			writeBinaryMessage(m, _output_str);
		}
	}

}
コード例 #13
0
ファイル: x_json.cpp プロジェクト: XCopterStudio/xcs
string XJson::encode(const ::urbi::UValue& data) {
    if (data.type != ::urbi::DATA_DICTIONARY && data.type != ::urbi::DATA_LIST) {
        send("throw \"Only UList or UDictionary are supported by UJson.\";");
        return "";
    }
    Document doc;
    StringBuffer stream;

    Writer<StringBuffer> writer(stream);

    unique_ptr<Value> valPtr(fromUValue(data, doc.GetAllocator()));
    (*valPtr).Accept(writer);

    string result(stream.GetString());
    stream.Clear();
    return result;
}
コード例 #14
0
ファイル: main.cpp プロジェクト: aa4145/PlayPhone
Value addControl(Document& root, const char* type, int x, int y, int w, int h, int id){
    Document::AllocatorType& a = root.GetAllocator();
    
    Value ctl;
    ctl.SetObject();
    ctl.AddMember("type", StringRef(type), a);
    ctl.AddMember("id", id, a);
    
    Value frame;
    frame.SetObject();
    frame.AddMember("x", x, a);
    frame.AddMember("y", y, a);
    frame.AddMember("w", w, a);
    frame.AddMember("h", h, a);
    ctl.AddMember("frame", frame, a);
    
    return ctl;
}
コード例 #15
0
TEST(Document, UnchangedOnParseError) {
    Document doc;
    doc.SetArray().PushBack(0, doc.GetAllocator());

    ParseResult err = doc.Parse("{]");
    EXPECT_TRUE(doc.HasParseError());
    EXPECT_EQ(err.Code(), doc.GetParseError());
    EXPECT_EQ(err.Offset(), doc.GetErrorOffset());
    EXPECT_TRUE(doc.IsArray());
    EXPECT_EQ(doc.Size(), 1u);

    err = doc.Parse("{}");
    EXPECT_FALSE(doc.HasParseError());
    EXPECT_FALSE(err.IsError());
    EXPECT_EQ(err.Code(), doc.GetParseError());
    EXPECT_EQ(err.Offset(), doc.GetErrorOffset());
    EXPECT_TRUE(doc.IsObject());
    EXPECT_EQ(doc.MemberCount(), 0u);
}
コード例 #16
0
ファイル: ZatData.cpp プロジェクト: vdrtuxnet/pvr.zattoo
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;
}
コード例 #17
0
ファイル: FoldersService.cpp プロジェクト: jurda23/homeis
void FoldersService::FolderToJson(HisBase *pFolder, Document & respjsondoc)
{
	Value d(kObjectType);
	string strvalue = pFolder->GetName();
	Value jsonvalue;
	jsonvalue.SetString(strvalue.c_str(),strvalue.length(),respjsondoc.GetAllocator());
	d.AddMember("name",jsonvalue, respjsondoc.GetAllocator());

	strvalue = pFolder->GetRecordId().ToString();
	jsonvalue.SetString(strvalue.c_str(),strvalue.length(),respjsondoc.GetAllocator());
	d.AddMember("id",jsonvalue, respjsondoc.GetAllocator());

	if (pFolder->GetParent()->GetRecordId()!=root->GetFolder()->GetRecordId())
	{
		strvalue = pFolder->GetParent()->GetRecordId().ToString();
		jsonvalue.SetString(strvalue.c_str(),strvalue.length(),respjsondoc.GetAllocator());
		d.AddMember("parentId",jsonvalue, respjsondoc.GetAllocator());
	}
	respjsondoc.PushBack(d, respjsondoc.GetAllocator());
}
コード例 #18
0
TYPED_TEST(DocumentMove, MoveConstructorStack) {
    typedef TypeParam Allocator;
    typedef UTF8<> Encoding;
    typedef GenericDocument<Encoding, Allocator> Document;

    Document a;
    size_t defaultCapacity = a.GetStackCapacity();

    // Trick Document into getting GetStackCapacity() to return non-zero
    typedef GenericReader<Encoding, Encoding, Allocator> Reader;
    Reader reader(&a.GetAllocator());
    GenericStringStream<Encoding> is("[\"one\", \"two\", \"three\"]");
    reader.template Parse<kParseDefaultFlags>(is, a);
    size_t capacity = a.GetStackCapacity();
    EXPECT_GT(capacity, 0u);

    Document b(std::move(a));
    EXPECT_EQ(a.GetStackCapacity(), defaultCapacity);
    EXPECT_EQ(b.GetStackCapacity(), capacity);

    Document c = std::move(b);
    EXPECT_EQ(b.GetStackCapacity(), defaultCapacity);
    EXPECT_EQ(c.GetStackCapacity(), capacity);
}
コード例 #19
0
ファイル: opts.cpp プロジェクト: picopter/picopterx
/**
 * 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());
        }
    }
}
コード例 #20
0
ファイル: TesrRapidJsonMain.cpp プロジェクト: mlqcmlmc/MyCode
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;
}
コード例 #21
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;
}
コード例 #22
0
ファイル: assignment7.cpp プロジェクト: felipegb94/simEngine
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;
}
コード例 #23
0
/**
 * 将两个anchor的incomming和outgoing部分分别合并,并将结果存入dst_anchor
 * @param src_anchor anchor1
 * @param dst_anchor anchor2,同时也是保存结果的anchor
 * @return
 */
bool VersionControlLayer::mergeAnchors(Value& src_anchor,
                                       Value& dst_anchor,
                                       Value& filt_anchor,
                                       Document& doc)
{
    Value& v_src_incomming  = src_anchor["@incomingConnections"];
    Value& v_src_outgoing   = src_anchor["@outgoingConnections"];
    Value& v_dst_incomming  = dst_anchor["@incomingConnections"];
    Value& v_dst_outgoing   = dst_anchor["@outgoingConnections"];
    Value& v_filt_incomming = filt_anchor["@incomingConnections"];
    Value& v_filt_outgoing  = filt_anchor["@outgoingConnections"];

    string s_src_incomming(v_src_incomming.GetString());
    string s_src_outgoing(v_src_outgoing.GetString());
    string s_dst_incomming(v_dst_incomming.GetString());
    string s_dst_outgoing(v_dst_outgoing.GetString());
    string s_filt_incomming(v_filt_incomming.GetString());
    string s_filt_outgoing(v_filt_outgoing.GetString());

    set<string> srcIncomming, srcOutgoing;
    set<string> mergeIncomming, mergeOutgoing, mergeFilter;

    splitStringToSet(s_filt_incomming, " ", &mergeFilter, NULL);
    splitStringToSet(s_dst_incomming, " ", &mergeIncomming, NULL);
    splitStringToSet(s_src_incomming, " ", &srcIncomming, NULL);
    filtId(&mergeIncomming, &mergeFilter, &srcIncomming);
    splitStringToSet(s_src_incomming, " ", &mergeIncomming, &mergeFilter);

    mergeFilter.clear();
    splitStringToSet(s_filt_outgoing, " ", &mergeFilter, NULL);
    splitStringToSet(s_dst_outgoing, " ", &mergeOutgoing, NULL);
    splitStringToSet(s_src_outgoing, " ", &srcOutgoing, NULL);
    filtId(&mergeOutgoing, &mergeFilter, &srcOutgoing);
    splitStringToSet(s_src_outgoing, " ", &mergeOutgoing, &mergeFilter);

    // ---------incomminng---------->>>
    string s_mergeIncomming = "";
    for(auto it=mergeIncomming.begin();it!=mergeIncomming.end();it++)
    {
        s_mergeIncomming += *it;
        s_mergeIncomming += " ";
    }
    v_dst_incomming.SetString(s_mergeIncomming.c_str(), s_mergeIncomming.size(), doc.GetAllocator());
    // <<<-------incomming--------------

    // ---------outgoing---------->>>
    string s_mergeOutgoing = "";
    for(auto it=mergeOutgoing.begin();it!=mergeOutgoing.end();it++)
    {
        s_mergeOutgoing += *it;
        s_mergeOutgoing += " ";
    }
    v_dst_outgoing.SetString(s_mergeOutgoing.c_str(), s_mergeOutgoing.size(), doc.GetAllocator());
    // <<<-------outgoing--------------

//    StringBuffer buffer1;
//    Writer<StringBuffer> writer1(buffer1);
//    dst_anchor.Accept(writer1);
//    // Output
//    std::cout << buffer1.GetString() << std::endl;
    
    return true;
}
コード例 #24
0
ファイル: profile_ctx.cpp プロジェクト: kku1993/ispc
std::string ProfileRegion::outputJSON() {
  const char *base = 
    "{"
      "\"region_id\":0,"
      "\"region_type\":0,"
      "\"file_name\":\"\","
      "\"start_line\":0,"
      "\"end_line\":0,"
      "\"initial_mask\":0,"
      "\"lane_usage\":[],"
      "\"full_mask_percentage\": [],"
      "\"ipc\":0,"
      "\"l2_hit\":0,"
      "\"l3_hit\":0,"
      "\"bytes_read\":0"
    "}";

  Document d;
  d.Parse(base);

  d["region_id"].SetUint64(this->id);
  d["region_type"].SetInt(this->region_type);
  d["file_name"].SetString(StringRef(this->file_name));
  d["start_line"].SetInt(this->start_line);
  d["end_line"].SetInt(this->end_line);
  d["initial_mask"].SetUint64(this->initial_mask);
  d["ipc"].SetDouble(this->avg_ipc);
  d["l2_hit"].SetDouble(this->avg_l2_hit);
  d["l3_hit"].SetDouble(this->avg_l3_hit);
  d["bytes_read"].SetDouble(this->avg_bytes_read);

  // Add list of lane usage by line number.
  Value &lane_usage = d["lane_usage"];
  Document::AllocatorType &allocator = d.GetAllocator();
  for (LaneUsageMap::iterator it = this->laneUsageMap.begin(); 
      it != this->laneUsageMap.end(); ++it) {
    Value line(kObjectType);

    double percent = it->second.second/double(it->second.first) * 100;

    line.AddMember("line", it->first, allocator);
    line.AddMember("percent", percent, allocator);

    lane_usage.PushBack(line, allocator); 
  }

  // Add list of percent of full mask runs by line number.
  Value &full_mask = d["full_mask_percentage"];
  for (LaneUsageMap::iterator it = this->fullMaskMap.begin(); 
      it != this->fullMaskMap.end(); ++it) {
    Value line(kObjectType);

    double percent = it->second.second/double(it->second.first) * 100;

    line.AddMember("line", it->first, allocator);
    line.AddMember("percent", percent, allocator);

    full_mask.PushBack(line, allocator); 
  }
  
  // Stringify the DOM
  StringBuffer buffer;
  Writer<StringBuffer> writer(buffer);
  d.Accept(writer);

  std::string str(buffer.GetString());
  return str;
}
コード例 #25
0
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();
	}
}
コード例 #26
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;
}
コード例 #27
0
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;
    }
}
コード例 #28
0
ファイル: sign.cpp プロジェクト: loveclj/c-
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);
}
コード例 #29
0
// Returns printer status as a JSON formatted string.
std::string PrinterStatus::ToString() const
{
    std::string retVal = "";
   
    std::ostringstream json;
    json << "{" <<
            "\"" << STATE_PS_KEY           << "\": \"\"," <<
            "\"" << UISUBSTATE_PS_KEY      << "\": \"\"," <<
            "\"" << CHANGE_PS_KEY          << "\": \"\"," <<
            "\"" << IS_ERROR_PS_KEY        << "\": false," <<
            "\"" << ERROR_CODE_PS_KEY      << "\": 0," <<
            "\"" << ERRNO_PS_KEY           << "\": 0," <<
            "\"" << ERROR_MSG_PS_KEY       << "\": \"\"," <<
            "\"" << JOB_NAME_PS_KEY        << "\": \"\"," <<  
            "\"" << JOB_ID_PS_KEY          << "\": \"\"," <<  
            "\"" << LAYER_PS_KEY           << "\": 0," <<
            "\"" << TOTAL_LAYERS_PS_KEY    << "\": 0," <<
            "\"" << SECONDS_LEFT_PS_KEY    << "\": 0," <<
            "\"" << TEMPERATURE_PS_KEY     << "\": 0.0," <<
            "\"" << PRINT_RATING_PS_KEY    << "\": \"\"," <<
            "\"" << SPARK_STATE_PS_KEY     << "\": \"\"," <<
            "\"" << SPARK_JOB_STATE_PS_KEY << "\": \"\"," <<
            "\"" << LOCAL_JOB_UUID_PS_KEY  << "\": \"\"," <<
            "\"" << CAN_LOAD_PS_KEY        << "\": \"\"" <<
            "}";
    
    try
    {
        std::string jsonString = json.str();
        Document doc;
        doc.Parse(jsonString.c_str());
        
        Value value;
        const char* state = GetStateName(_state);
        value.SetString(state, strlen(state), doc.GetAllocator());       
        doc[STATE_PS_KEY] = value; 
        
        const char* substate = GetSubStateName(_UISubState);
        value.SetString(substate, strlen(substate), doc.GetAllocator()); 
        doc[UISUBSTATE_PS_KEY] = value;
       
        if (_change == Entering)
           value.SetString(StringRef(ENTERING));
        else if (_change == Leaving)
           value.SetString(StringRef(LEAVING));
        else
            value.SetString(StringRef(NO_CHANGE));
        doc[CHANGE_PS_KEY] = value; 

        if (_printRating == Succeeded)
           value.SetString(StringRef(PRINT_SUCCESSFUL));
        else if (_printRating == Failed)
           value.SetString(StringRef(PRINT_FAILED));
        else
           value.SetString(StringRef(UNKNOWN_PRINT_FEEDBACK));
        doc[PRINT_RATING_PS_KEY] = value;         
        
        doc[IS_ERROR_PS_KEY] = _isError;        
        doc[ERROR_CODE_PS_KEY] = _errorCode; 
        doc[ERRNO_PS_KEY] = _errno; 
        value.SetString(GetLastErrorMessage().c_str(), 
                    GetLastErrorMessage().size(), doc.GetAllocator()); 
        doc[ERROR_MSG_PS_KEY] = value;       
        
        // job name comes from settings rather than PrinterStatus
        std::string ss = 
                    PrinterSettings::Instance().GetString(JOB_NAME_SETTING);
        value.SetString(ss.c_str(), ss.size(), doc.GetAllocator()); 
        doc[JOB_NAME_PS_KEY] = value;        
        
        value.SetString(_jobID.c_str(), _jobID.size(), doc.GetAllocator()); 
        doc[JOB_ID_PS_KEY] = value;        
        
        doc[LAYER_PS_KEY] = _currentLayer;
        doc[TOTAL_LAYERS_PS_KEY] = _numLayers;
        doc[SECONDS_LEFT_PS_KEY] = _estimatedSecondsRemaining;
        doc[TEMPERATURE_PS_KEY] = _temperature;
        
        // get the Spark API printer and job states
        ss = SparkStatus::GetSparkStatus(_state, _UISubState, 
                                                            _canLoadPrintData);
        value.SetString(ss.c_str(), ss.size(), doc.GetAllocator()); 
        doc[SPARK_STATE_PS_KEY] = value;
        
        // we know we're printing if we have a non-zero number of layers 
        ss = SparkStatus::GetSparkJobStatus(_state, _UISubState, 
                                                                _numLayers > 0);
        value.SetString(ss.c_str(), ss.size(), doc.GetAllocator()); 
        doc[SPARK_JOB_STATE_PS_KEY] = value;
        
        // write the UUID used by Spark for local jobs
        value.SetString(_localJobUniqueID, strlen(_localJobUniqueID), 
                                                            doc.GetAllocator()); 
        doc[LOCAL_JOB_UUID_PS_KEY] = value;
        
        doc[CAN_LOAD_PS_KEY] = _canLoadPrintData;   
        
        StringBuffer buffer; 
        Writer<StringBuffer> writer(buffer);
        doc.Accept(writer);        
        retVal = std::string(buffer.GetString()) + "\n";
    }
    catch(std::exception)
    {
        Logger::HandleError(PrinterStatusToString);
    }
    return retVal; 
}