Esempio n. 1
0
File: main.cpp Progetto: CCJY/coliru
int main()
{
  std::istringstream json1_stream {
      "{"
      "  \"node1\" : 1,"
      "  \"node_that_only_appears_in_this_one\" : 2,"
      "  \"node3\" :"
      "  {"
      "    \"nested1\" : 3,"
      "    \"nested2\" :"
      "    {"
      "      \"double_nested1\" : 5,"
      "      \"double_nested2\" : \"foo\""
      "    }"
      "  }"
      "}"};
  
  std::istringstream json2_stream {
      "{"
      "  \"node1\" : 1,"
      "  \"node3\" :"
      "  {"
      "    \"nested1\" : 3,"
      "    \"nested_that_only_appears_in_this_one\" : 5,"
      "    \"nested2\" :"
      "    {"
      "      \"double_nested1\" : 5,"
      "      \"double_nested2\" : \"bar\""
      "    }"
      "  }"
      "}"};
  
  boost::property_tree::ptree tree1, tree2;
  read_json(json1_stream, tree1);
  read_json(json2_stream, tree2);
  
  std::cout << "difference in tree2 and tree1:\n";
  write_json(std::cout, tree2 - tree1);
  
  std::cout << "union of tree1 and tree2:\n";
  write_json(std::cout, tree1 | tree2);
  
  std::cout << "intersection of tree1 and tree2:\n";
  write_json(std::cout, tree1 & tree2);
  
  std::cout << "symmetric difference of tree1 and tree2:\n";
  write_json(std::cout, tree1 ^ tree2);
}
Esempio n. 2
0
static void runtest_keys_valid(const char *json_base_fn)
{
	char *json_fn = test_filename(json_base_fn);
	cJSON *tests = read_json(json_fn);
	assert((tests->type & 0xFF) == cJSON_Array);

	unsigned int idx;

	for (idx = 0; idx < cJSON_GetArraySize(tests); idx++) {

	    cJSON *test = cJSON_GetArrayItem(tests, idx);
	    assert((test->type & 0xFF) == cJSON_Array);
	    assert(cJSON_GetArraySize(test) == 3);

		cJSON *j_base58 = cJSON_GetArrayItem(test, 0);
		cJSON *j_payload = cJSON_GetArrayItem(test, 1);
		assert((j_base58->type & 0xFF) == cJSON_String);
		assert((j_payload->type & 0xFF) == cJSON_String);

		cJSON *j_meta = cJSON_GetArrayItem(test, 2);
		assert((j_meta->type & 0xFF) == cJSON_Object);

		cJSON *j_addrtype = cJSON_GetObjectItem(j_meta, "addrType");
		assert(!j_addrtype || ((j_addrtype->type & 0xFF) == cJSON_String));

		cJSON *j_compress = cJSON_GetObjectItem(j_meta, "isCompressed");
		assert(!j_compress || ((j_compress->type & 0xFF) == cJSON_True) ||
		       ((j_compress->type & 0xFF) == cJSON_False));

		bool is_privkey = ((cJSON_GetObjectItem(j_meta, "isPrivkey")->type & 0xFF) == cJSON_True);
		bool is_testnet = ((cJSON_GetObjectItem(j_meta, "isTestnet")->type & 0xFF) == cJSON_True);

		if (is_privkey) {
			test_privkey_valid_enc(
			    j_base58->valuestring,
				hex2str(j_payload->valuestring),
				((j_compress->type & 0xFF) == cJSON_True),
				is_testnet);
			test_privkey_valid_dec(
				j_base58->valuestring,
				hex2str(j_payload->valuestring),
				((j_compress->type & 0xFF) == cJSON_True),
				is_testnet);
		} else {
			test_pubkey_valid_enc(
				j_base58->valuestring,
				hex2str(j_payload->valuestring),
				j_addrtype->valuestring,
				is_testnet);
			test_pubkey_valid_dec(
				j_base58->valuestring,
				hex2str(j_payload->valuestring),
				j_addrtype->valuestring,
				is_testnet);
		}
	}

	free(json_fn);
	cJSON_Delete(tests);
}
Esempio n. 3
0
static void runtest_encdec(const char *base_fn)
{
	char *fn = NULL;

	fn = test_filename(base_fn);
	json_t *data = read_json(fn);
	assert(json_is_array(data));

	size_t n_tests = json_array_size(data);
	unsigned int i;

	for (i = 0; i < n_tests; i++) {
		json_t *inner;

		inner = json_array_get(data, i);
		assert(json_is_array(inner));

		json_t *j_raw = json_array_get(inner, 0);
		json_t *j_enc = json_array_get(inner, 1);
		assert(json_is_string(j_raw));
		assert(json_is_string(j_enc));

		test_encode(json_string_value(j_raw),
			    json_string_value(j_enc));
		test_decode(json_string_value(j_raw),
			    json_string_value(j_enc));
	}

	free(fn);
	json_decref(data);
}
Esempio n. 4
0
    bool ConfigStorageManager::loadConfig(ConfigTree *&loadTree, std::string configName)
    {
        CONFIGSYS_DEBUG_CALLS;

        // get the path to load from
        std::string loadPath = "ConfigurationFiles/" + configName + ".json";
        // load tree from file(s) as ptree<string>
        ptree rawTree;
        
        try
        {
            read_json(loadPath, rawTree);
        }
        catch(boost::property_tree::json_parser::json_parser_error &je)
        {
            std::cout   << "ConfigStorageManager::loadConfig(...): " 
                        << je.what() 
                        << std::endl;
            return false;
        }

        /* 
         * (convert to ptree<ConfigParameter>) - currently performing this 
         * conversion ConfigTree's accessor methods. 
         */

        // Set the output parameter
        ConfigTree *newTree = new ConfigTree(rawTree);
        loadTree = newTree;

        return true;
    }
