コード例 #1
0
ファイル: output.cpp プロジェクト: justwalk/Panasonic
void printHomeData(ULONG ID) {
	printHeaders();
	JSON::Object obj;
	obj.add(new JSON::String("ID"), new JSON::Integer(ID));
	obj.add(new JSON::String("homeData"), new JSON::String("test"));
	obj.render();
}
コード例 #2
0
// Test connection with node.
bool ElasticSearch::isActive() {

    Json::Object root;

    try {
        _http.get(0, 0, &root);
    }
    catch(Exception& e){
        printf("get(0) failed in ElasticSearch::isActive(). Exception caught: %s\n", e.what());
        return false;
    }
    catch(std::exception& e){
        printf("get(0) failed in ElasticSearch::isActive(). std::exception caught: %s\n", e.what());
        return false;
    }
    catch(...){
        printf("get(0) failed in ElasticSearch::isActive().\n");
        return false;
    }

    if(root.empty())
        return false;

    if(!root.member("status") || root["status"].getInt() != 200){
        printf("Status is not 200. Cannot find Elasticsearch Node.\n");
        return false;
    }

    return true;
}
コード例 #3
0
ファイル: yggdrasil.cpp プロジェクト: andrewphorn/MCPP
Promise<void> Client::ClientSession (
    String access_token,
    String profile_id,
    String server_id,
    const Vector<Byte> & secret,
    const Vector<Byte> & public_key
) {

    //	Create JSON request
    JSON::Object obj;
    obj.Add(
        session_token_key,
        std::move(access_token),
        session_profile_key,
        std::move(profile_id),
        session_server_id_key,
        get_hash(server_id,secret,public_key)
    );

    //	We have to use a custom URL
    auto request=get_request(std::move(obj));
    request.URL=String::Format(
                    session_url,
                    client_session_endpoint
                );

    //	Dispatch
    return dispatch<void>(std::move(request));

}
コード例 #4
0
ファイル: RSexp.cpp プロジェクト: dreammaster38/rstudio
SEXP create(const json::Object& value, Protect* pProtect)
{
   // create the list
   SEXP listSEXP ;
   pProtect->add(listSEXP = Rf_allocVector(VECSXP, value.size()));
   
   // build list of names
   SEXP namesSEXP ;
   pProtect->add(namesSEXP = Rf_allocVector(STRSXP, value.size()));
   
   // add each object field to it
   int index = 0;
   for (json::Object::const_iterator 
            it = value.begin();
            it != value.end();
            ++it)
   {
      // set name
      SET_STRING_ELT(namesSEXP, index, Rf_mkChar(it->first.c_str()));
      
      // set value
      SEXP valueSEXP = create(it->second, pProtect);
      SET_VECTOR_ELT(listSEXP, index,  valueSEXP);
      
      // increment element index
      index++;
   }
   
   // attach names
   Rf_setAttrib(listSEXP, R_NamesSymbol, namesSEXP);
   
   // return the list
   return listSEXP;
}
コード例 #5
0
ファイル: yggdrasil.cpp プロジェクト: andrewphorn/MCPP
Promise<RefreshResult> Client::Refresh (
    String access_token,
    String client_token,
    Nullable<Profile> profile
) {

    //	Create JSON request
    JSON::Object obj;
    obj.Add(
        refresh_token_key,
        std::move(access_token),
        refresh_client_token_key,
        std::move(client_token)
    );
    if (!profile.IsNull()) obj.Add(
            refresh_profile_key,
            profile->ToJSON()
        );

    //	Dispatch request
    return dispatch<RefreshResult>(
               refresh_endpoint,
               std::move(obj)
           );

}
コード例 #6
0
void CompositorLoader::ParseRenderTargets(Compositor::Ptr& compositor, const json::Object& renderTargets)
{
	for (auto it = renderTargets.begin(); it != renderTargets.end(); ++it)
	{
		const Value& data = it->second;

		DataFormat dataFormat = JsonTypeHelper::ParseDataFormat(data);
		compositor->AddRenderTarget(it->first, dataFormat);

		if (data.HasKey("scale"))
		{
			compositor->SetRenderTargetScale(it->first, JsonTypeHelper::ParseFloatVector(data["scale"]).XY());
		}

		if (dataFormat.IsDepthFormat())
		{
			if (data.HasKey("clearDepth"))
			{
				compositor->SetClearDepth(it->first, data["clearDepth"].ToFloat(1.0f));
			}
		}
		else
		{
			if (data.HasKey("clearColor"))
			{
				compositor->SetClearColor(it->first, JsonTypeHelper::ParseColor(data["clearColor"]));
			}
		}
	}
}
コード例 #7
0
ファイル: yggdrasil.cpp プロジェクト: andrewphorn/MCPP
Promise<AuthenticateResult> Client::Authenticate (
    String username,
    String password,
    Nullable<String> client_token,
    Nullable<Agent> agent
) {

    //	Create JSON request
    JSON::Object obj;
    obj.Add(
        auth_username_key,
        std::move(username),
        auth_password_key,
        std::move(password)
    );
    if (!client_token.IsNull()) obj.Add(
            auth_client_token_key,
            std::move(*client_token)
        );
    if (!agent.IsNull()) obj.Add(
            auth_agent_key,
            agent->ToJSON()
        );

    //	Dispatch request
    return dispatch<AuthenticateResult>(
               auth_endpoint,
               std::move(obj)
           );

}
コード例 #8
0
/// Index a document.
bool ElasticSearch::index(const std::string& index, const std::string& type, const std::string& id, const Json::Object& jData){

    if(_readOnly)
        return false;

    std::stringstream url;
    url << index << "/" << type << "/" << id;

    std::stringstream data;
    data << jData;

    Json::Object result;
    _http.put(url.str().c_str(), data.str().c_str(), &result);

    if(!result.member("created"))
        EXCEPTION("The index induces error.");

    if(result.getValue("created"))
        return true;

    std::cout << "endPoint: " << index << "/" << type << "/" << id << std::endl;
    std::cout << "jData" << jData.pretty() << std::endl;
    std::cout << "result" << result.pretty() << std::endl;

    EXCEPTION("The index returns ok: false.");
    return false;
}
コード例 #9
0
void BulkBuilder::update_doc(const std::string &index, const std::string &type, const std::string &id, const Json::Object &fields, bool upsert) {
	createCommand("update", index, type, id);

	Json::Object updateFields;
	updateFields.addMemberByKey("doc", fields);
    updateFields.addMemberByKey("doc_as_upsert", upsert);

	operations.push_back(updateFields);
}
コード例 #10
0
WeatherForecast::WeatherForecast(const Json::Object &json)
    : _city(json.get("city"))
{
    _count = json.get("cnt").toNumber().orIfNull(0);
    _cod = json.get("cod").toString().orIfNull("");
    Json::Array weathers = json.get("list");
    for(auto w: weathers) {
        _weathers.push_back({w});
    }
}
コード例 #11
0
/// Delete the document by index/type/id.
bool ElasticSearch::deleteDocument(const char* index, const char* type, const char* id){
    if(_readOnly)
        return false;

    std::ostringstream oss;
    oss << index << "/" << type << "/" << id;
    Json::Object msg;
    _http.remove(oss.str().c_str(), 0, &msg);

    return msg.getValue("found");
}
コード例 #12
0
ファイル: yggdrasil.cpp プロジェクト: andrewphorn/MCPP
JSON::Object Profile::ToJSON () {

    JSON::Object retr;
    retr.Add(
        profile_id_key,
        std::move(ID),
        profile_name_key,
        std::move(Name)
    );

    return retr;

}
コード例 #13
0
ファイル: yggdrasil.cpp プロジェクト: andrewphorn/MCPP
JSON::Object Agent::ToJSON () {

    JSON::Object retr;
    retr.Add(
        agent_name_key,
        std::move(Name),
        agent_version_key,
        to_dbl(Version)
    );

    return retr;

}
コード例 #14
0
// Request the document number of type T in index I.
long unsigned int ElasticSearch::getDocumentCount(const char* index, const char* type){
    std::ostringstream oss;
    oss << index << "/" << type << "/_count";
    Json::Object msg;
    _http.get(oss.str().c_str(),0,&msg);

    size_t pos = 0;
    if(msg.member("count"))
        pos = msg.getValue("count").getUnsignedInt();
    else
        printf("We did not find \"count\" member.\n");

    return pos;
}
コード例 #15
0
ファイル: JsonUtil.cpp プロジェクト: AlexeyAB/Surround360
void exceptionIfMissingKeys(
    const json::Object& obj,
    const string& objKey,
    const string& key) {

  if (!obj.HasKey(objKey)) {
    throw VrCamException("JSON error. missing key:" + objKey);
  }

  const json::Object obj2 = obj[objKey];
  if (!obj2.HasKey(key)) {
    throw VrCamException("JSON error. missing key:" + key);
  }
}
コード例 #16
0
// Test if document exists
bool ElasticSearch::exist(const std::string& index, const std::string& type, const std::string& id){
    std::stringstream url;
    url << index << "/" << type << "/" << id;

    Json::Object result;
    _http.get(url.str().c_str(), 0, &result);

    if(!result.member("found")){
        std::cout << result << std::endl;
        EXCEPTION("Database exception, field \"found\" must exist.");
    }

    return result.getValue("found");
}
コード例 #17
0
ファイル: JsonRpc.hpp プロジェクト: harupiko/rstudio
core::Error readObject(const json::Object& object, 
                       const std::string& name, 
                       T* pValue)
{
   json::Object::const_iterator it = object.find(name) ;
   if (it == object.end())
      return Error(errc::ParamMissing, ERROR_LOCATION) ;

   if (!isType<T>(it->second))
      return Error(errc::ParamTypeMismatch, ERROR_LOCATION) ;

   *pValue = it->second.get_value<T>() ;

   return Success() ;
}
コード例 #18
0
ファイル: yggdrasil.cpp プロジェクト: andrewphorn/MCPP
Promise<void> Client::Signout (String username, String password) {

    //	Create JSON request
    JSON::Object obj;
    obj.Add(
        signout_username_key,
        std::move(username),
        signout_password_key,
        std::move(password)
    );

    //	Dispatch
    return dispatch<void>(
               signout_endpoint,
               std::move(obj)
           );

}
コード例 #19
0
/// Delete the document by index/type.
bool ElasticSearch::deleteAll(const char* index, const char* type){
    if(_readOnly)
        return false;

    std::ostringstream uri, data;
    uri << index << "/" << type << "/_query";
    data << "{\"query\":{\"match_all\": {}}}";
    Json::Object msg;
    _http.remove(uri.str().c_str(), data.str().c_str(), &msg);

    if(!msg.member("_indices") || !msg["_indices"].getObject().member(index) || !msg["_indices"].getObject()[index].getObject().member("_shards"))
        return false;

    if(!msg["_indices"].getObject()[index].getObject()["_shards"].getObject().member("failed"))
        return false;

    return (msg["_indices"].getObject()[index].getObject()["_shards"].getObject()["failed"].getInt() == 0);
}
コード例 #20
0
ファイル: yggdrasil.cpp プロジェクト: andrewphorn/MCPP
Promise<void> Client::Invalidate (String access_token, String client_token) {

    //	Create JSON request
    JSON::Object obj;
    obj.Add(
        invalidate_token_key,
        std::move(access_token),
        invalidate_client_token_key,
        std::move(client_token)
    );

    //	Dispatch
    return dispatch<void>(
               invalidate_endpoint,
               std::move(obj)
           );

}
コード例 #21
0
// Update a document field.
bool ElasticSearch::update(const std::string& index, const std::string& type, const std::string& id, const std::string& key, const std::string& value){
    if(_readOnly)
        return false;

    std::stringstream url;
    url << index << "/" << type << "/" << id << "/_update";

    std::stringstream data;
    data << "{\"doc\":{\"" << key << "\":\""<< value << "\"}}";

    Json::Object result;
    _http.post(url.str().c_str(), data.str().c_str(), &result);

    if(!result.member("_version"))
        EXCEPTION("The update failed.");

    return true;
}
コード例 #22
0
// Update doccument fields.
bool ElasticSearch::update(const std::string& index, const std::string& type, const std::string& id, const Json::Object& jData){
    if(_readOnly)
        return false;

    std::stringstream url;
    url << index << "/" << type << "/" << id << "/_update";

    std::stringstream data;
    data << "{\"doc\":" << jData;
    data << "}";

    Json::Object result;
    _http.post(url.str().c_str(), data.str().c_str(), &result);

    if(result.member("error"))
        EXCEPTION("The update doccument fields failed.");

    return true;
}
コード例 #23
0
/// Search API of ES.
long ElasticSearch::search(const std::string& index, const std::string& type, const std::string& query, Json::Object& result, const int n_result=10){

    std::stringstream url;
    url << index << "/" << type << "/_search?size=" << n_result;

    _http.post(url.str().c_str(), query.c_str(), &result);

    if(!result.member("timed_out")){
        std::cout << url.str() << " -d " << query << std::endl;
        std::cout << "result: " << result << std::endl;
        EXCEPTION("Search failed.");
    }

    if(result.getValue("timed_out")){
        std::cout << "result: " << result << std::endl;
        EXCEPTION("Search timed out.");
    }

    return result.getValue("hits").getObject().getValue("total").getLong();
}
コード例 #24
0
ファイル: yggdrasil.cpp プロジェクト: andrewphorn/MCPP
Promise<bool> Client::Validate (String access_token) {

    //	Create JSON request
    JSON::Object obj;
    obj.Add(
        validate_token_key,
        std::move(access_token)
    );

    //	Dispatch request
    return http.Execute(
               get_request(
                   validate_endpoint,
                   std::move(obj)
               )
    ).Then([] (Promise<MCPP::HTTPResponse> p) {

        auto response=p.Get();
        try {

            check(response);

            //	We need to catch the ERROR to see whether
            //	it's JUST RETURNING FALSE ARE YOU KIDDING
            //	ME?
        } catch (const Error & e) {

            if (
                (e.Type==invalid_token_type) &&
                (e.Message==invalid_token_message)
            ) return false;

            throw;

        }

        return true;

    });

}
コード例 #25
0
void getMailSettings(JSON::Object &obj, IDatabase *db)
{
	std::vector<std::wstring> slist=getMailSettingsList();
	IQuery *q=db->Prepare("SELECT key, value FROM settings_db.settings WHERE clientid=0 AND key=?");
	for(size_t i=0;i<slist.size();++i)
	{
		q->Bind(slist[i]);
		db_results res=q->Read();
		q->Reset();
		if(!res.empty())
		{
			obj.set(Server->ConvertToUTF8(slist[i]), res[0][L"value"]);
		}
		else
		{
			std::string v="";
			if(slist[i]==L"mail_serverport")
				v="25";
			obj.set(Server->ConvertToUTF8(slist[i]), v);
		}
	}
}
コード例 #26
0
//retrive all documemnts of a class
int ElasticSearch::fullScan(const std::string& index, const std::string& type, const std::string& query, Json::Array& resultArray, int scrollSize) {

    // Get the scroll id
    std::stringstream scrollUrl;
    scrollUrl << index << "/" << type << "/_search?search_type=scan&scroll=10m&size=" << scrollSize;

    Json::Object scrollObject;
    _http.post(scrollUrl.str().c_str(),query.c_str(),&scrollObject);

    if(!scrollObject.member("hits"))
        EXCEPTION("Result corrupted, no member \"hits\".");

    if(!scrollObject.getValue("hits").getObject().member("total"))
        EXCEPTION("Result corrupted, no member \"total\" nested in \"hits\".");

    int total = scrollObject.getValue("hits").getObject().getValue("total").getInt();

    std::string scrollId = scrollObject["_scroll_id"].getString();
    int count = 0;
    while(count < total) {

        Json::Object result;
        _http.rawpost("_search/scroll?scroll=10m", scrollId.c_str(), &result);

        // Kepp the new scroll id we received to inject in the next iteration.
        scrollId = result["_scroll_id"].getString();

        for(const Json::Value& value : result["hits"].getObject()["hits"].getArray()){
            resultArray.addElement(value);
            ++count;
        }
    }

    if(count != total)
        EXCEPTION("Result corrupted, total is different from count.");

    return total;
}
コード例 #27
0
/// Index a document with automatic id creation
std::string ElasticSearch::index(const std::string& index, const std::string& type, const Json::Object& jData){

    if(_readOnly)
        return "";

    std::stringstream url;
    url << index << "/" << type << "/";

    std::stringstream data;
    data << jData;

    Json::Object result;
    _http.post(url.str().c_str(), data.str().c_str(), &result);

    if(!result.member("created") || !result.getValue("created")){
        std::cout << "url: " << url.str() << std::endl;
        std::cout << "data: " << data.str() << std::endl;
        std::cout << "result: " << result.str() << std::endl;
        EXCEPTION("The index induces error.");
    }

    return result.getValue("_id").getString();
}
コード例 #28
0
ファイル: LinkedInService.C プロジェクト: RavilN/wt
    // this method is called when REST response is received for request to get user information:
    void handleMe(boost::system::error_code err, const Http::Message& response)
    {
#ifndef WT_TARGET_JAVA
      WApplication::instance()->resumeRendering();
#endif

      if (!err && response.status() == 200) {
#ifndef WT_TARGET_JAVA
        Json::ParseError e;
        Json::Object me;
        bool ok = Json::parse(response.body(), me, e);
#else
        Json::Object me;
        try {
	         me = (Json::Object)Json::Parser().parse(response.body());
        } 
        catch (Json::ParseError pe) {
        }
        bool ok = me.isNull();
#endif

        if (!ok) {
	        LOG_ERROR("could not parse JSON: '" << response.body() << "'");
	        setError(ERROR_MSG("badjson"));
	        authenticated().emit(Identity::Invalid);
        } 
        else {
	        std::string id = me.get("id");
          std::string email = me.get("emailAddress");
          
          if (getUserProfileAsJson)
          {
            // In the Identity's name field more complete user info is passed in JSON format as returned from LinkedIn, see details at:
            // https://developer.linkedin.com/docs/fields/basic-profile
            authenticated().emit(Identity(service().name(), id, response.body(), email, true));
          }
          else
          {
            std::string name = me.get("firstName");
            name += std::string(" ");
            name += std::string(me.get("lastName"));
            authenticated().emit(Identity(service().name(), id, name, email, true));
          }
        }
      } 
      else {
        if (!err) {
	        LOG_ERROR("user info request returned: " << response.status());
	        LOG_ERROR("with: " << response.body());
        } 
        else {
          LOG_ERROR("handleMe(): " << err.message());
        }
        setError(ERROR_MSG("badresponse"));
        authenticated().emit(Identity::Invalid);
      }
    }
