예제 #1
0
파일: behavior_chart.cpp 프로젝트: txe/ieml
    // canvas::draw overridable
    virtual void draw( HELEMENT he, graphics& gx, UINT width, UINT height )
    { 
      if( !data.is_array() )
      {
        draw_message( gx, width, height, const_wchars(L"Data not found") );
        return; 
      }

      color black(0,0,0);

       // x axis
      gx.line_cap(LINE_CAP_BUTT);
      gx.line_color(black);
      gx.line( 0.5, height - 0.5, width - 0.5, height - 0.5 ); // 0.5 - to draw line in the middle of the pixel

      for( int n = 0; n < data.length(); ++n )
      {
        json::value bar_def = data[n];
        json::value color_v = bar_def.k2v(L"color"); 
        json::value value_v = bar_def.k2v(L"value");
        if( color_v.is_undefined() || value_v.is_undefined())
        {
          draw_message( gx, width, height, const_wchars(L"Bad data structure") );
          return; 
        }
        draw_bar(gx, width, height, n, data.length(), color(color_v.get(0)), value_v.get(1.0));
      }
    }
예제 #2
0
	/*!
	 * \brief Reads an ECMAScript conformant number from the input buffer
	 */
bool parser_UTF8::readnum(JSON::value &rv){
	bool flt=false;
	const char *strt =bfr.ptr;
	bool fail=false;
	while (charisNumeric(*(bfr.ptr))){
		if (*(bfr.ptr) == '.' || *(bfr.ptr) == 'e' || *(bfr.ptr) == 'E'){flt=true;}
		++bfr.ptr;
		if (bfr.ptr == bfr.end) break;
	}
	int len = bfr.ptr - strt;
	char *tmpbuf = new char[len +1];
	memcpy(tmpbuf,strt,len);
	tmpbuf[len] = '\0';
	if (flt){
		char *nd;
		double v = strtod(tmpbuf,&nd);
		if (nd != tmpbuf+len) fail=true;
		rv.setnumber(v);
	}else{
		aint v;
		char *nd;
		v=strtoaint(tmpbuf,&nd,10);
		if (nd != tmpbuf+len) fail=true;
		rv.setnumber(v);
	}
	delete [] tmpbuf;
	return !fail;
}
예제 #3
0
 json::value main_frame::open(json::value url, json::value param)
 {
   if( !url.is_string() )
     return json::value(false);
   sciter::main_frame* wnd = new sciter::main_frame(url.to_string().c_str());
   return json::value(wnd != 0);
 }
예제 #4
0
bool UTF_test::readarray(){
	JSON::parser_UTF8 parser("[ \"a\" , \"b\" ]");
	JSON::value a;
	parser.readarray(a);
	if (a.getrawarray().size() != 2){
		return false;
	}

	parser.bfr.mapstring("[ 3 1 4 1 5 9 2 6 5 3]");
	parser.getvalue(a);
	if (a.getrawarray().size() != 10){
		return false;
	}
	if (a[5].getinteger() != 9) return false;

	parser.bfr.mapstring("[ [1,1,2,3,5],[8,13,21,34]]");
	parser.getvalue(a);
	astr tmp;
	a.getstring(tmp);

	if (tmp != A(" [  [ 1 , 1 , 2 , 3 , 5 ]  ,  [ 8 , 13 , 21 , 34 ]  ] ")){
		return false;
	}

	return true;
}
void HandleJson::EndTask(json::value jsonObj)
{
    /// Get the value for Json Object.
    int jobId = jsonObj.at(U("JobId")).as_integer();
    int taskId = jsonObj.at(U("TaskId")).as_integer();

    JobTaskDb::GetInstance().EndTask(jobId, taskId);
}
StartTaskArgs StartTaskArgs::FromJson(const json::value& j)
{
    StartTaskArgs args(
        JsonHelper<int>::Read("JobId", j.at("m_Item1")),
        JsonHelper<int>::Read("TaskId", j.at("m_Item1")),
        ProcessStartInfo::FromJson(j.at("m_Item2")));

    return std::move(args);
}
예제 #7
0
bool UTF_test::read_file(){
	JSON::parser_UTF8 parser;
	JSON::value value;
	parser.parsefile(value, "test.json");

	if (parser.fail()) return false;
	return true;
	astr s = value.getchild("Hello").getrawstring();
	if (s != A("world")) return false;
	return true;
}
예제 #8
0
static string_t get_string( const json::value& obj, const string_t& key, const string_t& def ) {
	if( !obj.has_field( key ) ) {
		return def;
	}

	json::value val = obj.at( key );
	if( val.is_null( ) ) {
		return def;
	}
	return val.as_string( );
}
예제 #9
0
static void __print_scalar (string & result, const json::value & v)
{
    if (v.is_null()) {
        result.append("null");
    } else if (v.is_string()) {
		string r;
		result.append(1, '"');
		result.append(v.get<string>());
		result.append(1, '"');
	} else {
    	result.append(v.get<string>());
    }
}
예제 #10
0
bool UTF_test::reado1(){
	JSON::parser_UTF8 parser("{a:\"ba\", b:2}");
	astr s;
	JSON::value v;
	parser.parse(v);
	if (parser.errorcount() > 2) return false; // If error 11 is enabled, we don't want to fail here
	astr dst;
	v.getstring(dst,true,false);
	if (
		   (dst != A(" { \"a\" : \"ba\" , \"b\" : 2 } "))
		&& (dst != A(" { \"b\" : 2 , \"a\" : \"ba\" } "))
		){ return false;}
	return true;
}
예제 #11
0
	/*!
	 * \brief Reads an array from the input stream into \p rv
	 */