Esempio n. 5
0
static void runtest_encdec(const char *json_base_fn)
{
	char *json_fn = test_filename(json_base_fn);
	cJSON *tests = read_json(json_fn);
	assert((tests->type & 0xFF) == cJSON_Array);

	unsigned int idx;

	for (idx = 0; idx < cJSON_GetArraySize(tests); idx++) {

	    cJSON *test = cJSON_GetArrayItem(tests, idx);
	    assert((test->type & 0xFF) == cJSON_Array);
	    assert(cJSON_GetArraySize(test) == 2);

            cJSON *j_raw = cJSON_GetArrayItem(test, 0);
            cJSON *j_enc = cJSON_GetArrayItem(test, 1);
            assert((j_raw->type & 0xFF) == cJSON_String);
            assert((j_enc->type & 0xFF) == cJSON_String);

            test_encode(j_raw->valuestring,
                        j_enc->valuestring);
            test_decode(j_raw->valuestring,
                        j_enc->valuestring);
	}

	free(json_fn);
	cJSON_Delete(tests);
}
Esempio n. 6
0
	/* \fn  Set
	  \brief Set running link
	  \param[in] char* setting as json string
	  \return bool
	*/
	virtual bool Set(char* setting, long settingLen)
	{
		try
		{
			string settingStr = setting;
			stringstream stream;
			stream << settingStr;
			property_tree::ptree pRoot;
			read_json(stream, pRoot);
			if (m_section.try_lock())
			{
				strcpy_s(name, sizeof(name), pRoot.get<string>("name").data());
				frameTimes = pRoot.get<long>("frameTimes");
				frameTime = pRoot.get<long>("frameTime");
				includeTaskTime = pRoot.get<bool>("includeTaskTime");
				readAndUpdate = pRoot.get<int>("readAndUpdate");
				readBlocked = pRoot.get<bool>("readBlocked");
				writeAndClear = pRoot.get<int>("writeAndClear");
				writeBlocked = pRoot.get<bool>("writeBlocked");
				m_section.unlock();
			}
			else
			{
				WRITE_LOG(severity_level::warning, "");
			}
		}
		catch (...)
		{
			WRITE_LOG(severity_level::error, "");
			return false;
		}
		return true;
	}
