Beispiel #1
0
Field SchemaHelper::parseField(const rapidjson::Document &data, int index)
{
    Field field = std::make_shared<SchemaField>();
    field->index = index;
    field->name = getJSONString(data, "name");
    field->type = getJSONString(data, "type");
    field->geometry_type = getJSONString(data, "geometry_type");
    field->nullable = getJSONBool(data, "nullable");
    field->related_to = getJSONLong(data, "related_to", -1);
    field->max_length = getJSONInt(data, "max_length", -1);
    field->default_value = getJSONString(data, "default");

    StringBuffer buffer;
    PrettyWriter<StringBuffer> writer(buffer);
    data.Accept(writer);
    field->json = buffer.GetString();

    if(field->name == "amigo_id")
    {
        field->unique = true;
    }
    return field;
}
TEST(Writer, ValidateEncoding)
{
  { StringBuffer buffer;
    Writer<StringBuffer, UTF8<>, UTF8<>, CrtAllocator, kWriteValidateEncodingFlag> writer(buffer);
    writer.StartArray();
    EXPECT_TRUE(writer.String("\x24"));             // Dollar sign U+0024
    EXPECT_TRUE(writer.String("\xC2\xA2"));         // Cents sign U+00A2
    EXPECT_TRUE(writer.String("\xE2\x82\xAC"));     // Euro sign U+20AC
    EXPECT_TRUE(writer.String("\xF0\x9D\x84\x9E")); // G clef sign U+1D11E
    writer.EndArray();
    EXPECT_STREQ("[\"\x24\",\"\xC2\xA2\",\"\xE2\x82\xAC\",\"\xF0\x9D\x84\x9E\"]", buffer.GetString());
  }

  // Fail in decoding invalid UTF-8 sequence http://www.cl.cam.ac.uk/~mgk25/ucs/examples/UTF-8-test.txt
  { StringBuffer buffer;
    Writer<StringBuffer, UTF8<>, UTF8<>, CrtAllocator, kWriteValidateEncodingFlag> writer(buffer);
    writer.StartArray();
    EXPECT_FALSE(writer.String("\xfe"));
    EXPECT_FALSE(writer.String("\xff"));
    EXPECT_FALSE(writer.String("\xfe\xfe\xff\xff"));
    writer.EndArray();
  }
}
Beispiel #3
0
TEST(SchemaValidatingWriter, Simple) {
    Document sd;
    sd.Parse("{\"type\":\"string\",\"minLength\":2,\"maxLength\":3}");
    SchemaDocument s(sd);

    Document d;
    StringBuffer sb;
    Writer<StringBuffer> writer(sb);
    GenericSchemaValidator<SchemaDocument, Writer<StringBuffer> > validator(s, writer);

    d.Parse("\"red\"");
    EXPECT_TRUE(d.Accept(validator));
    EXPECT_TRUE(validator.IsValid());
    EXPECT_STREQ("\"red\"", sb.GetString());

    sb.Clear();
    validator.Reset();
    d.Parse("\"ABCD\"");
    EXPECT_FALSE(d.Accept(validator));
    EXPECT_FALSE(validator.IsValid());
    EXPECT_TRUE(validator.GetInvalidSchemaPointer() == SchemaDocument::PointerType(""));
    EXPECT_TRUE(validator.GetInvalidDocumentPointer() == SchemaDocument::PointerType(""));
}
TEST(Document, ParseStream_AutoUTFInputStream) {
    // Any -> UTF8
    FILE* fp = OpenEncodedFile("utf32be.json");
    char buffer[256];
    FileReadStream bis(fp, buffer, sizeof(buffer));
    AutoUTFInputStream<unsigned, FileReadStream> eis(bis);

    Document d;
    d.ParseStream<0, AutoUTF<unsigned> >(eis);
    EXPECT_FALSE(d.HasParseError());

    fclose(fp);

    char expected[] = "I can eat glass and it doesn't hurt me.";
    Value& v = d["en"];
    EXPECT_TRUE(v.IsString());
    EXPECT_EQ(sizeof(expected) - 1, v.GetStringLength());
    EXPECT_EQ(0, StrCmp(expected, v.GetString()));

    // UTF8 -> UTF8 in memory
    StringBuffer bos;
    Writer<StringBuffer> writer(bos);
    d.Accept(writer);

    {
        // Condense the original file and compare.
        FILE *fp = OpenEncodedFile("utf8.json");
        FileReadStream is(fp, buffer, sizeof(buffer));
        Reader reader;
        StringBuffer bos2;
        Writer<StringBuffer> writer(bos2);
        reader.Parse(is, writer);

        EXPECT_EQ(bos.GetSize(), bos2.GetSize());
        EXPECT_EQ(0, memcmp(bos.GetString(), bos2.GetString(), bos2.GetSize()));
    }
}
Beispiel #5
0
TEST(test_emws_seger, test_emws_seger_test_save) {
    el::Logger *testLogger = el::Loggers::getLogger("emws_seger_unittest");

    using namespace std;
    using namespace rapidjson;

    const string filename = "./conf/emws_config.json";
    FILE* fp = fopen(filename.data(), "rb");
    char readBuffer[65536];
    FileReadStream is(fp, readBuffer, sizeof(readBuffer));
    Document config;
    config.ParseStream(is);
    fclose(fp);

    StringBuffer buffer;
    PrettyWriter<StringBuffer> writer(buffer);
    config.Accept(writer);

    testLogger->info("=====parameters====\n%v", buffer.GetString());

    testLogger->info("initial model ...");
    string const model_name = "emws";
    base_seger *seger = base_seger::create_seger(config, model_name);

    string const model_path = utf8_io::gen_model_path(model_name, "./model");
    testLogger->info("save model to %v\n\n", model_path);
    // save model
    bool ret = seger->save(model_path);
    EXPECT_EQ(ret, true);

    // load model
    testLogger->info("load model ...");
    base_seger *loaded_seger = base_seger::load(model_path, model_name);
    testLogger->info("train ...");
    loaded_seger->train();
    testLogger->info("train done");
}
Beispiel #6
0
	bool FileUtil::SaveToFile(const Serializable::Ptr &source, const std::string &filePath)
	{
		using namespace rapidjson;

		std::ofstream output(filePath);
		if (output)
		{
			StringBuffer sb;
			PrettyWriter<StringBuffer> writer(sb);

			if (!source->Save(&writer))
			{
				LOGE << "Serialization failed!";
				return false;
			}

			output << sb.GetString();
			output.close();

			LOGD << filePath << " successfully serialized!";
			return true;
		}
		return false;
	}