bool parser_UTF8::readarray(JSON::value &rv){
	rv.setarray();
	if (*bfr.ptr != '[') return false;
	++bfr.ptr;

	bool first=true;
	while (1){
		JSON::value curval;

		skipWS();
		if (bfr.ptr >= bfr.end){
			adderror(5);
			return false;
		}
		
		if (*bfr.ptr == ']'){
			++bfr.ptr;
			return true;
		}else if (*bfr.ptr != ','){
			if (first!=true){adderror(8);}
		}else{
			++bfr.ptr;
			skipWS();
			if (bfr.ptr >= bfr.end){
				adderror(5);
				return false;
			}
			if (*bfr.ptr == ']'){
				++bfr.ptr;
				return true;
			}
		}
		
		skipWS();
		if (bfr.ptr == bfr.end){
			adderror(5); return false;
		}
		
		
		getvalue(curval);
		if (curval.getdatatype() == datatype::_undefined && *(bfr.ptr)!=','){
			adderror(8);
			return false;
		}
		rv.addvalue(curval);
		first=false;
	}
	return true;
}
예제 #12
0
static void __print_container (string & result
        , json::value const & value
        , print_spec const & pspec
        , int indent)
{
    if (value.size() == 0) { 
        __print_open_brace(result, value, pspec);
        __print_close_brace(result, value, pspec);
        return;
    }
    
    json::value::const_iterator it_begin = value.cbegin();
    json::value::const_iterator it_end   = value.cend();
    json::value::const_iterator it       = it_begin;
    json::value::const_iterator it_next  = it_begin;
        
    ++it_next;
    
    indent += pspec.base_indent;
    
    __print_open_brace(result, value, pspec);
    result.append(pspec.new_line); // container content always begin after new line
    
    for (; it != it_end; ++it, ++it_next) {
        if (it == it_begin) {
            __print_indent(result, pspec, indent);
            
            if (pspec.comma_position == json::comma_next_line) {
                __print_indent(result, pspec, pspec.first_item_indent);
            }
        }
        
        if (value.is_object()) {
            __print_value(result, it.key(), *it, pspec, indent);
        } else {
            __print_value(result, *it, pspec, indent);
        }
        
        if (it_next != it_end) {
            __print_comma(result, pspec, indent);
        }
    }
    
    indent -= pspec.base_indent;    
    
    result.append(pspec.new_line);
    __print_indent(result, pspec, indent);
    __print_close_brace(result, value, pspec);
}
 // sets checkboxes by bit mask 
 inline void set_checkbox_bits(dom::element& el, const json::value& t )
 {
   selected_cb selected;
   dom::element r = el.parent(); // ATTN: I assume here that all checkboxes in the group belong to the same parent!
   r.find_all(&selected, "[type='checkbox'][name='%S']", el.get_attribute("name"));
   int m = 1, v = selected.elements.size()==1?(t.get(false)?1:0):t.get(0);
   for( unsigned int n = 0; n < selected.elements.size(); ++n, m <<= 1 )
   {
     dom::element& e = selected.elements[n];
     if( (v & m) != 0)
         e.set_state(  STATE_CHECKED, 0 ) ;
     else
         e.set_state(  0, STATE_CHECKED ) ;
   }
 }