Esempio n. 7
0
	/**
	* Function used to write the received html/json content to a c++ string.
	*
	* @param buffer
	* @param size
	* @param nmemb
	* @return
	*/
	size_t auth_write_data(const char *buffer, size_t size, size_t nmemb)
	{
		int result = 0;
		if (buffer != 0)
		{
			m_data.append(buffer, size*nmemb);
			result = size*nmemb;
		}
		/*cout <<__LINE__<<":"<<  buffer << endl;*/
		cout << __LINE__<<":"<< m_data << endl;
		ptree pt;
		stringstream stream;
		stream << m_data;
		read_json(stream, pt);

		string scope = pt.get<string>("scope");
		string nonce = pt.get<string>("nonce");
		m_access_token = pt.get<string>("access_token");
		m_token_type = pt.get<string>("token_type");
		string app_id = pt.get<string>("app_id");
		size_t expires_in = pt.get<size_t>("expires_in");
#ifdef DEBUG
		cout << scope << endl;
		cout << nonce << endl;
		cout << m_access_token << endl;
		cout << m_token_type << endl;
		cout << app_id << endl;
		cout << expires_in << endl;
#endif
		return result;
	}
Esempio n. 8
0
static void
handle_replicate_json (UfoDaemon *daemon, UfoMessage *msg)
{
    UfoDaemonPrivate *priv = UFO_DAEMON_GET_PRIVATE (daemon);
    gchar *json;
    UfoTaskGraph *graph;
    GError *error = NULL;

    json = read_json (daemon, msg);

    // send ack
    UfoMessage *response = ufo_message_new (UFO_MESSAGE_ACK, 0);
    ufo_messenger_send_blocking (priv->msger, response, NULL);
    ufo_message_free (response);

    graph = UFO_TASK_GRAPH (ufo_task_graph_new ());
    ufo_task_graph_read_from_data (graph, priv->manager, json, &error);

    if (error != NULL) {
        g_printerr ("%s\n", error->message);
        goto replicate_json_free;
    }

    ufo_scheduler_run (priv->scheduler, graph, NULL);
    g_object_unref (priv->scheduler);

    priv->scheduler = ufo_scheduler_new (priv->config, NULL);

replicate_json_free:
    g_object_unref (graph);
    g_free (json);
}
Esempio n. 9
0
  /// Parses osm json data from stream calling visitor.
  void parse(std::istream &istream, Visitor &visitor) const {
    istream.unsetf(std::ios::skipws);
    ptree pt;
    read_json(istream, pt);

    for (const ptree::value_type &feature : pt) {
      std::string featureName = feature.first;
      std::uint32_t featureId = stringTable_.getId(featureName);
      for (const ptree::value_type &f : pt.get_child(featureName).get_child("features")) {
        const auto &type = f.second.get_child("geometry.type").data();
        if (type=="Point")
          parsePoint(visitor, featureId, f.second);
        else if (type=="LineString")
          parseLineString(visitor, featureId, f.second);
        else if (type=="Polygon")
          parsePolygon(visitor, featureId, f.second);
        else if (type=="MultiLineString")
          parseMultiLineString(visitor, featureId, f.second);
        else if (type=="MultiPolygon")
          parseMultiPolygon(visitor, featureId, f.second);
        else
          throw std::invalid_argument(std::string("Unknown geometry type:") + type);
      }
    }
  }