Beispiel #7
0
void FoldersService::render_GET(const http_request& req, http_response** res)
{
	Document respjsondoc;
	respjsondoc.SetArray();

	string strid = req.get_arg("id");
	HisDevFolder* folder = root->GetFolder();
	string path = req.get_path();
	if(!strid.empty())
	{
		CUUID id = CUUID::Parse(strid);
		folder = dynamic_cast<HisDevFolder*>(folder->Find(id));
	}

	if (path.find("/api/folders")!=string::npos)
	{
		if (folder!=NULL)
		{
			FoldersToJson(folder,respjsondoc);
		}
	}
	else if (path.find("/api/folder")!=string::npos)
	{
		if (folder!=NULL)
		{
			FolderToJson(folder,respjsondoc);
		}
	}


	StringBuffer buffer;
	PrettyWriter<StringBuffer> wr(buffer);
	respjsondoc.Accept(wr);
	std::string json = buffer.GetString();
	*res = new http_string_response(json, 200, "application/json");
}
Beispiel #8
0
int ytopen_sdk::SetInfo(rapidjson::Document &result, const string& person_id, const string& person_name, const string& tag)
{
    std::stringstream ss;
    ss<<host<<"/youtu/api/setinfo";

    string addr;
    addr.assign(ss.str());

    string req;
    string rsp;

    StringBuffer sbuffer;
    Writer<StringBuffer> writer(sbuffer);

    writer.StartObject();
    writer.String("app_id"); writer.String(app_id.c_str());
    writer.String("person_id"); writer.String(person_id.c_str());
    writer.String("person_name"); writer.String(person_name.c_str());
    writer.String("tag"); writer.String(tag.c_str());
    writer.EndObject();

    req = sbuffer.GetString();
    int ret = curl_method(addr, req, rsp);
    if(ret == 0) {
        result.Parse<rapidjson::kParseStopWhenDoneFlag>(rsp.c_str());
        if(result.HasParseError()) {
            std::cout << "RapidJson parse error " << result.GetParseError() << endl;
            return -1;
        }

    }else {
        return -1;
    }

    return 0;
}
Beispiel #9
0
BOOST_FIXTURE_TEST_CASE( mo_serialize , BaseFixture ) {
    MOSerializer serializer(&db);
    StringBuffer buffer;
    Writer<StringBuffer> writer(buffer);

    shared_ptr<ObjectInstance> oi = 
        shared_ptr<ObjectInstance>(new ObjectInstance(1));
    oi->setUInt64(1, 42);
    oi->addString(2, "test1");
    oi->addString(2, "test2");
    URI uri("/");
    client1->put(1, uri, oi);

    shared_ptr<ObjectInstance> oi2 = 
        shared_ptr<ObjectInstance>(new ObjectInstance(2));
    oi2->setInt64(4, -42);
    URI uri2("/class2/-42");
    client1->put(2, uri2, oi2);
    client1->addChild(1, uri, 3, 2, uri2);

    shared_ptr<ObjectInstance> oi3 = 
        shared_ptr<ObjectInstance>(new ObjectInstance(2));
    oi3->setInt64(4, -84);
    URI uri3("/class2/-84");
    client1->put(2, uri3, oi3);
    client1->addChild(1, uri, 3, 2, uri3);

    writer.StartObject();

    writer.String("result");

    writer.StartObject();
    writer.String("policy");
    writer.StartArray();
    serializer.serialize(1, uri, *client1, writer);
    writer.EndArray();

    writer.String("prr");
    writer.Uint(3600);
    writer.EndObject();
    
    writer.String("id");
    writer.Uint(42);
    writer.EndObject();

    //std::cout << buffer.GetString() << std::endl;

    Document d;
    d.Parse(buffer.GetString());
    const Value& result = d["result"];
    BOOST_CHECK(result.IsObject());
    const Value& prr = result["prr"];
    BOOST_CHECK(prr.IsUint());
    BOOST_CHECK_EQUAL(3600, prr.GetInt());

    const Value& policy = result["policy"];
    BOOST_CHECK(policy.IsArray());
    BOOST_CHECK_EQUAL(3, policy.Size());
    
    const Value& mo1 = policy[SizeType(0)];
    BOOST_CHECK_EQUAL("class1", const_cast<char *>(mo1["subject"].GetString()));
    BOOST_CHECK_EQUAL("/", const_cast<char *>(mo1["uri"].GetString()));
    const Value& mo1props = mo1["properties"];
    BOOST_CHECK(mo1props.IsArray());
    BOOST_CHECK_EQUAL(2, mo1props.Size());
    const Value& mo1children = mo1["children"];
    BOOST_CHECK(mo1children.IsArray());
    BOOST_CHECK_EQUAL(2, mo1children.Size());

    for (SizeType i = 0; i < mo1children.Size(); ++i) {
        const Value& child = mo1children[i];
        BOOST_CHECK(child.IsString());
        BOOST_CHECK(std::string("/class2/-42") == child.GetString() ||
                    std::string("/class2/-84") == child.GetString());

        const Value& mo2 = policy[SizeType(i+1)];
        BOOST_CHECK(std::string("/class2/-42") == mo2["uri"].GetString() ||
                    std::string("/class2/-84") == mo2["uri"].GetString());
        BOOST_CHECK_EQUAL("class2", const_cast<char *>(mo2["subject"].GetString()));
        BOOST_CHECK_EQUAL("class1", const_cast<char *>(mo2["parent_subject"].GetString()));
        BOOST_CHECK_EQUAL("/", const_cast<char *>(mo2["parent_uri"].GetString()));
        BOOST_CHECK_EQUAL("class2", const_cast<char *>(mo2["parent_relation"].GetString()));
        const Value& mo2props = mo2["properties"];
        BOOST_CHECK(mo2props.IsArray());
        BOOST_CHECK_EQUAL(1, mo2props.Size());
        const Value& mo2children = mo2["children"];
        BOOST_CHECK(mo2children.IsArray());
        BOOST_CHECK_EQUAL(0, mo2children.Size());

    }
}
Beispiel #10
0
TEST(Writer, Compact) {
    StringStream s("{ \"hello\" : \"world\", \"t\" : true , \"f\" : false, \"n\": null, \"i\":123, \"pi\": 3.1416, \"a\":[1, 2, 3] } ");
    StringBuffer buffer;
    Writer<StringBuffer> writer(buffer);
    buffer.ShrinkToFit();
    Reader reader;
    reader.Parse<0>(s, writer);
    EXPECT_STREQ("{\"hello\":\"world\",\"t\":true,\"f\":false,\"n\":null,\"i\":123,\"pi\":3.1416,\"a\":[1,2,3]}", buffer.GetString());
    EXPECT_EQ(77u, buffer.GetSize());
    EXPECT_TRUE(writer.IsComplete());
}
Beispiel #11
0
BOOST_FIXTURE_TEST_CASE( types , BaseFixture ) {
    MOSerializer serializer(&db);
    StringBuffer buffer;
    Writer<StringBuffer> writer(buffer);

    StoreClient& sysClient = db.getStoreClient("_SYSTEM_");
    URI c2u("/class2/32/");
    URI c4u("/class4/test/");
    URI c5u("/class5/test/");
    URI c6u("/class4/test/class6/test2/");
    URI c7u("/class4/test/class7/0");

    shared_ptr<ObjectInstance> oi1 = make_shared<ObjectInstance>(1);
    shared_ptr<ObjectInstance> oi2 = make_shared<ObjectInstance>(2);
    shared_ptr<ObjectInstance> oi4 = make_shared<ObjectInstance>(4);
    shared_ptr<ObjectInstance> oi5 = make_shared<ObjectInstance>(5);
    shared_ptr<ObjectInstance> oi6 = make_shared<ObjectInstance>(6);
    shared_ptr<ObjectInstance> oi7 = make_shared<ObjectInstance>(7);

    oi2->setInt64(4, 32);
    oi2->setMAC(15, MAC("aa:bb:cc:dd:ee:ff"));
    oi5->setString(10, "test");
    oi5->addReference(11, 4, c4u);
    oi4->setString(9, "test");
    oi6->setString(13, "test2");
    oi7->setUInt64(14, 0);

    sysClient.put(1, URI::ROOT, oi1);
    sysClient.put(2, c2u, oi2);
    sysClient.put(4, c4u, oi4);
    sysClient.put(5, c5u, oi5);
    sysClient.put(6, c6u, oi6);
    sysClient.put(7, c7u, oi7);
    sysClient.addChild(1, URI::ROOT, 3, 2, c2u);
    sysClient.addChild(1, URI::ROOT, 8, 4, c4u);
    sysClient.addChild(1, URI::ROOT, 24, 5, c5u);
    sysClient.addChild(4, c4u, 12, 6, c6u);
    sysClient.addChild(4, c4u, 25, 7, c7u);

    writer.StartArray();
    serializer.serialize(1, URI::ROOT, sysClient, writer);
    writer.EndArray();
    string str(buffer.GetString());

    //std::cerr << str << std::endl;

    sysClient.remove(1, URI::ROOT, true);
    BOOST_CHECK_THROW(sysClient.get(1, URI::ROOT), out_of_range);
    BOOST_CHECK_THROW(sysClient.get(2, c2u), out_of_range);
    BOOST_CHECK_THROW(sysClient.get(4, c4u), out_of_range);
    BOOST_CHECK_THROW(sysClient.get(5, c5u), out_of_range);
    BOOST_CHECK_THROW(sysClient.get(6, c6u), out_of_range);
    BOOST_CHECK_THROW(sysClient.get(7, c7u), out_of_range);

    Document d;
    d.Parse(str.c_str());
    Value::ConstValueIterator it;
    for (it = d.Begin(); it != d.End(); ++it) {
        serializer.deserialize(*it, sysClient, true, NULL);
    }
    BOOST_CHECK_EQUAL("test", sysClient.get(4, c4u)->getString(9));
    BOOST_CHECK_EQUAL("test", sysClient.get(5, c5u)->getString(10));
    BOOST_CHECK(make_pair((class_id_t)4ul, c4u) == 
                sysClient.get(5, c5u)->getReference(11, 0));
    BOOST_CHECK_EQUAL("test2", sysClient.get(6, c6u)->getString(13));
    BOOST_CHECK_EQUAL(0, sysClient.get(7, c7u)->getUInt64(14));
    BOOST_CHECK_EQUAL(MAC("aa:bb:cc:dd:ee:ff"), sysClient.get(2, c2u)->getMAC(15));
}
Beispiel #12
0
int NodeBtHandler (int argc, char *argv[])
{
  // DDS değişkenleri
  DDSEntityManager                    mgrBtPub;
  DDSEntityManager                    mgrReqSub;
  ReturnCode_t                        status;
  SampleInfoSeq_var                   infoSeq = new SampleInfoSeq();
  BtSeq*                              btSeqInstance = new BtSeq();
  ServerReqSeq                        serverReqSeq;

  // Zaman ile alakalı değişkenler
  long int                            messageIDCount = 0;
  Time_t                              tsBeforeTheScan = { 0, 0 };
  Time_t                              tsAfterTheScan = { 0, 0 };
  //Time_t                              tsWifiPub = { 0, 0 };
  struct timeval                      tsConverter;
  DDS::Duration_t                     waitAckTime = { 0, 800000000 }; //800ms
  int                                 refreshRate = 60;

  // Veri tutucular (data structures)
  vector<string>                      btMacHolder;
  vector<int>                         btRssiHolder;
  string                              btFileContenHolder;

  // Bluetooth tarama sonuçlarının yazdırıldığı dosyadan okuma yapacak
  // olan değişken
  boost::filesystem::ifstream         fIn;

  // Bluetooth tarama sıklığı ayarlayan değişken
  int                                 refreshRateCounter = -1;

  char                                hostName[1024];
  gethostname(hostName, 1024);


  // !!! Bluetooth tarama mesajlarını Publish edecek Topic yaratılıyor
  // ve o Topic'e ait konfigürasyon ayarları yapılıyor.

  // Domain participant yaratılıyor
  mgrBtPub.createParticipant ("KonSens_BtSeq_Participant");

  // BtSeq tipi yaratılıyor
  BtSeqTypeSupport_var btSeqTs = new BtSeqTypeSupport();
  mgrBtPub.registerType(btSeqTs.in());

  // Topic yaratılıyor
  char btPubTopicName[] = "KonSensData_BtSeq_Topic";
  mgrBtPub.createTopic(btPubTopicName);

  // Publisher yaratılıyor
  mgrBtPub.createPublisher();

  // DataWriter yaratılıyor
  bool autodispose_unregistered_instances = false;
  mgrBtPub.createWriter(autodispose_unregistered_instances,
                        KEEP_ALL_HISTORY_QOS,
                        BY_SOURCE_TIMESTAMP_DESTINATIONORDER_QOS);

  // Yaratılan DataWriter, BtSeq tipi için özelleştiriliyor
  DataWriter_var dWriter = mgrBtPub.getWriter ();
  BtSeqDataWriter_var btSeqWriter = BtSeqDataWriter::_narrow(dWriter.in());

  // Düğüm numarasını atanıyor
  btSeqInstance->userID = 13;

  // Publish edilecek olan mesajlara zaman etiketi takabilmek için
  // btSeqInstance değişkeni register ediliyor
  //userHandle = btSeqWriter->register_instance_w_timestamp(*btSeqInstance,
  //                                                        tsWifiPub);

  cout << "=== [Publisher of KonSensData_BtSeq_Topic] Ready ..." << endl;


  // !!! Sunucudan gelen komutlara Subscribe olacak olan Topic yaratılıyor
  // ve o Topic için gerekli konfigürasyon ayarları yapılıyor

  // Domain participant yaratılıyor
  mgrReqSub.createParticipant(
        "KonSensData_ServerReq_Participant_Server_to_Node");

  // ServerReq tipi yaratılıyor.
  ServerReqTypeSupport_var mgrSubscriberTS = new ServerReqTypeSupport();
  mgrReqSub.registerType(mgrSubscriberTS.in());

  // Topic yaratılıyor
  char reqSubTopicName[] = "KonSensData_ServerReq_Topic_Server_to_Node";
  mgrReqSub.createTopic(reqSubTopicName, RELIABLE_RELIABILITY_QOS,
                        VOLATILE_DURABILITY_QOS);

  // Subscriber yaratılıyor
  mgrReqSub.createSubscriber();

  // DataReader yaratılıyor
  mgrReqSub.createReader(KEEP_LAST_HISTORY_QOS, 1);

  // Yaratılan DataReader, ServerReq tipi için özelleştiriliyor.
  DataReader_var dReaderSub = mgrReqSub.getReader();
  ServerReqDataReader_var serverReqReader =
      ServerReqDataReader::_narrow(dReaderSub.in());
  checkHandle(serverReqReader.in(), "ServerReqDataReader::_narrow");

  cout << "=== [Subscriber KonSensData_ServerReq_Topic_Server_to_Node]"
          " Ready ..." << endl;


  // Bluetooth aktif hale getiriliyor.
  system("sudo hciconfig -a hci0 up");
  stringstream ssBtName;
  ssBtName << "sudo bt-adapter -a hci0 --set Name \"" << hostName << "\"";
  system(ssBtName.str().c_str());
  system("sudo bt-adapter -a hci0 --set Discoverable 1");

  // Yenileme sıklığını belirleyecek olan 'timelimit' değişkeni yaratılıyor.
  Timeout timelimit(std::chrono::milliseconds(refreshRate*1000));


  while (true)
  {
    if (timelimit.isExpired() || refreshRateCounter == -1)
    {

      // BT mesajını Publish etmek için hazırlık yapılıyor.

      cout << "-----------------------------------" << endl;

      btSeqInstance->messageID = messageIDCount;

      // Tarama öncesi alınan zaman etiketi (timestamp[0])
      gettimeofday(&tsConverter, NULL);
      tsBeforeTheScan.sec = tsConverter.tv_sec;
      tsBeforeTheScan.nanosec = (tsConverter.tv_usec * 1000);
      cout << " timestamp[0] (before the scan) = " << tsBeforeTheScan.sec
           << '.';
      cout << setfill('0') << setw(9) << (tsBeforeTheScan.nanosec)
           << endl;

      // BT taraması yapılıyor ve ardından tarama sonuçları 'bt_rssi'
      // dosyasına yazdırılıyor.
      system("sudo hciconfig hci0 reset");
      FakeDelay();
      system("sudo bt-adapter -a hci0 -d >> bt_rssi.txt");
      FakeDelay();

      cout << "Bluetooth message is publishing..." << endl;

      try
      {
        // BT tarama dosyası okunuyor
        fIn.open ("bt_rssi.txt", ios::in);
        stringstream ssBt;
        ssBt << fIn.rdbuf();
        btFileContenHolder = ssBt.str();
        system("rm bt_rssi.txt");

        // Okunan dosya boost kütüphane yardımıyla ayrıştırılıyor
        boost::regex expAd( "Address: ([0-9A-F:]{17})" ) ;
        boost::regex expBt( "RSSI:.*?([0-9]+)") ;
        boost::match_results<string::const_iterator> whatAd;

        string::const_iterator startAd = btFileContenHolder.begin();
        string::const_iterator finishAd = btFileContenHolder.end();

        while (boost::regex_search(startAd, finishAd, whatAd, expAd))
        {
          btMacHolder.push_back(whatAd[1]);
          startAd = whatAd[0].second ;
        }

        boost::match_results<string::const_iterator> whatBt;
        startAd = btFileContenHolder.begin() ;
        finishAd = btFileContenHolder.end() ;

        while (boost::regex_search(startAd, finishAd, whatBt, expBt))
        {
          string foundRssi(whatBt[1]);
          btRssiHolder.push_back(atoi(foundRssi.c_str()));
          startAd = whatBt[0].second ;
        }

        cout << "Number of BT connection that has been found: "
             << btRssiHolder.size() << endl;
        cout << "MessageID: " << btSeqInstance->messageID << endl;

        // Tarama sonrası alınan zaman etiketi (timestamp[1])
        gettimeofday(&tsConverter, NULL);
        tsAfterTheScan.sec = tsConverter.tv_sec;
        tsAfterTheScan.nanosec =( tsConverter.tv_usec * 1000);
        cout << " timestamp[1] (after the scan) = "
             << tsAfterTheScan.sec << '.';
        cout << setfill('0') << setw(9) << (tsAfterTheScan.nanosec)
             << endl;


        // Ayrıştırılan BT tarama dosyası ve alınan zaman etiketleri,
        // Publish edilecek olan mesaj değişkenlerine kaydediliyor.
        btSeqInstance->timestamp[0][0] = tsBeforeTheScan.nanosec;
        btSeqInstance->timestamp[0][1] = tsBeforeTheScan.sec;
        btSeqInstance->timestamp[1][0] = tsAfterTheScan.nanosec;
        btSeqInstance->timestamp[1][1] = tsAfterTheScan.sec;

        btSeqInstance->messages.length(btMacHolder.size());
        for(int i = 0; i < btMacHolder.size(); i++)
        {
          Msg msg;
          msg.devID = DDS::string_dup(btMacHolder[i].c_str());
          msg.hostName = DDS::string_dup(hostName);
          msg.dbm = -btRssiHolder[i];
          btSeqInstance->messages[i] = msg;
        }

        // Publish edilmeden önce, bir önceki mesajın acknowlegde mesajı
        // bekleniyor
        btSeqWriter->wait_for_acknowledgments(waitAckTime);

        status = btSeqWriter->write(*btSeqInstance,
                                    DDS::HANDLE_NIL);
        checkStatus(status, "BtSeqDataWriter::write");
        messageIDCount++;
      }

      catch ( boost::bad_expression & ex )
      {
        std::cout << ex.what() ;
        break;
      }

      btMacHolder.clear();
      btRssiHolder.clear();
      fIn.close();

      cout << "-----------------------------------" << endl;

      // Tarama sıklığını belirleyen değişken sıfırlanıyor
      timelimit.setTimerToZero();
      refreshRateCounter = 0;
      cout << refreshRateCounter << endl;

    } // BT Publisher kısmının sonu


    // Sunucu tarafından gönderilen Matlab komutlarına Subscribe olunuyor
    else
    {
      status = serverReqReader->take(serverReqSeq,
                                     infoSeq,
                                     LENGTH_UNLIMITED,
                                     ANY_SAMPLE_STATE,
                                     ANY_VIEW_STATE,
                                     ANY_INSTANCE_STATE);
      checkStatus(status, "severReqDataReader::read");

      for (DDS::ULong j = 0; j < serverReqSeq.length(); j++)
      {
        if(infoSeq[j].valid_data)
        {
          cout << "=== [Subscriber] message received :" << endl;
          cout << "    Received Request Message  : "
               << serverReqSeq[j].request << endl;
          cout << "    Received RequestID : \""
               << serverReqSeq[j].requestID << "\"" << endl;

          // Rapidjson yapılandırıcısı yaratılıyor
          Document d;
          if(d.Parse(serverReqSeq[j].request).HasParseError())
            cout << " Parsing Error!" << endl;

          StringBuffer nodeIdBuffer;
          Writer<StringBuffer> nodeIdWriter(nodeIdBuffer);
          d["NodeID"].Accept(nodeIdWriter);

          string tempNodeId = nodeIdBuffer.GetString();

          // Subscribe olunan mesajın düğüme ait olup olmadığı kontrol ediliyor
          if (tempNodeId == "\"SensDug13\"")
          {
            StringBuffer buffer;

            Value::ConstMemberIterator itr = d.FindMember("SetRefreshRate");
            // Ref Rate komutunun gelip gelmediği kontrol ediliyor
            if(itr != d.MemberEnd())
            {
              string refreshRateString;
              int refreshRateInt;

              // Document formatındaki JSON mesajı StrinBuffer'a dönüştürülüyor
              Writer<StringBuffer> writer(buffer);
              d["SetRefreshRate"].Accept(writer);
              refreshRateString = buffer.GetString();

              // Gelen mesajda fazladan çift tırnak ile bulunuyor
              // Örneğin, ""15""
              // Bu yüzden ilk son karakterler kırpılıyor
              refreshRateString =
                  refreshRateString.substr(1, refreshRateString.size()-1);
              // Refresh rate değeri stringden integera çevriliyor
              refreshRateInt = atoi(refreshRateString.c_str());

              refreshRate = refreshRateInt;
              timelimit.setMaxDuration(std::chrono::milliseconds
                                       (refreshRate*1000));

            }
          }
          else
            cout << "Invalid NodeID!" << endl;
        }
      }

      status = serverReqReader->return_loan(serverReqSeq, infoSeq);
      checkStatus(status, "ServerReqDataReader::return_loan");

      refreshRateCounter++;
      cout << refreshRateCounter << endl;

    } // Matlab komutuna Subscribe olma kısmının sonu

    // Terminalde akacak olan çıktıları dah gözle görülebilir bir şekilde
    // yazdırmak için koyulmuştur
    FakeDelay();
  }

  // Hafıza temizle işlemleri gerçekleştiriliyor

  mgrBtPub.deleteWriter();
  mgrBtPub.deletePublisher();
  mgrBtPub.deleteTopic();
  mgrBtPub.deleteParticipant();

  mgrReqSub.deleteReader();
  mgrReqSub.deleteSubscriber();
  mgrReqSub.deleteTopic();
  mgrReqSub.deleteParticipant();

  return 0;
}
Beispiel #13
0
/*****************************************************************************
;ValidateHandlesLists

Given Method() Handles X1.SomeEvent

    1. verify that X1 is a valid WithEvents variable
    2. verify that X1 sources SomeEvent()
*****************************************************************************/
void
Bindable::ValidateAndHookUpHandles
(
    BCSYM_HandlesList *HandlesEntry,
    BCSYM_MethodImpl *HandlingMethod
)
{
    VSASSERT( !HandlesEntry->IsBad(), "Bad handles unexpected here!!");
    VSASSERT( CurrentContainer()->IsClass(),
                    "Non-classes/non-structures/non-modules cannot have handles clauses!!");

    // Dev10#489103: if the handling method is bad, then we can't really tell whether it handles the event:
    if (HandlingMethod->IsBadParamTypeOrReturnType())
    {
        HandlesEntry->SetIsBad();
        return;
    }

    Symbols
        SymbolFactory(
            CurrentCompilerInstance(),
            CurrentAllocator(),
            NULL,
            CurrentGenericBindingCache());

    BCSYM_Class *ContainerOfHandlingMethod = CurrentContainer()->PClass();

    BCSYM *TypeToFindEventIn;
    BCSYM_Property *EventSourceProperty = NULL;
    BCSYM_Property *WithEventsProperty;
    BCSYM *InstanceTypeThroughWhichEventIsAccessed;

    if (HandlesEntry->IsMyBase())
    {
        TypeToFindEventIn = TypeHelpers::GetBaseClass(ContainerOfHandlingMethod, SymbolFactory);

        // A bad base is no base
        if (!TypeToFindEventIn)
        {
            HandlesEntry->SetIsBad();
            return;
        }

        InstanceTypeThroughWhichEventIsAccessed = ContainerOfHandlingMethod;
    }
    else if (HandlesEntry->IsEventFromMeOrMyClass())
    {
        if (ContainerOfHandlingMethod->IsGeneric())
        {
            TypeToFindEventIn =
                SynthesizeOpenGenericBinding(
                    ContainerOfHandlingMethod,
                    SymbolFactory);
        }
        else
        {
            TypeToFindEventIn = ContainerOfHandlingMethod;
        }

        InstanceTypeThroughWhichEventIsAccessed = ContainerOfHandlingMethod;
    }
    else
    {
        WithEventsProperty = HandlesEntry->GetWithEventsProperty();

        VSASSERT( WithEventsProperty,
                        "How can a non-bad handles entry not have a withevents property ?");

        BCSYM_Variable *WithEventsVar = WithEventsProperty->CreatedByWithEventsDecl();

        VSASSERT( WithEventsVar,
                        "How can a non-bad handles entry not refer to a withevents var ?");

        if (WithEventsVar->IsBad() ||
            WithEventsVar->IsBadVariableType())
        {
            HandlesEntry->SetIsBad();
            return;
        }

        BCSYM *TypeOfWithEventsVar = WithEventsProperty->GetType();

        VSASSERT( TypeOfWithEventsVar->IsContainer() ||
                  (TypeOfWithEventsVar->IsGenericParam() &&
                        TypeOfWithEventsVar->PGenericParam()->IsReferenceType()),
                            "What else can the type of a withevents variable be ?");

        if (HandlesEntry->GetEventSourcePropertyName())
        {
            // If withevents variable type is type parameter, then search in its class constraint,
            // else search in the withevents variable type itself.
            //
            EventSourceProperty =
                GetEventSourceProperty(
                    TypeOfWithEventsVar,
                    HandlesEntry->GetEventSourcePropertyName());

            if (!EventSourceProperty)
            {
                // "'Handles' must specify a 'WithEvents' variable or 'MyBase' qualified with a single identifier."

                ReportErrorOnSymbol(
                    IsStdModule(CurrentContainer()) ?
                        ERRID_HandlesSyntaxInModule :
                        ERRID_HandlesSyntaxInClass,
                    CurrentErrorLog(HandlingMethod),
                    HandlesEntry);

                HandlesEntry->SetIsBad();
                return;
            }

            // 






            HandlesEntry->SetEventSourceProperty(EventSourceProperty);

            // 


            VSASSERT( EventSourceProperty->GetType()->IsContainer(),
                            "Referring Property - What else can a type that is not a named type be ?");

            TypeToFindEventIn = EventSourceProperty->GetType();
        }
        else
        {
            TypeToFindEventIn = TypeOfWithEventsVar;
        }

        InstanceTypeThroughWhichEventIsAccessed = TypeToFindEventIn;
    }

    VSASSERT( TypeToFindEventIn, "No type to find the event in ?");

    bool IsBadName;
    BCSYM_NamedRoot *EventDecl =
        Semantics::EnsureNamedRoot
        (
            Semantics::InterpretName
            (
                HandlesEntry->GetEventName(),
                *(HandlesEntry->GetLocationOfEvent()),
                TypeToFindEventIn->IsContainer() ?
                    TypeToFindEventIn->PContainer()->GetHash() :
                    NULL,
                TypeToFindEventIn->IsGenericParam() ?
                    TypeToFindEventIn->PGenericParam() :
                    NULL,
                NameSearchIgnoreParent | NameSearchEventReference | NameSearchIgnoreExtensionMethods,
                InstanceTypeThroughWhichEventIsAccessed,
                ContainerOfHandlingMethod->GetHash(),     // Current Context
                CurrentErrorLog(HandlingMethod),
                CurrentCompilerInstance(),
                CurrentCompilerHost(),
                m_CompilationCaches,
                CurrentSourceFile(HandlingMethod),
                false,                                    // don't perform obsolete checks
                IsBadName,
                NULL,   // the binding context is not required here since the synthesized
                        // code has the withevents variable from which the type binding
                        // information is obtained
                NULL,
                -1
            )
        );


    if (IsBadName)
    {
        HandlesEntry->SetIsBad();
        return;
    }

    if (!EventDecl || !EventDecl->IsEventDecl())
    {
        ReportErrorAtLocation(
            ERRID_EventNotFound1,
            CurrentErrorLog(HandlingMethod),
            HandlesEntry->GetLocationOfEvent(),
            HandlesEntry->GetEventName());

        HandlesEntry->SetIsBad();
        return;
    }

    if (EventDecl->IsBad())
    {
        HandlesEntry->SetIsBad();
        return;
    }


    BCSYM_EventDecl *Event = EventDecl->PEventDecl();
    HandlesEntry->SetEvent(Event);

    // [....] - 11/17/2005
    // See Bug # 544269
    // The call to ResolveAllNamedTypesForContainer needed to be replaced with a call
    // to ResolveShadowingOverloadingAndOverridingForContainer because event signatures
    // are not necessarily setup untill after ResolveShadowingOverloadingAndOverriding
    // has been called.

    // Go and bind the event we are comparing against up to the state we need for
    // validating handles.
    ResolveShadowingOverloadingOverridingAndCheckGenericsForContainer(Event->GetContainer(), m_CompilationCaches);


    // Check for bad param types here (VSW#172753).
    if (Event->GetDelegate() &&
        Event->GetDelegate()->IsContainer() &&
        DefinedInMetaData(Event->GetDelegate()->PContainer()))
    {
        for (BCSYM_Param *Param = Event->GetFirstParam();
             Param;
             Param = Param->GetNext())
        {
            if (Param->GetType()->IsBad())
            {
                Param->GetType()->PNamedRoot()->ReportError(
                    CurrentCompilerInstance(),
                    CurrentErrorLog(HandlingMethod),
                    HandlesEntry->GetLocationOfEvent());

                HandlesEntry->SetIsBad();
                return;
            }
        }
    }

    BCSYM_GenericBinding *EventGenericBindingContext =
        DeriveGenericBindingForMemberReference(TypeToFindEventIn, Event, SymbolFactory, CurrentCompilerHost());

   MethodConversionClass MethodConversion = Semantics::ClassifyMethodConversion(
            HandlingMethod,
            GenericBindingInfo(),
            Event,
            EventGenericBindingContext,
            false, //IgnoreReturnValueErrorsForInference
            &SymbolFactory,
            CurrentCompilerHost());

    SourceFile * SourceFile = HandlingMethod->GetSourceFile();

    if (!Semantics::IsSupportedMethodConversion(
            SourceFile->GetOptionFlags() & OPTION_OptionStrict,
            MethodConversion))
    {
        // "Method '|1' cannot handle Event '|2' because they do not have the same signature."

        StringBuffer HandlingMethodRepresentation;
        HandlingMethod->GetBasicRep(CurrentCompilerInstance(), NULL, &HandlingMethodRepresentation);

        StringBuffer EventRepresentation;
        Event->GetBasicRep(CurrentCompilerInstance(), NULL, &EventRepresentation, EventGenericBindingContext);

        ReportErrorAtLocation(
            ERRID_EventHandlerSignatureIncompatible2,
            CurrentErrorLog(HandlingMethod),
            HandlesEntry->GetLocationOfEvent(),
            HandlingMethodRepresentation.GetString(),
            EventRepresentation.GetString());

        HandlesEntry->SetIsBad();
        return;
    }

    // Hook up handlers to the events they specify in their handles clauses

    if (HandlesEntry->IsMyBase() ||
        HandlesEntry->IsEventFromMeOrMyClass())
    {
        // For these cases, we search for valid MyBase, Me, MyClass handles clauses and set up the
        // addhandlers in all constructors that directly call a base constructor. This is done in
        // semantics in initializefields because that is when the information whether it directly
        // calls the base constructor is known.
        //

        const bool BuildSharedConstructor = true;

        if (HandlesEntry->GetEvent()->IsShared() &&
            HandlingMethod->IsShared())
        {
            // Make sure a shared constructor is present, else synthesize one

            if (!ContainerOfHandlingMethod->GetSharedConstructor(CurrentCompilerInstance()))
            {
                // Synthesize one
                SynthesizeConstructor(BuildSharedConstructor);
            }
        }
        else
        {
            // Make sure an Instance constructor is present, else synthesize one

            if (!ContainerOfHandlingMethod->GetFirstInstanceConstructor(CurrentCompilerInstance()))
            {
                // Synthesize one
                SynthesizeConstructor(!BuildSharedConstructor);
            }
        }
    }
    else
    {
        VSASSERT( WithEventsProperty->SetProperty(),
                        "How can there be no set accessor for a withevents property ?");


        if (WithEventsProperty->IsShared() &&
            !HandlingMethod->IsShared())
        {
            // "Events of shared WithEvents variables cannot be handled by non-shared methods."

            ReportErrorAtLocation(
                ERRID_SharedEventNeedsSharedHandler,
                CurrentErrorLog(HandlingMethod),
                HandlesEntry->GetLocationOfWithEventsVar());

            HandlesEntry->SetIsBad();
            return;
        }

        // 

        // hookup the handler list info for the above handles entry on to the WithEvents_Set.
        // GenWithEventsSetCode() will write synthetic code for these later
        //
        WithEventsProperty->SetProperty()->AddToHandlerList(
            HandlingMethod,
            Event,
            EventGenericBindingContext,
            EventSourceProperty,
            CurrentAllocator());

    }
}
int VersionControlLayer::mergeFile(const std::string& file0,
                                   const std::string& file1,
                                   const std::string& hash1,
                                   const std::string& file2,
                                   const std::string& hash2,
                                   const std::string& filename)
{
    cout<<"merge file"<<endl;
    // 
    Document conflictDoc, mergeDoc;
    conflictDoc.SetObject();
    mergeDoc.SetObject();
    cout<<"set obj over"<<endl;

    Value conflict_node, merged_node, merged_navi;
    conflict_node.SetArray();
    merged_node.SetArray();
    merged_navi.SetArray();
    assert(merged_node.IsArray());

    cout<<"set array over"<<endl;

    // 将json字符串转成文档
    Document doc0, doc1, doc2;
    doc0.Parse(file0.c_str());
    doc1.Parse(file1.c_str());
    doc2.Parse(file2.c_str());

    cout<<"navi start"<<endl;
    // ------------------navi--------------->>>
    assert(doc0.IsObject());
    Value& navi0 = doc0["description"]["-diagram"]["navi"];
    Value& navi1 = doc1["description"]["-diagram"]["navi"];
    Value& navi2 = doc2["description"]["-diagram"]["navi"];

    for(int n=0;n<navi1.Size();n++)
    {
        Value mergeNaviObj(kObjectType);
        bool merged = true;
        
        Value& href = navi1[n]["businessObjects"]["@href"];
        // 在navi2中查找同样的跳转
        if(findNaviByHref(navi2, href))  // 如果存在
        {
            // nothing to do
            merged = false;
        }
        else  // 如果navi2中不存在同样的跳转
        {
            // 查看navi0中是否存在该跳转
            if(findNaviByHref(navi0, href))  // navi0存在该跳转,则这是被版本2删除的跳转
            {
                // 合并:从版本1中删除该跳转,并存入结果
                // 实际实现:保持navi2对该跳转的删除状态

                // 记录合并:删除
                mergeNaviObj.AddMember("version",
                                       Value(kStringType).SetString(hash2.c_str(),hash2.length()),
                                       mergeDoc.GetAllocator());
                mergeNaviObj.AddMember("action", Value("delete"), mergeDoc.GetAllocator());
                mergeNaviObj.AddMember("href",
                                       Value(kStringType).CopyFrom(href, mergeDoc.GetAllocator()),
                                       mergeDoc.GetAllocator());
            }
            else  // navi0不存在该跳转,这是被版本1添加的跳转
            {
                // 添加到 navi2
                Value temp;
                temp.CopyFrom(navi1[n], doc1.GetAllocator());
                navi2.PushBack(temp,doc2.GetAllocator());

                // 记录合并
                mergeNaviObj.AddMember("version",
                                       Value(kStringType).SetString(hash1.c_str(),hash1.length()),
                                       mergeDoc.GetAllocator());
                mergeNaviObj.AddMember("action", Value("add"), mergeDoc.GetAllocator());
                mergeNaviObj.AddMember("href",
                                       Value(kStringType).CopyFrom(href, mergeDoc.GetAllocator()),
                                       mergeDoc.GetAllocator());
            }
        }
        if(merged == true)
            merged_navi.PushBack(mergeNaviObj, mergeDoc.GetAllocator());
    }  // for

    for(auto m=navi2.Begin();m!=navi2.End();m++)
    {
        Value mergeNaviObj(kObjectType);
        bool merged = true;
        
        Value& href = (*m)["businessObjects"]["@href"];
        // 在navi1中查找同样的跳转
        if(findNaviByHref(navi1, href))  //
        {
            // nothing to do
            merged = false;
        }
        else  // if navi2 doesn't have this obj
        {
            // check the obj in navi0
            if(findNaviByHref(navi0, href))  // navi0存在该跳转,则这是被版本1删除的跳转
            {
                // 记录合并:删除
                mergeNaviObj.AddMember("version",
                                       Value(kStringType).SetString(hash1.c_str(),hash1.length()),
                                       mergeDoc.GetAllocator());
                mergeNaviObj.AddMember("action", Value("delete"), mergeDoc.GetAllocator());
                mergeNaviObj.AddMember("href",
                                       Value(kStringType).CopyFrom(href, mergeDoc.GetAllocator()),
                                       mergeDoc.GetAllocator());

                // 合并:从版本2中删除该跳转,并存入结果
                m = navi2.Erase(m);
            }
            else  // navi0不存在该跳转,这是被版本2添加的跳转
            {
                // 将该跳转添加到最终结果
                // 实现:保持navi2的状态

                // 记录合并
                mergeNaviObj.AddMember("version",
                                       Value(kStringType).SetString(hash2.c_str(), hash2.length()),
                                       mergeDoc.GetAllocator());
                mergeNaviObj.AddMember("action", Value("add"), mergeDoc.GetAllocator());
                mergeNaviObj.AddMember("href",
                                       Value(kStringType).CopyFrom(href, mergeDoc.GetAllocator()),
                                       mergeDoc.GetAllocator());
            }
        }
        if(merged == true)
            merged_navi.PushBack(mergeNaviObj, mergeDoc.GetAllocator());
        if(m == navi2.End()) break;
    }  // for
    // <<<---------------navi------------------

    cout<<"navi over, conn start"<<endl;
    // -----------------connections--------->>>
    Value& src_conn = doc1["description"]["-diagram"]["connections"];
    Value& dst_conn = doc2["description"]["-diagram"]["connections"];
    Value& filt_conn = doc0["description"]["-diagram"]["connections"];
    mergeConnections(src_conn, dst_conn, filt_conn, doc2);

//    StringBuffer bufferConn;
//    Writer<StringBuffer> writerConn(bufferConn);
//    doc2.Accept(writerConn);
//    // Output
//    std::cout << bufferConn.GetString() << std::endl;
    // <<<--------------connections------------
    cout<<"conn over"<<endl;

    queue<Value*> nodeQueue0;
    queue<Value*> nodeQueue1;
    queue<Value*> nodeQueue2;

    // 获取nodelist
    Value& n0 = doc0["description"]["-diagram"]["node"];
    Value& n1 = doc1["description"]["-diagram"]["node"];
    Value& n2 = doc2["description"]["-diagram"]["node"];

    // 加入队列
    nodeQueue0.push(&n0);
    nodeQueue1.push(&n1);
    nodeQueue2.push(&n2);

    while(!nodeQueue0.empty())
    {
        cout<<"-------while-----------"<<endl;
        // 从队列获取nodelist
        Value* nodelist0 = nodeQueue0.front();
        Value* nodelist1 = nodeQueue1.front();
        Value* nodelist2 = nodeQueue2.front();

        // ------------ nodelist1----------->>>
        cout<<"-------1-----------"<<endl;
        assert((*nodelist1).IsArray());
        for(SizeType i = 0;i < (*nodelist1).Size(); i++)
        {
            cout<<"-------for-----------"<<endl;
            // 声明用于保存冲突信息的对象
            Value conflictNode_i(kObjectType);
            conflictNode_i.AddMember("isDeleted", Value("false"), conflictDoc.GetAllocator());
            Value conflict_key;
            conflict_key.SetArray();

            bool conflictHappened = false;

            // 获取 node[i]的id
            Value& id1_value = (*nodelist1)[i]["@shape_id"];
            string id1_string = id1_value.GetString();

            // 将id存入 conflictNode_i
            Value temp;
            temp.CopyFrom(id1_value, doc1.GetAllocator());
            conflictNode_i.AddMember("shape_id", temp, conflictDoc.GetAllocator());

            // 在nodelist2中找到相同id的节点
            int j = findNodeByID((*nodelist2), id1_string);  // 返回找到的节点下标

            // 如果找到了相同节点,比较是否所有属性相同
            if(j >= 0)
            {
                cout<<"-------j>=0-----------"<<endl;
                // 从nodelist0中取出该节点(1、2有共同节点,一定是从0继承的,0一定存在该点)
                int k = findNodeByID((*nodelist0), id1_string);

                // merge anchors
                mergeAnchors((*nodelist1)[i]["anchors"], (*nodelist2)[j]["anchors"], (*nodelist0)[k]["anchors"], doc2);

                // --------将子节点数组加入队列---->>>
                Value& subn0 = (*nodelist0)[k]["node"];
                Value& subn1 = (*nodelist1)[i]["node"];
                Value& subn2 = (*nodelist2)[j]["node"];

                // 加入队列
                nodeQueue0.push(&subn0);
                nodeQueue1.push(&subn1);
                nodeQueue2.push(&subn2);
                // <<<-----将子节点数组加入队列-------

                // ------对比text------>>>
                cout<<"-------text-----------"<<endl;
                Value* v_text2;
                bool propertySame12 = compareProperty((*nodelist1)[i], (*nodelist2)[j], "text", &v_text2);
                // 如果不相同则需要各自检查相对于基础版本的变动情况
                if(propertySame12 == false)
                {
                    cout<<"-------same12 == false-----------"<<endl;
                    bool propertySame01 = false, propertySame02 = false;

                    // 比较0和1的text
                    Value* v_text1;
                    propertySame01 = compareProperty((*nodelist0)[k], (*nodelist1)[j], "text", &v_text1);

                    // 比较0和2的text
                    propertySame02 = compareProperty((*nodelist0)[k], (*nodelist2)[j], "text", &v_text2);

                    // 如果两者都发生变更,则冲突
                    if(propertySame01 == false && propertySame02 == false)
                    {
                        // 记录冲突
                        conflict_key.PushBack(Value("text"), conflictDoc.GetAllocator());
                        temp.CopyFrom(*v_text1, mergeDoc.GetAllocator());
                        conflictNode_i.AddMember("text", temp, conflictDoc.GetAllocator());
                        conflictHappened = true;
                    }
                    // 如果1变了2没变,则用1覆盖2
                    else if(propertySame01 == false && propertySame02 == true)
                    {
                        // 记录合并,保留版本1的值
                        Value mergeObj(kObjectType);
                        //temp.Clear();
                        temp.SetString(hash1.c_str(), hash1.length());  // 获取版本1的hash号
                        mergeObj.AddMember("version", temp, mergeDoc.GetAllocator());  // 记录所保留的是哪个版本的值
                        mergeObj.AddMember("action", Value("modify"), mergeDoc.GetAllocator());
                        mergeObj.AddMember("object", Value("text"), mergeDoc.GetAllocator());
                        temp.CopyFrom(id1_value, mergeDoc.GetAllocator());
                        mergeObj.AddMember("shape_id", temp, mergeDoc.GetAllocator());
                        temp.CopyFrom(*v_text2, mergeDoc.GetAllocator());
                        mergeObj.AddMember("attr_name", temp, mergeDoc.GetAllocator());
                        
                        merged_node.PushBack(mergeObj, mergeDoc.GetAllocator());  // 添加到 merge array

                        // 合并
                        v_text2->CopyFrom(*v_text1, mergeDoc.GetAllocator());
                    }
                    // 如果2变了1没变,则保留2
                    else if(propertySame01 == true && propertySame02 == false)
                    {
                        cout<<"-------same01==true,same02==false-----------"<<endl;
                        // 记录合并,保留版本2的值
                        cout<<"-------get hash2-----------";
                        Value mergeObj(kObjectType);
                        //temp.Clear();
                        temp.SetString(hash2.c_str(), hash2.length());  // 获取版本2的hash号
                        mergeObj.AddMember("version", temp, mergeDoc.GetAllocator());  // 记录所保留的是哪个版本的值
                        cout<<"-------done-----------"<<endl;
                        mergeObj.AddMember("action", Value("modify"), mergeDoc.GetAllocator());
                        mergeObj.AddMember("object", Value("text"), mergeDoc.GetAllocator());
                        cout<<"-------get id-----------";
                        temp.CopyFrom(id1_value, mergeDoc.GetAllocator());
                        mergeObj.AddMember("shape_id", temp, mergeDoc.GetAllocator());
                        cout<<"-------done-----------"<<endl;
                        cout<<"-------get attr-----------";
                        temp.CopyFrom(*v_text2, mergeDoc.GetAllocator());
                        mergeObj.AddMember("attr_name", temp, mergeDoc.GetAllocator());
                        cout<<"-------done-----------"<<endl;

                        merged_node.PushBack(mergeObj, mergeDoc.GetAllocator());  // 添加到 merge array
                        cout<<"-------push done-----------"<<endl;

                        // 合并: nothing to do
                    }
                    else // 两者都没变更的情况,不可能发生
                    {}
                }  // if

                // 合并两个版本中,该节点的连线列表,将相关连线加入2中
                
                // <<<------对比text------
            }  // if(j >= 0)
            else  // 如果nodelist2中没有找到相同节点,则从nodelist0中找,以确定节点的增删情况
            {
                // 在nodelist0中找到相同id的节点
                int k = findNodeByID(*nodelist0, id1_string);  // 返回找到的节点下标

                // 如果版本0存在该节点,则这是版本2删除的节点
                if(k>=0)
                {
                    // 比较是否版本1相对版本0存在不同
                    if(diffNodeTree((*nodelist1)[i], (*nodelist0)[k]))  // 存在删除冲突
                    {
                        // 该节点原样存入doc2, 在冲突文件中标注为删除冲突
                        // 该节点加入到nodelist2
                        Value cp;
                        cp.CopyFrom((*nodelist1)[i], doc1.GetAllocator());
                        nodelist2->PushBack(cp, doc2.GetAllocator());
                        // 在冲突文件中标注为删除冲突
                        Value& isDeleted = conflictNode_i["isDeleted"];
                        isDeleted.SetString(hash2.c_str(), hash2.length());
                        conflictHappened = true;

//                        // 相关连线加入doc["connection"]
//                        cpyConnections(doc1, doc2, (*nodelist1)[i]["anchors"]);
                    }
                    else  // 不存在删除冲突
                    {
                        // 合并: 维持版本2对该节点的删除状态,并删除doc2中受影响的连线
                        removeConnections(doc2, (*nodelist1)[i]["anchors"]);

                        // 记录合并
                        Value mergeObj(kObjectType);
                        //temp.Clear();
                        temp.SetString(hash2.c_str(), hash2.length());  // 获取版本2的hash号
                        mergeObj.AddMember("version", temp, mergeDoc.GetAllocator());  // 记录所保留的是哪个版本的值
                        mergeObj.AddMember("action", Value("delete"), mergeDoc.GetAllocator());
                        mergeObj.AddMember("object", Value("node"), mergeDoc.GetAllocator());
                        temp.CopyFrom(id1_value, mergeDoc.GetAllocator());
                        mergeObj.AddMember("shape_id", temp, mergeDoc.GetAllocator());

                        merged_node.PushBack(mergeObj, mergeDoc.GetAllocator());  // 添加到 merge array
                    }
                }
                else // 版本0没有这个节点,则这是1添加的节点
                {
                    // 合并:将该节点增加至diagram2当前正在处理的node数组中,并将相关连线加入diagram2的connections数组
                    // 该节点加入到nodelist2
                    Value cp;
                    cp.CopyFrom((*nodelist1)[i], doc1.GetAllocator());
                    nodelist2->PushBack(cp, doc2.GetAllocator());

//                    // 相关连线加入doc["connection"]
//                    cpyConnections(doc1, doc2, (*nodelist1)[i]["anchors"]);

                    // 记录合并
                    Value mergeObj(kObjectType);
//                    temp.Clear();
                    temp.SetString(hash1.c_str(), hash2.length());  // 获取版本2的hash号
                    mergeObj.AddMember("version", temp, mergeDoc.GetAllocator());  // 记录所保留的是哪个版本的值
                    mergeObj.AddMember("action", Value("add"), mergeDoc.GetAllocator());
                    mergeObj.AddMember("object", Value("node"), mergeDoc.GetAllocator());
                    temp.CopyFrom(id1_value, mergeDoc.GetAllocator());
                    mergeObj.AddMember("shape_id", temp, mergeDoc.GetAllocator());

                    merged_node.PushBack(mergeObj, mergeDoc.GetAllocator());  // 添加到 merge array
                }
            }  // else

            // 将 conflictNode_i 存入 conflict_node 数组
            if(conflictHappened == true)
            {
                conflictNode_i.AddMember("conflict_key", conflict_key, conflictDoc.GetAllocator());
                conflict_node.PushBack(conflictNode_i, conflictDoc.GetAllocator());
            }

        }  // for
        // <<<--------- nodelist1--------------

        // ------------ nodelist2----------->>>
        cout<<"-------2-----------"<<endl;
        auto it = nodelist2->Begin();
        for(SizeType j = 0;j < (*nodelist2).Size(); j++, it++)
        {
            cout<<"-------for-----------"<<endl;
			// 声明用于保存冲突信息的对象
            Value conflictNode_j(kObjectType);
            conflictNode_j.AddMember("isDeleted", Value("false"), conflictDoc.GetAllocator());
            Value conflict_key;
            conflict_key.SetArray();

            bool conflictHappened = false;

            // 获取 node[j]的id
            Value& id2_value = (*nodelist2)[j]["@shape_id"];
            string id2_string = id2_value.GetString();

            // 将id存入 conflictNode_j
            Value temp;
            temp.CopyFrom(id2_value, doc2.GetAllocator());
            conflictNode_j.AddMember("shape_id", temp, conflictDoc.GetAllocator());

            // 在nodelist1中找到相同id的节点
            int i = findNodeByID((*nodelist1), id2_string);  // 返回找到的节点下标

            if(i >= 0)  // 如果找到了相同节点
            {
                // nothing to do
            }
            else  // 如果nodelist1中没有找到相同节点,则从nodelist0中找,以确定节点的增删情况
            {
                cout<<"-------i<0-----------"<<endl;
                // 在nodelist0中找到相同id的节点
                int k = findNodeByID(*nodelist0, id2_string);  // 返回找到的节点下标

                // 如果版本0存在该节点,则这是版本1删除的节点
                if(k>=0)
                {
                    // 比较是否版本2相对版本0存在不同
                    if(diffNodeTree((*nodelist2)[j], (*nodelist0)[k]))  // 存在删除冲突
                    {
                        // 保留节点信息在版本2中
                        // 在冲突文件中标注为删除冲突
                        Value& isDeleted = conflictNode_j["isDeleted"];
                        isDeleted.SetString(hash1.c_str(), hash1.length());
                        conflictHappened = true;
                    }
                    else  // 不存在删除冲突
                    {
                        // 合并:删除版本2中该节点 及 相关连线
                        removeConnections(doc2, (*nodelist2)[j]["anchors"]);
                        it = nodelist2->Erase(it);

                        // 记录合并
                        Value mergeObj(kObjectType);
//                        temp.Clear();
                        temp.SetString(hash1.c_str(), hash1.length());  // 获取版本1的hash号
                        mergeObj.AddMember("version", temp, mergeDoc.GetAllocator());  // 记录所保留的是哪个版本的值
                        mergeObj.AddMember("action", Value("delete"), mergeDoc.GetAllocator());
                        mergeObj.AddMember("object", Value("node"), mergeDoc.GetAllocator());
                        temp.CopyFrom(id2_value, mergeDoc.GetAllocator());
                        mergeObj.AddMember("shape_id", temp, mergeDoc.GetAllocator());

                        merged_node.PushBack(mergeObj, mergeDoc.GetAllocator());  // 添加到 merge array

                        if(it == nodelist2->End()) break;  // 如果此时刚刚删除的节点是最后一个节点,则退出循环
                    }
                }
                else  // added by 2
                {
                    // nothing to do

                    // 记录合并
                    Value mergeObj(kObjectType);
//                        temp.Clear();
                    temp.SetString(hash2.c_str(), hash2.length());  // 获取版本2的hash号
                    mergeObj.AddMember("version", temp, mergeDoc.GetAllocator());  // 记录所保留的是哪个版本的值
                    mergeObj.AddMember("action", Value("add"), mergeDoc.GetAllocator());
                    mergeObj.AddMember("object", Value("node"), mergeDoc.GetAllocator());
                    temp.CopyFrom(id2_value, mergeDoc.GetAllocator());
                    mergeObj.AddMember("shape_id", temp, mergeDoc.GetAllocator());

                    merged_node.PushBack(mergeObj, mergeDoc.GetAllocator());  // 添加到 merge array
                }
            }  // else

            // 将 conflictNode_j 存入 conflict_node 数组
            if(conflictHappened == true)
                conflict_node.PushBack(conflictNode_j, conflictDoc.GetAllocator());
        }  // for

        // 将刚处理完的nodelist弹出队列
        nodeQueue0.pop();
        nodeQueue1.pop();
        nodeQueue2.pop();
    }
    cout<<"node over"<<endl;

    int res = 0;  // 0表示无冲突无合并,1表示有合并无冲突,2表示无合并有冲突,3表示有合并有冲突
    
    // TODO: 这里的1 和2改成全局常量
    cout<<conflict_node.Capacity()<<" "<<merged_navi.Capacity()<<" "<<merged_node.Capacity()<<endl;
    if(conflict_node.Capacity()>0)  // 如果发生了冲突
    {
        res = res | 0x02;
    }
    if(merged_navi.Capacity()>0 || merged_node.Capacity()>0)  // 如果发生了合并
    {
        res = res | 0x01;
    }
    // add result to responding doc
    conflictDoc.AddMember("conflict_node", conflict_node, conflictDoc.GetAllocator());
    mergeDoc.AddMember("merged_navi", merged_navi, mergeDoc.GetAllocator());
    mergeDoc.AddMember("merged_node", merged_node, mergeDoc.GetAllocator());

    // 将conflictDoc 和 mergeDoc 存入以filename命名的结果文件
    // 注意这里用于保存结果的临时文件名格式为 [commit.filename.*]
    StringBuffer conflictDocBuffer;
    Writer<StringBuffer> writer1(conflictDocBuffer);
    conflictDoc.Accept(writer1);
    // Output
    //std::cout << conflictDocBuffer.GetString() << std::endl;
    saveStringToFile(conflictDocBuffer.GetString(), hash2+"."+filename+".conflict");
    cout<<"save conflict over"<<endl;

    StringBuffer mergeDocBuffer;
    Writer<StringBuffer> writer2(mergeDocBuffer);
    mergeDoc.Accept(writer2);
    // Output
    //std::cout << mergeDocBuffer.GetString() << std::endl;
    saveStringToFile(mergeDocBuffer.GetString(), hash2+"."+filename+".merge");

    cout<<"------------------"<<endl;

    StringBuffer doc2Buffer;
    Writer<StringBuffer> writer3(doc2Buffer);
    doc2.Accept(writer3);
    // Output
    std::cout << doc2Buffer.GetString() << std::endl;
    saveStringToFile(doc2Buffer.GetString(), hash2+"."+filename+".res");


    cout<<"return "<<endl;
    return res;
}
Beispiel #15
0
		int MessageBusFactory::CreateRouterMessage(MessageBus* messageBus, void** messageBuffer , bool useCompression)
		{
			StringBuffer sbMessageBus;
			Writer<StringBuffer> writerBus(sbMessageBus);
			messageBus->Serialize(writerBus);

			void *serializedMessage = (void*) sbMessageBus.GetString();
			int serializedMessageLen = sbMessageBus.GetSize();
			Bytef *zBuffer = NULL;

			if(useCompression)
			{
				
				z_stream defstream;
				defstream.zalloc = Z_NULL;
				defstream.zfree = Z_NULL;
				defstream.opaque = Z_NULL;
				defstream.avail_in = sbMessageBus.GetSize();
				defstream.next_in = (Bytef *)sbMessageBus.GetString();

				int zBufLen = (int) ceil(1.001 * sbMessageBus.GetSize()) + 12 + 6;
				zBuffer = (Bytef *)malloc( zBufLen );

				defstream.avail_out = zBufLen;
				defstream.next_out = zBuffer;
				deflateInit2( &defstream, Z_DEFAULT_COMPRESSION, Z_DEFLATED, (15+16), 8, Z_DEFAULT_STRATEGY);
				int status;
				while( ( status = deflate( &defstream, Z_FINISH ) ) == Z_OK );
				deflateEnd(&defstream);

				serializedMessage = zBuffer;
				serializedMessageLen = defstream.total_out;
			}

			int bufferLen = 15 + messageBus->Header.BodyType.size() + 4 + serializedMessageLen + 4;

			CallerContext c1;
			if(!messageBus->Header.CallStack.empty())
			{
				c1 = messageBus->Header.CallStack.top();
				bufferLen += c1.Id.Id.size() + 4 + c1.Id.Type.size();
			}
			 
			void* bufferRet = malloc(bufferLen);
			char* pos = (char*)bufferRet;
			memset(bufferRet, 0, bufferLen);
			memcpy(pos, &(messageBus->Header.Type), sizeof(char));
			pos += 1;
			memcpy(pos, &(messageBus->Header.Priority), sizeof(char));
			pos += 2; //Reservado
			int64_t ticks = HermEsb::Utils::Time::TimeExtensions::ticks_from_mindate(messageBus->Header.CreatedAt);
			
			memcpy(pos, &ticks, sizeof(int64_t));
			pos +=sizeof(int64_t);
			int bodytypeLen = messageBus->Header.BodyType.size();
			memcpy(pos, &bodytypeLen, sizeof(int));
			pos += sizeof(int);
			memcpy(pos, messageBus->Header.BodyType.c_str(), bodytypeLen);
			pos += bodytypeLen;
			int bodysize = serializedMessageLen;
			memcpy(pos, &bodysize, sizeof(int));
			pos += sizeof(int);
			memcpy(pos, serializedMessage, bodysize);

			if(!c1.Id.Id.empty())
			{
				pos += bodysize;
				int idLen = c1.Id.Id.size();
				memcpy(pos, &idLen, sizeof(int));
				pos +=  sizeof(int);
				memcpy(pos, c1.Id.Id.c_str(), c1.Id.Id.size());
				pos += c1.Id.Id.size();
				int typeLen = c1.Id.Type.size();
				memcpy(pos, &typeLen, sizeof(int));
				pos +=  sizeof(int);
				memcpy(pos, c1.Id.Type.c_str(), c1.Id.Type.size());
			}

			if(zBuffer!=NULL)
				free(zBuffer);

			*messageBuffer = bufferRet;
			return bufferLen;
		}