void HandleJson::StartTask(json::value jsonObj, std::string callBackUri)
{
    std::cout << "StartTask ... " << std::endl;

    // Get value from Json Object.
    auto arg = jsonObj.at(U("m_Item1"));
    auto startInfoJson = jsonObj.at(U("m_Item2"));
    int jobId = arg.at(U("JobId")).as_integer();
    int taskId = arg.at(U("TaskId")).as_integer();
    ProcessStartInfo *startInfo = ProcessStartInfo::FromJson(startInfoJson);

    std::cout << "start the task: " << startInfo->commandLine << std::endl;

    JobTaskDb::GetInstance().StartJobAndTask(jobId, taskId, startInfo, callBackUri);
}
예제 #15
0
static void __print_value (string & result
        , string const & key
        , json::value const & value
        , print_spec const & pspec
        , int indent)
{
    result.append(__stringify(key));
    result.append(pspec.ws_before_kvseparator);
    result.append(pspec.key_separator);
    
    if (value.is_scalar()) {
        result.append(pspec.ws_after_kvseparator);
        __print_scalar(result, value);
    } else {
        if (pspec.brace_position == json::brace_same_line) {
            result.append(pspec.ws_after_kvseparator);
        } else if (pspec.brace_position == json::brace_next_line) {
            result.append(pspec.new_line);
            __print_indent(result, pspec, indent);
            __print_brace_indent(result, pspec, pspec.brace_indent);
        }
        
        indent += pspec.brace_indent;
        __print_container(result, value, pspec, indent);
        indent -= pspec.brace_indent;
    }
}
예제 #16
0
void print_json(const json::value & jvalue)
{
   if (!jvalue.is_null())
   {
        cout << jvalue << endl;
   }
}
void RemoteExecutor::ReportTaskCompletion(
    int jobId, int taskId, int taskRequeueCount, json::value jsonBody,
    const std::string& callbackUri)
{
    try
    {
        if (!jsonBody.is_null())
        {
            Logger::Debug(jobId, taskId, taskRequeueCount,
                "Callback to {0} with {1}", callbackUri, jsonBody);

            client::http_client client = HttpHelper::GetHttpClient(callbackUri);
            http_request request = HttpHelper::GetHttpRequest(methods::POST, jsonBody);
            http_response response = client.request(request).get();

            Logger::Info(jobId, taskId, taskRequeueCount,
                "Callback to {0} response code {1}", callbackUri, response.status_code());
        }
    }
    catch (const std::exception& ex)
    {
        this->jobTaskTable.RequestResync();
        Logger::Error(jobId, taskId, taskRequeueCount,
            "Exception when sending back task result. {0}", ex.what());
    }
}
예제 #18
0
bool UTF_test::readl1(){
	JSON::parser_UTF8 parser("true");
	JSON::value l;
	bool b = parser.readlit(l);
	if (l.getbool() != true) return false;	

	parser.bfr.mapstring("false");
	b = parser.readlit(l);
	if (l.getbool() != false) return false;	

	parser.bfr.mapstring("null");
	b = parser.readlit(l);
	if (l.getliteral(JSON::literals::_true) != JSON::literals::_null) return false;	

	return true;
}
void PacketStreamWriter::WriteMeta(PacketStreamSourceId src, const json::value& data)
{
    SCOPED_LOCK;
    writeTag(_stream, TAG_SRC_JSON);
    writeCompressedUnsignedInt(_stream, src);
    data.serialize(std::ostream_iterator<char>(_stream), false);
}
예제 #20
0
inline void __print_close_brace (string & result, json::value const & v, print_spec const & pspec)
{
    if (v.is_array()) {
        result.append(pspec.close_array_brace);
    } else {
        result.append(pspec.close_object_brace);
    }
}
예제 #21
0
void GoogleSearchClient::flattenJsonInnerLoop(json::value const & val, FlatJsonObject & json_map) {
  // input : Body of the google search response as json::value
  // This recursive function parse the Json raw value to a C++ multimap
  if (!val.is_null() && val.is_object()) {
    for (auto const &iter : val.as_object()) {
      //iter on each element for Json object type. Return a vect<string_t,json::value>
      const auto &mapKey = iter.first;
      const auto &content = iter.second;
      json_map.insert(std::pair<utility::string_t, utility::string_t>(mapKey, content.serialize()));
      flattenJsonInnerLoop(content, json_map);
    }
  } else if (val.is_array()) {
    for (auto const &content : val.as_array()) {
      //iter on each element for Json array type. Return a json::value
      flattenJsonInnerLoop(content, json_map);
    }
  }
}
예제 #22
0
http::http_request http_client_impl::_build_request(http::method method, http::uri_builder request_uri, const ::utility::string_t& accept, json::value object) const
{
    http::http_request msg(method);

    if (!accept.empty())
        msg.headers().add(U("Accept"), accept);

    msg.set_request_uri(request_uri.to_uri());

    if (method == http::methods::POST || method == http::methods::PUT || method == http::methods::PATCH)
    {
        if(object.is_null() || !object.is_object())
            throw std::invalid_argument("POST, PUT, and PATCH requests require a payload");

        msg.set_body(object);
    }

    return msg;
}
예제 #23
0
static string __to_string (json::value const & v, print_spec const & pspec)
{
    string r;
    
    if (v.is_scalar()) {
        __print_scalar(r, v);
        return r;
    }
    
    json::__print_container(r, v, pspec, 0);
    
    return r;
}
예제 #24
0
static void __print_value (string & result
        , json::value const & value
        , print_spec const & pspec
        , int indent)
{
//    __print_indent(result, pspec, indent);
    
    if (value.is_scalar()) {
        __print_scalar(result, value);
    } else {
        __print_container(result, value, pspec, indent);
    }
}    
예제 #25
0
파일: Source.cpp 프로젝트: ourselin/Master
void print_search_results(json::value const & value)
{
	if (!value.is_null())
	{
		//auto response = value.at(L"data");
		//auto results = response[L"movies"];

		// iteration is supported not directly on json::value but on 
		// json::object and json::array. Use json::value::as_object() and json::value::as_array().
		std::wcout << value.as_array().at(0) << std::endl;
		for (auto const & o : value.as_array())
		{
			auto id = o.at(L"id");
			auto name = o.at(L"name");
			auto username = o.at(L"username");
			auto email = o.at(L"email");
			auto address = o.at(L"address");
			auto street = address.at(L"street");
			
			std::wcout << id << std::endl << name << std::endl << username << std::endl << email << std::endl << street << std::endl << std::endl;
		}
	}
}
예제 #26
0
void Leanplum::ParserResponse(json::value response)
{
	if (response.is_null()){
		return;
	}

	CString key;
	VARIABLE_TYPE type;
	typedef std::map<CString, std::pair<VARIABLE_TYPE, CString>>::iterator it_type;
	for(it_type iterator = m_variablesMap.begin(); iterator != m_variablesMap.end(); iterator++) {
		key = iterator->first;
		type = iterator->second.first;
		if (VARIABLE_TYPE::INT == type) {
			 int v = response.at(key.GetBuffer()).as_integer();
			 iterator->second.second.Format(_T("%d"), v);
		} else if (VARIABLE_TYPE::BOOL == type) {
			bool v = response.at(key.GetBuffer()).as_bool();
			iterator->second.second = v? _T("true"):_T("false");
		} else if (VARIABLE_TYPE::STRING == type) {
			iterator->second.second = response.at(key.GetBuffer()).as_string().c_str();
		}
	}
}
예제 #27
0
void addline (json::value& jsonlines, ripplestate const& line, ledger::pointer ledger)
{
    stamount sabalance (line.getbalance ());
    stamount const& salimit (line.getlimit ());
    stamount const& salimitpeer (line.getlimitpeer ());
    json::value& jpeer (jsonlines.append (json::objectvalue));

    jpeer[jss::account] = to_string (line.getaccountidpeer ());
    if (assetcurrency() == sabalance.getcurrency()) {
        // calculate released & reserved balance for asset.
        auto lpledger = std::make_shared<ledger> (std::ref (*ledger), false);
        ledgerentryset les(lpledger, tapnone);
        auto sleripplestate = les.entrycache(ltripple_state, getripplestateindex(line.getaccountid(), line.getaccountidpeer(), assetcurrency()));
        les.assetrelease(line.getaccountid(), line.getaccountidpeer(), assetcurrency(), sleripplestate);
        stamount reserve = sleripplestate->getfieldamount(sfreserve);
        stamount balance = sleripplestate->getfieldamount(sfbalance);
        if (line.getaccountid() == sleripplestate->getfieldamount(sfhighlimit).getissuer()) {
            reserve.negate();
            balance.negate();
        }
        jpeer[jss::reserve] = reserve.gettext();
        jpeer[jss::balance] = balance.gettext();
    } else {
        // amount reported is positive if current account holds other
        // account's ious.
        //
        // amount reported is negative if other account holds current
        // account's ious.
        jpeer[jss::balance] = sabalance.gettext();
    }
    jpeer[jss::currency] = sabalance.gethumancurrency ();
    jpeer[jss::limit] = salimit.gettext ();
    jpeer[jss::limit_peer] = salimitpeer.gettext ();
    jpeer[jss::quality_in]
        = static_cast<json::uint> (line.getqualityin ());
    jpeer[jss::quality_out]
        = static_cast<json::uint> (line.getqualityout ());
    if (line.getauth ())
        jpeer[jss::authorized] = true;
    if (line.getauthpeer ())
        jpeer[jss::peer_authorized] = true;
    if (line.getnoripple ())
        jpeer[jss::no_ripple] = true;
    if (line.getnoripplepeer ())
        jpeer[jss::no_ripple_peer] = true;
    if (line.getfreeze ())
        jpeer[jss::freeze] = true;
    if (line.getfreezepeer ())
        jpeer[jss::freeze_peer] = true;
}
 inline void set_radio_index( dom::element& el, const json::value& t  )
 {
   selected_cb selected;
   dom::element r = el.parent(); // ATTN: I assume here that all radios in the group belong to the same parent!
   r.find_all(&selected, "[type='radio'][name='%S']", el.get_attribute("name"));
   unsigned int idx = (unsigned int)t.get(0);
   for( unsigned int n = 0; n < selected.elements.size(); ++n )
   {
     dom::element& e = selected.elements[n];
     if ( n == idx)
     {
       e.set_value(json::value(true));
       break;
     }
   }
 }