Esempio n. 10
0
static void runtest(bool is_valid, const char *basefn)
{
	char *fn = test_filename(basefn);
	json_t *tests = read_json(fn);
	assert(json_is_array(tests));

	unsigned int idx;
	for (idx = 0; idx < json_array_size(tests); idx++) {
		json_t *test = json_array_get(tests, idx);
		assert(json_is_array(test));

		const char *scriptSigEnc =
			json_string_value(json_array_get(test, 0));
		const char *scriptPubKeyEnc =
			json_string_value(json_array_get(test, 1));
		assert(scriptSigEnc != NULL);
		assert(scriptPubKeyEnc != NULL);

		cstring *scriptSig = parse_script_str(scriptSigEnc);
		cstring *scriptPubKey = parse_script_str(scriptPubKeyEnc);
		assert(scriptSig != NULL);
		assert(scriptPubKey != NULL);

		test_script(is_valid, scriptSig, scriptPubKey,
			    idx, scriptSigEnc, scriptPubKeyEnc);

		cstr_free(scriptSig, true);
		cstr_free(scriptPubKey, true);
	}

	json_decref(tests);
	free(fn);
}
Esempio n. 11
0
 SoulSifterSettings::SoulSifterSettings() {
   // TODO settings file stored in other OS place
   filename.append(getenv("HOME"));
   filename.append("/Library/Application Support/Soul Sifter");
   if (!filesystem::exists(filename)) {
     if (!filesystem::create_directory(filename)) {
       LOG(WARNING) << "Unable to create settings directory " << filename;
     }
   }
   filename.append("/settings.json");
   if (filesystem::exists(filename)) {
     // Load the JSON file into the property tree. If reading fails
     // (cannot open file, parse error), an exception is thrown.
     read_json(filename, ptree);
   } else {
     // defaults
     //ptree.put("music.dir", "");
     //ptree.put("staging.dir", "");
     //ptree.put("mv.dir", "");
     ptree.put("dir.tmp", "/tmp");
     ptree.put("db.url", "localhost");
     ptree.put("db.user", "ss");
     ptree.put("db.name", "music");
     ptree.put("db.password", "pw");
     //ptree.put("google.appKey", "");
     //ptree.put("google.email", "");
     ptree.put("songList.limit", 128);
     //ptree.put("tag.readOverwrite", "");
   }
 }