Beispiel #16
0
/**
 * @brief SDSMemoryNode::reciveMns
 * @param mns
 */
void SDSMemoryNode::reciveMns(char * message){

    cout<<message<<endl;
    Document doc;
    doc.ParseInsitu(message);
   if(doc.IsObject()){
       if(doc.HasMember("protocolo")){
           if(doc["protocolo"].IsString()){
               string comando;
               comando=doc["protocolo"].GetString();
               if(comando=="d_calloc"){
                 if(doc.HasMember("pSize")){
                 if(doc["pSize"].IsInt()){
                 int pSize= doc["pSize"].GetInt();
                 d_calloc(pSize);
                 }
                 }
               }


               else if(comando=="d_status"){
                   d_status();

               }
               else{
                  d_pointer_size pointerSize;
                  if(doc.HasMember("dir")){
                  if(doc["dir"].IsInt()){
                   int pDir= doc["dir"].GetInt();
                   pointerSize.pointer.dirMemory=pDir;

}
                   }
                   if(doc.HasMember("pSize")){
                   if(doc["pSize"].IsInt()){
                   int pSize= doc["pSize"].GetInt();
                   pointerSize.bytes=pSize;
}
                   }


                   if(comando=="d_free"){

                        d_free(pointerSize);
                    }
                   else{

//Documento para en caso de que se quiera obtener el dato
                       StringBuffer s;
                       Writer<StringBuffer> writer(s);
                       writer.StartObject();
                       writer.String("dato");


                     int status;
                     bystream statusBystream;
                      if(doc.HasMember("tipo")){
                      if(doc["tipo"].IsString()){
                      string tipo= doc["tipo"].GetString();

                           if(tipo=="char"){

                                 if(comando=="d_set"){
                                      if(doc.HasMember("dato")){
                                          if(doc["dato"].IsString()){
                                         //Parsear a char

                                           char pData =*(const_cast<char *>(doc["dato"].GetString()));
                                           status= Manejador.setearDatoChar(pointerSize,pData);
                                          }
                                      }

                                 }
                                if(comando=="d_get"){
                                    statusBystream=Manejador.obtenerDatoChar(pointerSize);
                                    writer.String(&(statusBystream.datachar));


                                 }


                           }
                           else if(tipo=="int"){

                                if(comando=="d_set"){
                                    if(doc.HasMember("dato")){
                                    if(doc["dato"].IsInt()){
                                     //Parsear a int
                                     int pData =doc["dato"].GetInt();
                                     status= Manejador.setearDatoInt(pointerSize,pData);
                                    }
                                    }
                                }
                               if(comando=="d_get"){

                                   statusBystream=Manejador.obtenerDatoInt(pointerSize);
                                   writer.Int(statusBystream.dataint);

                                }


                           }
                           else if(tipo=="bool"){
                       //Parsear a bool
                                 //status= Manejador.setearDatoBool(pointerSize,pData);
                           }
                           else if(tipo=="float"){
                       //parsear a float
                                // status= Manejador.setearDatoFloat(pointerSize,pData);

                           }
                           else if(tipo=="arrayint"){
                       //parsear a arreglo de int
                                // status= Manejador.setearDatoArrayInt(pointerSize,pData);
                           }
                           else if(tipo=="arraychar"){
                       //Parsear a arreglos de char
                                 //status= Manejador.setearDatoArrayChar(pointerSize,pData);
                           }
                           else if(tipo=="long"){
                       //Parsear a long
                                // status= Manejador.setearDatoLong(pointerSize,pData);
                           }
                           else if(tipo=="double"){
                       //Parsear a double
                                // status= Manejador.setearDatoDouble(pointerSize,pData);
                           }
                           if(comando=="d_set"){
                              d_set(status);

                           }
                          if(comando=="d_get"){
                              writer.String("status");
                              writer.Int(statusBystream.status);
                              writer.EndObject();
                              const char* mensaje=s.GetString();
                              cout<<"Enviando... "<<mensaje<<endl;
                              puerto->sentMns(mensaje,client);

                           }


                      }}



                   }



               }
           }


       }

   }



}
void CLSComplianceChecker::VerifyOverloadsForCLSCompliance(
    BCSYM_Proc * OverloadedProc,
    BCSYM_Proc * OverloadingProc)
{
    if (!OverloadedProc->GetFirstParam() || !OverloadingProc->GetFirstParam())
    {
        return;
    }

    bool ParamTypesAreArrayOfArrays = false;
    bool ParamsDifferOnlyByArrayRank = false;

    {
        BCSYM_Param *Param1;
        BCSYM_Param *Param2;
        for(Param1 = OverloadedProc->GetFirstParam(), Param2 = OverloadingProc->GetFirstParam();
            Param1 && Param2;
            Param1 = Param1->GetNext(), Param2 = Param2->GetNext())
        {
            // Don't do any checking if any of the parameters are bad
            //
            if (Param1->IsBad() || Param2->IsBad())
            {
                return;
            }

            // Note: Nothing special to do for optional and paramarrays
            // because a CLS Compliant consumer can always call them by
            // providing all the parameters.
            //

            BCSYM *Type1 = Param1->GetType();
            BCSYM *Type2 = Param2->GetType();


            if (Type1->IsArrayType() && Type2->IsArrayType())
            {
                BCSYM *ArrayElementType1 = Type1->PArrayType()->GetRoot();
                BCSYM *ArrayElementType2 = Type2->PArrayType()->GetRoot();

                if (ArrayElementType1->IsArrayType() &&
                    ArrayElementType2->IsArrayType())
                {
                    ParamTypesAreArrayOfArrays = true;
                    continue;
                }
                else if (BCSYM::AreTypesEqual(ArrayElementType1, ArrayElementType2))
                {
                    if (Type1->PArrayType()->GetRank() != Type2->PArrayType()->GetRank())
                    {
                        ParamsDifferOnlyByArrayRank = true;
                    }
                    continue;
                }

                // Signatures are different enough
            }
            else
            {
                if (BCSYM::AreTypesEqual(Type1, Type2))
                {
                    continue;
                }
            }

            // Signatures are different enough
            //
            return;
        }

        VSASSERT( !(Param1 && Param2),
                        "both non-NULLs Unexpected!!!");

        // Different number of parameters, so Signatures are different enough
        //
        if (Param1 != Param2)
        {
            return;
        }
    }

    VSASSERT( ParamTypesAreArrayOfArrays ||
              ParamsDifferOnlyByArrayRank,
                    "How did two indetical overloads get through bindable ?");


    if (ParamTypesAreArrayOfArrays ||
        ParamsDifferOnlyByArrayRank)
    {
        // 


        // "'|1' which overloads '|2' differs from it only by array of array parameter types
        // or by the rank of the the array parameter types and so is not CLS Compliant."

        StringBuffer OverloadingMember;
        StringBuffer OverloadedMember;

        OverloadingProc->GetBasicRep(m_Compiler, OverloadingProc->GetContainer(), &OverloadingMember);
        OverloadedProc->GetBasicRep(m_Compiler, OverloadedProc->GetContainer(), &OverloadedMember);

        ReportErrorOnSymbol(
            WRNID_ArrayOverloadsNonCLS2,
            OverloadingProc,
            OverloadingMember.GetString(),
            OverloadedMember.GetString());
    }
}
Beispiel #18
0
TEST(Writer, Transcode) {
	// UTF8 -> UTF16 -> UTF8
	StringStream s("{ \"hello\" : \"world\", \"t\" : true , \"f\" : false, \"n\": null, \"i\":123, \"pi\": 3.1416, \"a\":[1, 2, 3], \"dollar\":\"\x24\", \"cents\":\"\xC2\xA2\", \"euro\":\"\xE2\x82\xAC\", \"gclef\":\"\xF0\x9D\x84\x9E\" } ");
	StringBuffer buffer;
	Writer<StringBuffer, UTF16<>, UTF8<> > writer(buffer);
	GenericReader<UTF8<>, UTF16<> > reader;
	reader.Parse<0>(s, writer);
	EXPECT_STREQ("{\"hello\":\"world\",\"t\":true,\"f\":false,\"n\":null,\"i\":123,\"pi\":3.1416,\"a\":[1,2,3],\"dollar\":\"\x24\",\"cents\":\"\xC2\xA2\",\"euro\":\"\xE2\x82\xAC\",\"gclef\":\"\xF0\x9D\x84\x9E\"}", buffer.GetString());
}
Beispiel #19
0
void Converter::Save(const std::wstring & taniFileName)
{
	auto ddsFileName = GenTempFileName();
	StringBuffer sb;
	{
		// width group
		std::unordered_map<uint32_t, std::vector<size_t>> frameGroups;
		{
			size_t id = 0;
			for (auto&& frame : _shp.GetFrames())
				frameGroups[frame.CroppedWidth].emplace_back(id++);
		}
		uint32_t width = 0;
		{
			for (auto&& group : frameGroups)
				width += group.first;
		}
		width = FitTo4(width);
		uint32_t height = 0;
		{
			for (auto&& group : frameGroups)
			{
				uint32_t groupHeight = 0;
				for (auto&& frame : group.second)
					groupHeight += _shp.GetFrames()[frame].CroppedHeight;
				height = std::max(height, groupHeight);
			}
		}
		height = FitTo4(height);

		ComPtr<IWICBitmap> targetBitmap;
		ThrowIfFailed(_wicFactory->CreateBitmap(width, height, GUID_WICPixelFormat32bppBGRA, WICBitmapCacheOnDemand, &targetBitmap));

		MemoryPoolAllocator<> allocator;
		auto jFrames = Value(Type::kArrayType).GetArray();
		WICRect rect{ 0, 0, width, height };
		{
			ComPtr<IWICBitmapLock> locker;
			ThrowIfFailed(targetBitmap->Lock(&rect, WICBitmapLockWrite, &locker));

			UINT cbBufferSize = 0;
			UINT cbStride = 0;
			BYTE *pv = NULL;
			ThrowIfFailed(locker->GetDataPointer(&cbBufferSize, &pv));
			ThrowIfFailed(locker->GetStride(&cbStride));

			uint32_t x = 0;
			for (auto&& group : frameGroups)
			{
				uint32_t y = 0;
				for (auto&& frameId : group.second)
				{
					auto&& frame = _shp.GetFrames()[frameId];
					DrawFrame(reinterpret_cast<uint32_t*>(pv), x, y, cbStride / 4, _palette, frame);

					Value jFrame(Type::kObjectType);
					{
						Value jCoord(kObjectType);
						jCoord.AddMember("x", x, allocator);
						jCoord.AddMember("y", y, allocator);
						jFrame.AddMember("coord", jCoord, allocator);
					}
					{
						Value jOffset(kObjectType);
						jOffset.AddMember("x", frame.OffsetX, allocator);
						jOffset.AddMember("y", frame.OffsetY, allocator);
						jFrame.AddMember("offset", jOffset, allocator);
					}
					{
						Value jSize(kObjectType);
						jSize.AddMember("width", frame.CroppedWidth, allocator);
						jSize.AddMember("height", frame.CroppedHeight, allocator);
						jFrame.AddMember("size", jSize, allocator);
					}
					{
						auto color = frame.RadarColor;
						jFrame.AddMember("radarColor", uint32_t((color.a << 24) | (color.r << 16) | (color.g << 8) | color.b), allocator);
					}
					jFrames.PushBack(jFrame, allocator);
					y += frame.CroppedHeight;
				}
				x += group.first;
			}
		}
		Document doc(Type::kObjectType);
		{
			Value jSize(Type::kObjectType);
			jSize.AddMember("width", _shp.GetFrameWidth(), allocator);
			jSize.AddMember("height", _shp.GetFrameHeight(), allocator);
			doc.AddMember("size", jSize, allocator);
		}
		doc.AddMember("frames", jFrames, allocator);
		PrettyWriter<StringBuffer> writer(sb);
		doc.Accept(writer);

		ComPtr<IWICDdsEncoder> ddsEncoder;
		ComPtr<IWICBitmapEncoder> bitmapEncoder;
		ThrowIfFailed(_wicFactory->CreateEncoder(GUID_ContainerFormatDds, NULL, &bitmapEncoder));
		ThrowIfFailed(bitmapEncoder.As(&ddsEncoder));

		ComPtr<IWICStream> outputStream;
		ThrowIfFailed(_wicFactory->CreateStream(&outputStream));
		
		ThrowIfFailed(outputStream->InitializeFromFilename(ddsFileName.c_str(), GENERIC_WRITE));
		ThrowIfFailed(bitmapEncoder->Initialize(outputStream.Get(), WICBitmapEncoderNoCache));

		WICDdsParameters parameters{};
		parameters.Width = width;
		parameters.Height = height;
		parameters.ArraySize = 1;
		parameters.AlphaMode = WICDdsAlphaModeStraight;
		parameters.Dimension = WICDdsTexture2D;
		parameters.DxgiFormat = DXGI_FORMAT_BC2_UNORM;
		parameters.MipLevels = 1;
		parameters.Depth = 1;
		ThrowIfFailed(ddsEncoder->SetParameters(&parameters));

		ComPtr<IWICBitmapFrameEncode> frameEncoder;
		ThrowIfFailed(bitmapEncoder->CreateNewFrame(&frameEncoder, nullptr));
		ThrowIfFailed(frameEncoder->Initialize(nullptr));
		ThrowIfFailed(frameEncoder->WriteSource(targetBitmap.Get(), nullptr));
		ThrowIfFailed(frameEncoder->Commit());
		ThrowIfFailed(bitmapEncoder->Commit());

	}

	zipFile_raii zipFile(zipOpen(ws2s(taniFileName, CP_UTF8).c_str(), APPEND_STATUS_CREATE));
	{
		zip_fileinfo zi{};
		ThrowIfNot(zipOpenNewFileInZip(zipFile.get(), "ani.dds", &zi, nullptr, 0, nullptr, 0, nullptr, Z_DEFLATED, 3) == ZIP_OK, L"Error in create new archive.");
		FILE* fin;
		_wfopen_s(&fin, ddsFileName.c_str(), L"rb");
		int err = ZIP_OK;
		int size_read;
		byte buf[40960];
		do
		{
			size_read = (int)fread(buf, 1, sizeof(buf), fin);
			if ((size_read < sizeof(buf)) && (feof(fin) == 0))
			{
				err = ZIP_ERRNO;
			}

			if (size_read > 0)
			{
				err = zipWriteInFileInZip(zipFile.get(), buf, size_read);
			}
		} while ((err == ZIP_OK) && (size_read > 0));
		fclose(fin);
		ThrowIfNot(zipCloseFileInZip(zipFile.get()) == ZIP_OK, L"Error in close ani.dds archive.");
	}

	{
		zip_fileinfo zi{};
		ThrowIfNot(zipOpenNewFileInZip(zipFile.get(), "ani.json", &zi, nullptr, 0, nullptr, 0, nullptr, Z_DEFLATED, 3) == ZIP_OK, L"Error in create new archive.");
		ThrowIfNot(zipWriteInFileInZip(zipFile.get(), sb.GetString(), sb.GetSize()) == ZIP_OK, L"Error in write ani.json archive.");
		ThrowIfNot(zipCloseFileInZip(zipFile.get()) == ZIP_OK, L"Error in close ani.json archive.");
	}
}
TEST(StringBuffer, InitialSize) {
    StringBuffer buffer;
    EXPECT_EQ(0u, buffer.GetSize());
    EXPECT_STREQ("", buffer.GetString());
}
Beispiel #21
0
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;
}
Beispiel #22
0
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;
}
/* returns Writer<StringBuffer>::getString() */
extern "C" const char* tm_json_write_result (tm_json_w_handler_t wh) {
    StringBuffer* sb = static_cast<StringBuffer*>(wh.stringBuffer);
    return sb->GetString();
}
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;
    }
}
Beispiel #25
0
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;

	cout << "Part 2. " << endl;

	MyJsonDocument d = parseJSON("models/finalExam.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;


	MyJsonDocument d4 = parseJSON("models/finalExam.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.solveD();
	cout << "took " << timer.toc() << " seconds to solve" << endl;
	arma::vec Q = arma::zeros(2);
	arma::vec P = arma::zeros(2);
	double constraintID = 1;

	Q(0) = -2;
	int bodyID = 1;

	std::vector<arma::vec> qgen = m.getQList();
	std::vector<arma::vec> qQ = m.getQList(2,Q(0),Q(1));

    std::vector<arma::vec> qdgen = m.getQdList();

	std::vector<arma::vec> qddgen = m.getQddList();
	std::vector<arma::vec> reactionForces = m.getReactionForces(constraintID, bodyID,P);
	cout << reactionForces.at(0).n_elem <<endl;
	//arma::vec sP1 = arma::zeros(2);
	//sP1(0) = -0.02;
	//std::vector<arma::vec> requiredTorque = m.getReactionForces(7, 1,sP1);

	double xPlot[2][(int)m.getSimulationSteps()];
	double yPlot[2][(int)m.getSimulationSteps()];
	double xAccPlot[2][(int)m.getSimulationSteps()];
	double yAccPlot[2][(int)m.getSimulationSteps()];

	rapidjson::Document doc;
	doc.SetObject();
	rapidjson::Document::AllocatorType& allocator = doc.GetAllocator();

	rapidjson::Value plot1(kArrayType);
	rapidjson::Value plot1X(kArrayType);
	rapidjson::Value plot1Y(kArrayType);
	rapidjson::Value plot2(kArrayType);
	rapidjson::Value plot2X(kArrayType);
	rapidjson::Value plot2Y(kArrayType);


	rapidjson::Value plot3(kArrayType);
	rapidjson::Value plot3X(kArrayType);
	rapidjson::Value plot3Y(kArrayType);

	rapidjson::Value plot4(kArrayType);
	rapidjson::Value plot4X(kArrayType);
	rapidjson::Value plot4Y(kArrayType);
		cout << "here" << endl;

		for(int i = 0; i <= m.getSimulationSteps(); i++){

			xPlot[0][i] = qgen.at(i)(4);
			xPlot[1][i] = qgen.at(i)(3);

			plot1X.PushBack(xPlot[0][i],allocator);
			plot1Y.PushBack(xPlot[1][i],allocator);

			yPlot[0][i] = m.getStepSize()*i;
			yPlot[1][i] = qgen.at(i)(0);
			plot2X.PushBack(yPlot[0][i],allocator);
			plot2Y.PushBack(yPlot[1][i],allocator);

			xAccPlot[0][i] = m.getStepSize()*i;
			xAccPlot[1][i] = reactionForces.at(i)(2);
			plot3X.PushBack(xAccPlot[0][i],allocator);
			plot3Y.PushBack(xAccPlot[1][i],allocator);
	/**
			yAccPlot[0][i] = m.getStepSize()*i;
			yAccPlot[1][i] = qddQ.at(i)(1);
			plot4X.PushBack(yAccPlot[0][i],allocator);
			plot4Y.PushBack(yAccPlot[1][i],allocator);
	*/
		}
		plot1.PushBack(plot1X,allocator);
		plot1.PushBack(plot1Y,allocator);

		plot2.PushBack(plot2X,allocator);
		plot2.PushBack(plot2Y,allocator);

		plot3.PushBack(plot3X,allocator);
		plot3.PushBack(plot3Y,allocator);

		//plot4.PushBack(plot4X,allocator);
		//plot4.PushBack(plot4Y,allocator);

		doc.AddMember("Plot1",plot1,allocator);
		doc.AddMember("Plot2",plot2,allocator);
		doc.AddMember("Plot3",plot3,allocator);
		//doc.AddMember("Plot4",plot4,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" );







  return 0;
  }
Beispiel #26
0
/**********
*TemporaryManager::DoAllocateTemporary
*       Allocates memory for a temporary and inserts it into the list
***********/
BCSYM_Variable *
TemporaryManager::DoAllocateTemporary
(
    _In_z_ STRING *TemporaryName,
    BCSYM *TemporaryType,
    LifetimeClass Lifetime,
    const Location *TextSpan,
    ILTree::ExecutableBlock *Block
)
{
    Temporary *Return;

    Return = (Temporary *)m_TempAllocator->Alloc(sizeof(Temporary));
    Return->Symbol = m_SymbolAllocator.AllocVariable(TextSpan ? true : false, false);
    Return->Lifetime = Lifetime;
    Return->Block = Block;
    Return->IsLocked = false;

#if IDE 
    if (TemporaryType->DigThroughNamedType()->IsAnonymousType())
    {
        // Special case anonymous type since they are globally unique with no qualification.
        Return->VariableTypeName = TemporaryType->DigThroughNamedType()->PNamedRoot()->GetName();
    }
    else
    {
        StringBuffer sb;
        TemporaryType->GetBasicRep(m_Compiler,NULL,&sb);
        if (sb.GetStringLength() > 0)
        {
            Return->VariableTypeName = m_Compiler->AddString(sb.GetString());
        }
    }
#endif IDE 

    Return->UseCount = 1;

    // Temporaries with no lifetime are never "in use", i.e., they are always available from the pool.
    if (Return->Lifetime != LifetimeNone && Return->Lifetime != LifetimeDefaultValue)
    {
        Return->IsCurrentlyInUse = true;
    }

    m_SymbolAllocator.GetVariable(
        TextSpan,
        TemporaryName,
        TemporaryName,
        DECLF_Public,
        VAR_Local,
        TemporaryType,
        NULL,
        NULL,
        Return->Symbol);

    Return->Symbol->SetIsTemporary();

    Symbols::SetParent(Return->Symbol, m_ContainingProcedure);

    // Insert at beginning of list
    Return->Next = m_Temporaries;
    m_Temporaries = Return;

    // Set the temporary manager after inserting into the list because the set method will
    // assert that the temporary is actually apart of this manager
    Return->Symbol->SetTemporaryManager(this);

    return Return->Symbol;
}
Beispiel #27
0
BOOST_FIXTURE_TEST_CASE(subscribe, NotifFixture) {

    struct stat buffer;
    WAIT_FOR(stat(SOCK_NAME.c_str(), &buffer) == 0, 500);

    LOG(INFO) << "Connecting";

    stream_protocol::socket s(io);
    s.connect(stream_protocol::endpoint(SOCK_NAME));

    StringBuffer r;
    Writer<StringBuffer> writer(r);
    writer.StartObject();
    writer.Key("method");
    writer.String("subscribe");
    writer.Key("params");
    writer.StartObject();
    writer.Key("type");
    writer.StartArray();
    writer.String("virtual-ip");
    writer.EndArray();
    writer.EndObject();
    writer.Key("id");
    writer.String("1");
    writer.EndObject();
    std::string t("test");
    uint32_t size = htonl(r.GetSize());
    ba::write(s, ba::buffer(&size, 4));
    ba::write(s, ba::buffer(r.GetString(), r.GetSize()));

    Document rdoc;
    readMessage(s, rdoc);

    //StringBuffer output;
    //{
    //    PrettyWriter<StringBuffer> owriter(output);
    //    rdoc.Accept(owriter);
    //    LOG(INFO) << std::endl << output.GetString();
    //}

    {
        boost::unordered_set<std::string> uuids;
        uuids.insert("4412dcd2-0cd0-4741-99d1-d8b3946e1fa9");
        uuids.insert("1cc9483a-8d7a-48d5-9c23-862401691e01");
        notif.dispatchVirtualIp(uuids,
                                opflex::modb::MAC("11:22:33:44:55:66"),
                                "1.2.3.4");
    }

    Document notif;
    readMessage(s, notif);

    BOOST_REQUIRE(notif.HasMember("method"));
    BOOST_REQUIRE(notif["method"].IsString());
    BOOST_CHECK_EQUAL("virtual-ip",
                      std::string(notif["method"].GetString()));
    BOOST_REQUIRE(notif.HasMember("params"));
    BOOST_REQUIRE(notif["params"].IsObject());

    const rapidjson::Value& p = notif["params"];
    BOOST_REQUIRE(p.HasMember("mac"));
    BOOST_REQUIRE(p["mac"].IsString());
    BOOST_CHECK_EQUAL("11:22:33:44:55:66",
                      std::string(p["mac"].GetString()));

    BOOST_REQUIRE(p.HasMember("ip"));
    BOOST_REQUIRE(p["ip"].IsString());
    BOOST_CHECK_EQUAL("1.2.3.4",
                      std::string(p["ip"].GetString()));

    BOOST_REQUIRE(p.HasMember("uuid"));
    BOOST_REQUIRE(p["uuid"].IsArray());
    std::set<std::string> us;
    const rapidjson::Value& uuids = p["uuid"];
    rapidjson::Value::ConstValueIterator it;
    for (it = uuids.Begin(); it != uuids.End(); ++it) {
        BOOST_REQUIRE(it->IsString());
        us.insert(it->GetString());
    }
    BOOST_CHECK_EQUAL(2, us.size());
    BOOST_CHECK(us.find("4412dcd2-0cd0-4741-99d1-d8b3946e1fa9") != us.end());
    BOOST_CHECK(us.find("1cc9483a-8d7a-48d5-9c23-862401691e01") != us.end());

    //output.Clear();
    //{
    //    PrettyWriter<StringBuffer> owriter(output);
    //    notif.Accept(owriter);
    //    LOG(INFO) << std::endl << output.GetString();
    //}

}
// 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; 
}
Beispiel #29
0
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;
}
Beispiel #30
0
#include "rapidjson/document.h"
#include "rapidjson/writer.h"
#include "rapidjson/stringbuffer.h"
#include <iostream>

using namespace rapidjson;

TEST_CASE("JSON Parsed", "[rapidjson]"){
    // 1. Parse a JSON string into DOM.
    const char* json = "{\"project\":\"rapidjson\",\"stars\":10}";
    Document d;
    d.Parse(json);

    // 2. Modify it by DOM.
    Value& s = d["stars"];
    s.SetInt(s.GetInt() + 1);
    REQUIRE(s.GetInt() == 11);

    // 3. Stringify the DOM
    StringBuffer buffer;
    Writer<StringBuffer> writer(buffer);
    d.Accept(writer);

    // Output {"project":"rapidjson","stars":11}
    const std::string expectedString = "{\"project\":\"rapidjson\",\"stars\":11}";
    const std::string testString = buffer.GetString();
    REQUIRE( testString == expectedString );
    // std::cout << buffer.GetString() << std::endl;
    // return 0;
}