예제 #29
0
cache_pool::cache_pool(json::value const &settings) :
	d(new _data())
{
	std::string type = settings.get("cache.backend","none");
#ifndef CPPCMS_NO_CACHE
	if(type=="thread_shared") {
		if(settings.get("service.worker_processes",0)>1)
			throw cppcms_error(
				"Can't use `thread_shared' backend with more then one process ether set "
				"service.worker_processes to 0 or 1 or use cache.backend=\"process_shared\"");
		unsigned items = settings.get("cache.limit",64);
		d->module=impl::thread_cache_factory(items);
	}
	else if(type=="process_shared") {
#if defined(CPPCMS_WIN32)
		throw cppcms_error("The 'process_shared' backend is not supported under MS Windows and Cygwin platforms");
#elif defined(CPPCMS_NO_PREFOK_CACHE)
		throw cppcms_error("The 'process_shared' backend is disabled during build procedure");
#else // has prefork cache
		size_t memory = settings.get("cache.memory",16384);
		if(memory < 64)
			throw cppcms_error("'process_shared' cache backend requires at least 64 KB of cache memory: cache.memory >= 64");
		unsigned items = settings.get("cache.limit",memory);
		d->module=impl::process_cache_factory(memory*1024,items);
#endif // prefork cache
	}	
	else
#endif // no cache
	if(type != "none" ) {
		throw cppcms_error("Unsupported cache backend `" + type + "'");
	}
#ifndef CPPCMS_NO_TCP_CACHE	
	if(settings.find("cache.tcp").type()==json::is_object) {

		std::vector<std::string> ips=settings.get<std::vector<std::string> >("cache.tcp.ips");
		std::vector<int> ports = settings.get<std::vector<int> >("cache.tcp.ports");

		if(ips.empty() || ports.empty() || ips.size()!=ports.size()) {
			throw cppcms_error("Invalid settings in cache.tcp.ports or cache.tcp.ips");
		}

		booster::intrusive_ptr<impl::base_cache> l1=d->module;
		d->module=impl::tcp_cache_factory(ips,ports,l1);
	}
#endif // no tcp cace
}
예제 #30
0
    bool node::update(const json::value& new_data, unsigned keep_update_size_percent)
    {
        if ( new_data == data_ )
            return false;

        const std::size_t max_size = new_data.size() * keep_update_size_percent / 100;

        if ( max_size != 0 )
        {
            std::pair<bool, json::value> update_instruction = delta(data_, new_data, max_size);

            if ( update_instruction.first )
                updates_.insert(updates_.length(), update_instruction.second);

        }

        data_ = new_data;
        ++version_;

        remove_old_versions(max_size);

        return true;
    }