Esempio n. 12
0
int netsocket_setup(int argc, char **argv)
{
	cJSON *json;
	struct netsocket_config cfg;
	int error;

	error = read_json(argc, argv, &json);
	if (error)
		return error;

	error = json_to_config(json, &cfg);
	if (error)
		goto end;

	error = create_socket(&cfg);
	if (error)
		goto end;

	error = adjust_mcast_opts(&cfg);
	if (error) {
		close(sk);
		freeaddrinfo(addr_candidates);
		goto end;
	}
	/* Fall through. */

end:
	cJSON_Delete(json);
	return error;
}
Esempio n. 13
0
void Tag::fromJsonString(std::string const& jsonString)
{
	std::stringstream ss(jsonString);
	ptree pt;
	read_json(ss,pt);
	m_Id = pt.get("Id", 0L);
	m_Name = pt.get("Name", "");
}
void CJsonReader::load(String path)
{
    m_data.clear();
    try {
        read_json(path, m_data);
    } catch (json_parser_error &e) {
        throw;
    }
}
Esempio n. 15
0
static void
handle_stream_json (UfoDaemon *daemon, UfoMessage *msg)
{
    UfoDaemonPrivate *priv = UFO_DAEMON_GET_PRIVATE (daemon);
    gchar *json;
    GList *roots;
    GList *leaves;
    UfoNode *first;
    UfoNode *last;
    GError *error = NULL;

    json = read_json (daemon, msg);
    // send ack
    UfoMessage *response = ufo_message_new (UFO_MESSAGE_ACK, 0);
    ufo_messenger_send_blocking (priv->msger, response, NULL);
    ufo_message_free (response);

    /* Setup local task graph */
    priv->task_graph = UFO_TASK_GRAPH (ufo_task_graph_new ());
    ufo_task_graph_read_from_data (priv->task_graph, priv->manager, json, &error);

#ifdef DEBUG
    ufo_graph_dump_dot (UFO_GRAPH (priv->task_graph), "task_graph_received.dot");
#endif

    if (error != NULL) {
        g_printerr ("%s\n", error->message);
        /* Send error to master */
        return;
    }

    roots = ufo_graph_get_roots (UFO_GRAPH (priv->task_graph));
    g_assert (g_list_length (roots) == 1);

    leaves = ufo_graph_get_leaves (UFO_GRAPH (priv->task_graph));
    g_assert (g_list_length (leaves) == 1);

    first = UFO_NODE (g_list_nth_data (roots, 0));
    last = UFO_NODE (g_list_nth_data (leaves, 0));

    first = remove_dummy_if_present (UFO_GRAPH (priv->task_graph), first);

    priv->input_task = ufo_input_task_new ();
    priv->output_task = ufo_output_task_new (2);

    ufo_graph_connect_nodes (UFO_GRAPH (priv->task_graph),
                             priv->input_task, first,
                             GINT_TO_POINTER (0));

    ufo_graph_connect_nodes (UFO_GRAPH (priv->task_graph),
                             last, priv->output_task,
                             GINT_TO_POINTER (0));

    priv->scheduler_thread = g_thread_create ((GThreadFunc) run_scheduler, daemon, TRUE, NULL);
    g_free (json);
}
Esempio n. 16
0
void udp_server::parse(std::string str) {
  boost::property_tree::ptree child;
  try {
    std::istringstream iss(str);
    read_json(iss, child);
    m_queue.push(child);
  } catch (boost::property_tree::json_parser::json_parser_error& error) {
    std::cerr << error.message() << std::endl;
  }
}
Esempio n. 17
0
static int
db_replay_log(heim_db_t db, heim_error_t *error)
{
    int ret;
    heim_string_t journal_fname = NULL;
    heim_object_t journal;
    size_t len;

    heim_assert(!db->in_transaction, "DB transaction not open");
    heim_assert(db->set_keys == NULL && db->set_keys == NULL, "DB transaction not open");

    if (error)
	*error = NULL;

    if (db->options == NULL)
	return 0;

    journal_fname = heim_dict_get_value(db->options, HSTR("journal-filename"));
    if (journal_fname == NULL)
	return 0;

    ret = read_json(heim_string_get_utf8(journal_fname), &journal, error);
    if (ret == ENOENT)
	return 0;
    if (ret == 0 && journal == NULL)
	return 0;
    if (ret != 0)
	return ret;

    if (heim_get_tid(journal) != HEIM_TID_ARRAY)
	return HEIM_ERROR(error, EINVAL,
			  (ret, N_("Invalid journal contents; delete journal",
				   "")));

    len = heim_array_get_length(journal);

    if (len > 0)
	db->set_keys = heim_array_get_value(journal, 0);
    if (len > 1)
	db->del_keys = heim_array_get_value(journal, 1);
    ret = db_do_log_actions(db, error);
    if (ret)
	return ret;

    /* Truncate replay log and we're done */
    ret = open_file(heim_string_get_utf8(journal_fname), 1, 0, NULL, error);
    if (ret)
	return ret;
    heim_release(db->set_keys);
    heim_release(db->del_keys);
    db->set_keys = NULL;
    db->del_keys = NULL;

    return 0;
}
Esempio n. 18
0
    bool LoadCheckpoints(const std::string& strNetwork)
    {
        UniValue v;
        if (strNetwork == "main")
            v = read_json(GetMainCheckpoints());
        else if (strNetwork == "test")
            v = read_json(GetTestCheckpoints());
        else if (strNetwork == "regtest")
            v = read_json(GetRegTestCheckpoints());
        else
            return false;

        if (v.empty())
            return false;

        for (unsigned int idx = 0; idx < v.size(); idx++) {
            const UniValue &val = v[idx];
            const UniValue &o = val.get_obj();

            const UniValue &vHeight = find_value(o, "height");
            if (!vHeight.isNum())
                return false;

            int nHeight = vHeight.get_int();
            if (nHeight < 0)
                return false;

            Checkpoint checkpoint;
            for (auto denom : libzerocoin::zerocoinDenomList) {
                const UniValue& vDenomValue = find_value(o, std::to_string(denom));
                if (!vDenomValue.isStr()) {
                    return false;
                }
                CBigNum bn = 0;
                bn.SetHex(vDenomValue.get_str());
                checkpoint.insert(std::make_pair(denom, bn));
            }

            mapCheckpoints.insert(make_pair(nHeight, checkpoint));
        }
        return true;
    }