コード例 #29
0
void PlotManipulatorManager::setPlotManipulatorValues(const json::Object& values)
{
   if (manipulatorIsActive())
   {
      // get the manipulator
      SEXP manipulatorSEXP = plotManager().activePlot().manipulatorSEXP();

      // set the underlying values
      std::for_each(values.begin(),
                    values.end(),
                    boost::bind(setManipulatorJsonValue, manipulatorSEXP, _1));

      // replay the manipulator
      replayManipulator(manipulatorSEXP);

      // set all of the buttons to false
      setManipulatorButtonsToFalse(manipulatorSEXP);
   }
   else
   {
      LOG_WARNING_MESSAGE("called setPlotManipulatorValues but active plot "
                          "has no manipulator");
   }
}
コード例 #30
0
void ControllerServer::handle_http_get( const HttpServer::Request & request , HttpServer::Response & response )
{
	if ( request.get_path() == "/controllers" )
	{
		JSON::Object result;

		result[ "version" ] = CONTROLLER_PROTOCOL_VERSION;
		result[ "port" ] = server->get_port();

		response.set_response( "application/json", result.stringify() );
		response.set_status( HttpServer::HTTP_STATUS_OK );

		return;
	}

    ResourceMap::iterator it = resources.find( request.get_path() );

    if ( it == resources.end() )
    {
        return;
    }

    response.respond_with_file_contents( it->second.native_uri );
}