Esempio n. 19
0
File: db.c Progetto: InvLim/heimdal
static heim_data_t
json_db_copy_value(void *db, heim_string_t table, heim_data_t key,
		  heim_error_t *error)
{
    json_db_t jsondb = db;
    heim_string_t key_string;
    const heim_octet_string *key_data = heim_data_get_data(key);
    struct stat st;
    heim_data_t result;

    if (error)
	*error = NULL;

    if (strnlen(key_data->data, key_data->length) != key_data->length) {
	HEIM_ERROR(error, EINVAL,
		   (EINVAL, N_("JSON DB requires keys that are actually "
			       "strings", "")));
	return NULL;
    }

    if (stat(heim_string_get_utf8(jsondb->dbname), &st) == -1) {
	HEIM_ERROR(error, errno,
		   (errno, N_("Could not stat JSON DB file", "")));
	return NULL;
    }

    if (st.st_mtime > jsondb->last_read_time ||
	st.st_ctime > jsondb->last_read_time) {
	heim_dict_t contents = NULL;
	int ret;

	/* Ignore file is gone (ENOENT) */
	ret = read_json(heim_string_get_utf8(jsondb->dbname),
		(heim_object_t *)&contents, error);
	if (ret)
	    return NULL;
	if (contents == NULL)
	    contents = heim_dict_create(29);
	heim_release(jsondb->dict);
	jsondb->dict = contents;
	jsondb->last_read_time = time(NULL);
    }

    key_string = heim_string_create_with_bytes(key_data->data,
					       key_data->length);
    if (key_string == NULL) {
	(void) HEIM_ENOMEM(error);
	return NULL;
    }

    result = heim_path_copy(jsondb->dict, error, table, key_string, NULL);
    heim_release(key_string);
    return result;
}
Esempio n. 20
0
	void register_callback()
	{
		m_resource["^/admin/products.json/[[:graph:]]+$"]["GET"] = [&]()
		{
			try
			{
				//parse m_data and update mysql
				ptree pt;
				std::istringstream content(m_data);
				read_json(content, pt);
				for (auto p = pt.begin(); p != pt.end(); ++p)
				{
					cout << p->second.get<int>("product_category_id") << endl;
					cout << p->second.get<string>("product_category") << endl;
					cout << p->second.get<int>("product_group_id") << endl;
					cout << p->second.get<string>("product_group") << endl;
					cout << p->second.get<int>("product_id") << endl;
					cout << p->second.get<string>("product_name") << endl;
					cout << p->second.get<string>("sku") << endl;


					ptree pChild = p->second.get_child("inventory_quantities");

					for (auto it = pChild.begin(); it != pChild.end(); ++it)
					{
						cout << "--------------------------" << endl;
						cout << it->second.get<int>("distribution_center_id") << endl;
						cout << it->second.get<string>("distribution_center_name") << endl;
						cout << it->second.get<double>("inventory_quantity") << endl;
						//scout<<"--------------------------"<<endl;
					}
					cout << "#####################################################" << endl;
				}

				//cout<<m_data<<endl;
				BOOST_LOG_SEV(slg, boost_log->get_log_level()) << __LINE__;
				boost_log->get_initsink()->flush();

			}
			catch (json_parser_error& e)
			{
				cout << e.what() << endl;
			}
			catch (exception& e)
			{
				cout << e.what() << endl;
			}
			catch (...)
			{

			}
		};
		copy_opt();
	}
Esempio n. 21
0
void Order::fromJsonString(std::string const& jsonString)
{
	std::stringstream ss(jsonString);
	ptree pt;
	read_json(ss,pt);
	m_Id = pt.get("Id", 0L);
	m_PetId = pt.get("PetId", 0L);
	m_Quantity = pt.get("Quantity", 0);
	m_ShipDate = pt.get("ShipDate", "");
	m_Status = pt.get("Status", "");
	m_Complete = pt.get("Complete", false);
}
Esempio n. 22
0
CryConfig CryConfig::load(const Data &data) {
  stringstream stream;
  data.StoreToStream(stream);
  ptree pt;
  read_json(stream, pt);

  CryConfig cfg;
  cfg._rootBlob = pt.get("cryfs.rootblob", "");
  cfg._encKey = pt.get("cryfs.key", "");
  cfg._cipher = pt.get("cryfs.cipher", "");
  cfg._version = pt.get("cryfs.version", "0.8"); // CryFS 0.8 didn't specify this field, so if the field doesn't exist, it's 0.8.
  return cfg;
}
Esempio n. 23
0
void User::fromJsonString(std::string const& jsonString)
{
	std::stringstream ss(jsonString);
	ptree pt;
	read_json(ss,pt);
	m_Id = pt.get("Id", 0);
	m_Username = pt.get("Username", "");
	m_FirstName = pt.get("FirstName", "");
	m_LastName = pt.get("LastName", "");
	m_Email = pt.get("Email", "");
	m_Password = pt.get("Password", "");
	m_Phone = pt.get("Phone", "");
	m_UserStatus = pt.get("UserStatus", 0);
}
Esempio n. 24
0
    // load stored parameters from disk
    void read_from_disk()
    {
        BOOST_ASSERT(!m_file_name.empty());

        m_cache.clear();

        boost::property_tree::ptree pt;
        try {
            read_json(m_file_name, pt);
        }
        catch(boost::property_tree::json_parser::json_parser_error &e){
            // no saved cache file, ignore
            return;
        }

        std::string stored_device;
        try {
            stored_device = pt.get<std::string>("header.device");
        }
        catch(boost::property_tree::ptree_bad_path&){
            return;
        }

        std::string stored_version;
        try {
            stored_version = pt.get<std::string>("header.version");
        }
        catch(boost::property_tree::ptree_bad_path&){
            return;
        }

        if(stored_device == m_device_name && stored_version == version_string()){
            typedef boost::property_tree::ptree::const_iterator pt_iter;
            for(pt_iter iter = pt.begin(); iter != pt.end(); ++iter){
                if(iter->first == "header"){
                    // skip header
                    continue;
                }

                boost::property_tree::ptree child_pt = pt.get_child(iter->first);
                for(pt_iter child_iter = child_pt.begin(); child_iter != child_pt.end(); ++child_iter){
                    set(iter->first, child_iter->first, boost::lexical_cast<uint_>(child_iter->second.data()));
                }
            }
        }

        m_dirty = false;
    }
Esempio n. 25
0
void Borrow::deSerialize(std::string ntwMsg)
{
    // Obj Creation
    ptree jsonObj;
    std::istringstream is(ntwMsg);
    read_json (is, jsonObj);

    // assignment
    borrowDate = jsonObj.get<std::string>("borrowDate");

    Book bw;
    bw.deSerializeJson(jsonObj.get<std::string>("borrowedBook"));
    borrowedBook = bw;

    Member brw;
    brw.deSerialize(jsonObj.get<std::string>("borrowingMember"));
    borrowingMember = brw;
}
Esempio n. 26
0
	// ------------------------------------------------------------------
	JSONObject::JSONObject(const std::string& id)
		:Resource(id, RESOURCE_JSON)
	{
		File* file = Resources::inst().require<File> (id);

		if (!file || !file->getData()) {
			throw Error("ObjectScript", getID(), "Cannot open file '" + id + "'");
		}

		try {		
			// Initialise the property tree
			std::stringstream ss((char*)file->getData());
			read_json(ss, mData);

		} catch (std::exception except) {
			throw Error("ObjectScript", getID(), std::string(except.what()));
		}
	}
Esempio n. 27
0
static void
changed (WebKitWebView *view, WebKitLoadEvent event, gpointer data)
{
	g_print ("%d ", event);
	if (!launched && event == WEBKIT_LOAD_FINISHED) {
		launched = TRUE;

		gchar *json = read_json ();
		if (!json)
			return;

		gchar *script = g_strdup_printf ("window.init_online(%s);", json);
		g_free (json);

		webkit_web_view_run_javascript (view, script, NULL, js_cb, NULL);
		g_free (script);
	}
}
Esempio n. 28
0
static void runtest_keys_invalid(const char *json_base_fn)
{
	char *json_fn = test_filename(json_base_fn);
	cJSON *tests = read_json(json_fn);
	assert((tests->type & 0xFF) == cJSON_Array);

	unsigned int idx;

	for (idx = 0; idx < cJSON_GetArraySize(tests); idx++) {

	    cJSON *test = cJSON_GetArrayItem(tests, idx);
	    assert((test->type & 0xFF) == cJSON_Array);
	    assert(cJSON_GetArraySize(test) == 1);

	    cJSON *j_base58 = cJSON_GetArrayItem(test, 0);
	    assert((j_base58->type & 0xFF) == cJSON_String);

	    unsigned char addrtype;
	    cstring *payload = base58_decode_check(&addrtype, j_base58->valuestring);
	    bool is_valid = (payload != NULL);

	    if (is_valid)
			if ((addrtype == PUBKEY_ADDRESS_TEST) ||
				(addrtype == PUBKEY_ADDRESS) ||
				(addrtype == SCRIPT_ADDRESS_TEST) ||
				(addrtype == SCRIPT_ADDRESS))
				    is_valid = (payload->len == RIPEMD160_DIGEST_LENGTH);
			else if
				((addrtype == PRIVKEY_ADDRESS_TEST) ||
				(addrtype == PRIVKEY_ADDRESS))
                is_valid = (payload->len == 32 ||
                            (payload->len == 33 && payload->str[32] == 1));
            else is_valid = false;

	    cstr_free(payload, true);
	    assert(!is_valid);
	}

	free(json_fn);
	cJSON_Delete(tests);
}
Esempio n. 29
0
void YubikoOtpKeyConfig::load() {
	BOOST_LOG_NAMED_SCOPE("YubikoOtpKeyConfig::load");
	const string myInFile = checkFileName(false);
	ptree myTree;
	read_json(myInFile, myTree);
	const string myVer(myTree.get<string>(K_NM_DOC_VERS));
	BOOST_LOG_TRIVIAL(info)<< K_NM_VERS << ":" << myVer;
	setPrivateId(myTree.get<string>(K_NM_DOC_PRIV_ID));
	setPublicId(myTree.get<string>(K_NM_DOC_PUB_ID));
	setSecretKey(myTree.get<string>(K_NM_DOC_SEC_KEY));
	setTimestamp(UTimestamp(myTree.get<uint64_t>(K_NM_DOC_TIMESTAMP)));
	setCounter(myTree.get<uint8_t>(K_NM_DOC_SES_CNTR));
	setCrc(myTree.get<uint16_t>(K_NM_DOC_CRC));
	setRandom(myTree.get<uint16_t>(K_NM_DOC_RANDOM));
	setUseCounter(myTree.get<uint8_t>(K_NM_DOC_USE_CNTR));
	setDescription(myTree.get<string>(K_NM_DOC_DESC));
	if (myVer != "0.0.1") {
		const string mySysUser { myTree.get<string>(K_NM_DOC_SYS_USER) };
		if (!mySysUser.empty())
			setSysUser(mySysUser);
	}
	itsChangedFlag = false;
}
Esempio n. 30
0
CryConfig CryConfig::load(const Data &data) {
  stringstream stream;
  data.StoreToStream(stream);
  ptree pt;
  read_json(stream, pt);

  CryConfig cfg;
  cfg._rootBlob = pt.get<string>("cryfs.rootblob");
  cfg._encKey = pt.get<string>("cryfs.key");
  cfg._cipher = pt.get<string>("cryfs.cipher");
  cfg._version = pt.get<string>("cryfs.version", "0.8"); // CryFS 0.8 didn't specify this field, so if the field doesn't exist, it's 0.8.
  cfg._createdWithVersion = pt.get<string>("cryfs.createdWithVersion", cfg._version); // In CryFS <= 0.9.2, we didn't have this field, but also didn't update cryfs.version, so we can use this field instead.
  cfg._blocksizeBytes = pt.get<uint64_t>("cryfs.blocksizeBytes", 32832); // CryFS <= 0.9.2 used a 32KB block size which was this physical block size.

  optional<string> filesystemIdOpt = pt.get_optional<string>("cryfs.filesystemId");
  if (filesystemIdOpt == none) {
    cfg._filesystemId = Random::PseudoRandom().getFixedSize<FilesystemID::BINARY_LENGTH>();
  } else {
    cfg._filesystemId = FilesystemID::FromString(*filesystemIdOpt);
  }

  return cfg;
}