Ejemplo n.º 1
0
//
// A GET of the dealer resource produces a list of existing tables.
// 
void BlackJackDealer::handle_get(http_request message)
{
    ucout <<  message.to_string() << endl;

    auto paths = http::uri::split_path(http::uri::decode(message.relative_uri().path()));
    if (paths.empty())
    {
        message.reply(status_codes::OK, TablesAsJSON(U("Available Tables"), s_tables));
        return;
    }

    utility::string_t wtable_id = paths[0];
    const utility::string_t table_id = wtable_id;

    // Get information on a specific table.
    auto found = s_tables.find(table_id);
    if (found == s_tables.end())
    {
        message.reply(status_codes::NotFound);
    }
    else
    {
        message.reply(status_codes::OK, found->second->AsJSON());
    }
};
Ejemplo n.º 2
0
http_response www_server::on_request(const http_request &req) {
	http_response resp;
	// we are support only HTTP GET method
	if (req.get_method() != http_method::get) {
		resp.set_status(http_error::method_not_allowed);
		resp.set_allow(http_method::get);
        resp.set_content("The POST requests are not supported yet.");
		return resp;
	}
	// obtain the name of the file requested
	url u(req.get_path_info());
	u.normalize(root_dir);
	// load file content to the server response
	try {
		ifstream in(u.path.c_str());
		// if file can't be open, throw an error
		if (!in)
			throw dbp::exception(string("File not found: ") + u.path);
		// set file content type
		resp.set_content_type(mime(u.path));
		// load file
		resp.add_content(in);
	}
	catch (dbp::exception &e) {
		// return error message
		resp.set_status(http_error::not_found);
		resp.set_content(e.what());
	}
	return resp;
}
Ejemplo n.º 3
0
// Handler to process HTTP::GET requests.
// Replies to the request with data.
void CasaLens::handle_get(http_request message)
{    
    auto path = message.relative_uri().path();
    auto content_data = m_htmlcontentmap.find(path);
    if (content_data == m_htmlcontentmap.end())
    {
        message.reply(status_codes::NotFound, U("Path not found")).then(std::bind(&handle_error, std::placeholders::_1));
        return;
    }

    auto file_name = std::get<0>(content_data->second);
    auto content_type = std::get<1>(content_data->second);
    concurrency::streams::fstream::open_istream(file_name, std::ios::in).then([=](concurrency::streams::istream is)
    {
        message.reply(status_codes::OK, is, content_type).then(std::bind(&handle_error, std::placeholders::_1));
    }).then([=](pplx::task<void>& t)
    {
        try
        {
            t.get();
        }
        catch(...)
        {
            // opening the file (open_istream) failed.
            // Reply with an error.
            message.reply(status_codes::InternalError).then(std::bind(&handle_error, std::placeholders::_1));
        }
    });
}
Ejemplo n.º 4
0
void FoldersService::render_DELETE(const http_request& req, http_response** res)
{
	if (req.get_user()=="a" && req.get_pass()=="a")
	{
		string strid = req.get_arg("id");

		CUUID id = CUUID::Parse(strid);
		HisDevFolder* folder = dynamic_cast<HisDevFolder*>(root->GetFolder()->Find(id));

		if (folder!=NULL)
		{
			HisDevFolder* parentfolder = dynamic_cast<HisDevFolder*>(folder->GetParent());
			parentfolder->Remove(id);
			delete(folder);
			root->Save();

			*res = new http_string_response("", 200, "application/json");
			return;
		}
	}
	else
	{
		string message = "Autentication error";
		*res = new http_string_response(message.c_str(), 401, "application/json");
		return;
	}

	*res = new http_string_response("", 403, "application/json");

}
Ejemplo n.º 5
0
void details::http_listener_impl::handle_request(http_request msg)
{
    // Specific method handler takes priority over general.
    const method &mtd = msg.method();
    if(m_supported_methods.count(mtd))
    {
        m_supported_methods[mtd](msg);
    }
    else if(mtd == methods::OPTIONS)
    {
        handle_options(msg);
    }
    else if(mtd == methods::TRCE)
    {
        handle_trace(msg);
    }
    else if(m_all_requests != nullptr)
    {
        m_all_requests(msg);
    }
    else
    {
        // Method is not supported.
        // Send back a list of supported methods to the client.
        http_response response(status_codes::MethodNotAllowed);
        response.headers().add(U("Allow"), get_supported_methods());
        msg.reply(response);
    }
}
Ejemplo n.º 6
0
void ModbusService::render_GET(const http_request& req, http_response** res)
{
	//api/modbus/holdings/{connectorname}/{devaddress}/{baseaddress}/{count}
	string connectorName = req.get_arg("connectorname");
	string strDevAddress = req.get_arg("devaddress");
	string strBaseAddress = req.get_arg("baseaddress");
	string strCount = req.get_arg("value");

	int devAddress = Converter::stoi(strDevAddress);
	int baseAddress = Converter::stoi(strBaseAddress);
	int count = Converter::stoi(strCount);

	Document document;
	StringBuffer buffer;
	PrettyWriter<StringBuffer> wr(buffer);
	Value jsonvalue;

	IModbus* modbus = mm->Find(connectorName);
	if (modbus!=NULL)
	{
		uint16_t* target = new uint16_t[count];
		if (modbus->getHoldings(devAddress,baseAddress,count,target))
		{
			document.SetArray();
			for(int i=0;i<count;i++)
			{
				Value jsonvalue;
				jsonvalue.SetUint(target[i]);
				document.PushBack(jsonvalue, document.GetAllocator());
			}
		}
		else
		{
			document.SetObject();

			jsonvalue.SetObject();
			jsonvalue.SetString("Error",document.GetAllocator());
			document.AddMember("Result",jsonvalue,document.GetAllocator());
			jsonvalue.SetString("Modbus getHoldings failed",document.GetAllocator());
			document.AddMember("Message",jsonvalue,document.GetAllocator());
		}

		delete[] target;
		target = NULL;
	}
	else
	{
		document.SetObject();
		jsonvalue.SetString("Error",document.GetAllocator());
		document.AddMember("Result",jsonvalue,document.GetAllocator());
		jsonvalue.SetString("Connector not found",document.GetAllocator());
		document.AddMember("Message",jsonvalue,document.GetAllocator());
	}

	document.Accept(wr);
	std::string json = buffer.GetString();
	*res = new http_response(http_response_builder(json, 200,"application/json").string_response());
}
Ejemplo n.º 7
0
void
RestEngineUri::handle_delete(http_request request)
{
    std::cout << request.method() << " : " << request.absolute_uri().path() << std::endl;
    http_response response(status_codes::OK);
    std::string resultstr("Not Supported");
    std::pair<bool, std::string> result {true, std::string()};
    make_response(response, resultstr, result);
    request.reply(response);
}
Ejemplo n.º 8
0
pplx::task<http_response> client::http_client::request(http_request request, pplx::cancellation_token token)
{
    if(!request.headers().has(header_names::user_agent))
    {
        request.headers().add(header_names::user_agent, USERAGENT);
    }

    request._set_base_uri(base_uri());
    request._set_cancellation_token(token);
    return m_pipeline->propagate(request);
}
Ejemplo n.º 9
0
void RDService::handle_get(http_request message)
{
	std::cout << "GET request got" << std::endl;
	web::uri reqUri = message.relative_uri();

	wcout << "Query:" << reqUri.query() << endl << reqUri.resource().to_string() << endl;

	utility::string_t queryStr = reqUri.query();
	
	auto path = reqUri.path();
	vector<utility::string_t> queryList = splitStringByAnd(queryStr);

	wstring conditions = U("");

	if (queryList.size() > 0)
	{
		conditions += queryList[0];
	}

	for (size_t i = 1; i < queryList.size(); i++)
	{
		conditions += U(" AND ") + queryList[i];
	}

	string finalCondition(conditions.begin(), conditions.end());

	vector<Vehicle> dbResult = DbHelper::getInstance()->getVehicleList((char *)finalCondition.c_str());

	string table = "";


	auto path2 = message.relative_uri().path();
	string reply;

	for (int i = 0; i < dbResult.size(); i++)
	{
		Vehicle v = dbResult[i];
		string tr = "";
		tr += v.Registration + "#";
		tr +=  to_string(v.Make) + "#";
		tr += "" + v.Model + "#";
		tr += "" + v.Owner + "#";
	
		table += tr;
	}

	utility::string_t replyText(table.begin(), table.end());
	message.reply(status_codes::OK, replyText).then([](pplx::task<void> t) { handle_error(t); });

}
Ejemplo n.º 10
0
    int operator() (const http_request& request, http_response* response)
    {
        char buf[256] = {0};
        std::string resp_body;
        std::vector<pid_t>::iterator it;
        std::string path_str;
        time_t time_now;

        ///只允许get方法
        http_request::request_method method = request.get_method();
        if (method != http_request::rGet)
            goto err;

        ///只允许请求/
        path_str =request.get_path();
        if (path_str != "/")
            return -1;

        if (request.get_request_head("Connection") == std::string("close")) {
            response->add_header("Connection", "close");
            response->set_close_conn(true);
        }

        snprintf(buf, sizeof(buf), "uid: %d \r\n", process_info::uid());
        resp_body = buf + process_info::username() + "\r\n" +
                    process_info::hostname() + "\r\n" + "\r\n";

        for (it = m_pid_vec_.begin(); it != m_pid_vec_.end(); ++it) {
            resp_body += process_info::get_proc_status(*it) + "\r\n";

            snprintf(buf, sizeof(buf), "opend Files: %d \r\n\r\n", process_info::get_opened_files(*it));
            resp_body += buf;
        }

        response->set_status_code(http_response::k200Ok);
        response->set_status_str("OK");
        response->add_header("Content-Type", "text/plain");
        response->add_header("Server", "async_serv");
        response->add_header("Connection", "keep-alive");

        ::time(&time_now);
        ::strftime(buf, sizeof(buf), "%a, %d %b %Y %H:%M:%S GMT", ::gmtime(&time_now));
        response->add_header("Date", buf);

        response->set_body(resp_body);

        return 0;
err:
        return default_404_response(request, response);
    }
Ejemplo n.º 11
0
void
RestRollupsUri::handle_post(http_request request)
{
    std::cout << request.method() << " : " << request.absolute_uri().path() << std::endl;
    int rc = 0;
    std::string resultstr;
    std::pair<bool, std::string> result {true, std::string()};

    char json[1024];

    // extract json from request
    snprintf(json, sizeof(json), "%s", request.extract_string(true).get().c_str());
    std::cout << "JSON:\n" << json << std::endl;

    rapidjson::Document document; 
    if (document.Parse(json).HasParseError())
    {
        rc = 1;
        resultstr += "document invalid";
    }

    rapidjson::SchemaValidator validator(*_schema);
    if (!document.Accept(validator)) {
        rc = 1;
        resultstr += get_schema_validation_error(&validator);
    }

    rapidjson::Value::MemberIterator name = document.FindMember("name");
    rapidjson::Value::MemberIterator nocsv = document.FindMember("nocsv");
    rapidjson::Value::MemberIterator quantity = document.FindMember("quantity");
    rapidjson::Value::MemberIterator maxdroop = document.FindMember("maxDroop");
    rapidjson::Value::MemberIterator maxsdroop_validation = document.FindMember("maxDroopMaxtoMinIOPSSection");

    // Execute Ivy Engine command
    if (rc == 0)
    {
        std::unique_lock<std::mutex> u_lk(goStatementMutex);
        std::pair<int, std::string> 
        rslt = m_s.create_rollup(name->value.GetString(),
                   (nocsv != document.MemberEnd() ? nocsv->value.GetBool() : false),
                   false /* have_quantity_validation */,
                   (maxsdroop_validation != document.MemberEnd() ? maxsdroop_validation->value.GetBool() : false),
                   (quantity != document.MemberEnd() ? quantity->value.GetInt() : 1),
                   (maxdroop != document.MemberEnd() ? maxdroop->value.GetDouble() : 6.95323e-310));
    }

    http_response response(status_codes::OK);
    make_response(response, resultstr, result);
    request.reply(response);
}
Ejemplo n.º 12
0
void
RestRollupsUri::handle_get(http_request request)
{
    std::cout << request.method() << " : " << request.absolute_uri().path() << std::endl;
    http_response response(status_codes::OK);
    std::string resultstr("Not Supported");
    std::pair<bool, std::string> result {true, std::string()};

    resultstr = m_s.show_rollup_structure();

    make_response(response, resultstr, result);
    request.reply(response);
    return;
}
Ejemplo n.º 13
0
// Respond to HTTP::POST messages
// Post data will contain the postal code or location string.
// Aggregate location data from different services and reply to the POST request.
void CasaLens::handle_post(http_request message)
{
    auto path = message.relative_uri().path();
    if (0 == path.compare(U("/")))
    {
        message.extract_string()
            .then([=](const utility::string_t& location) { get_data(message, location); })
            .then([](pplx::task<void> t) { handle_error(t); });
    }
    else
    {
        message.reply(status_codes::NotFound, U("Path not found")).then([](pplx::task<void> t) { handle_error(t); });
    }
}
Ejemplo n.º 14
0
// Respond to HTTP::POST messages
// Post data will contain the postal code or location string.
// Aggregate location data from different services and reply to the POST request.
void CasaLens::handle_post(http_request message)
{ 
    auto path = message.relative_uri().path();
    if (0 == path.compare(U("/")))
    {
        message.extract_string().then([=](const utility::string_t& location)
        {
            get_data(message, location); 
        }).then(std::bind(&handle_error, std::placeholders::_1));
    }
    else
    {
        message.reply(status_codes::NotFound, U("Path not found")).then(std::bind(&handle_error, std::placeholders::_1));
    }
}
Ejemplo n.º 15
0
void ModbusService::render_PUT(const http_request& req, http_response** res)
{
	string connectorName = req.get_arg("connectorname");
	string strDevAddress = req.get_arg("devaddress");
	string strBaseAddress = req.get_arg("baseaddress");
	string strValue = req.get_arg("value");

	int devAddress = Converter::stoi(strDevAddress);
	int baseAddress = Converter::stoi(strBaseAddress);
	int value = Converter::stoi(strValue);

	Document document;
	StringBuffer buffer;
	PrettyWriter<StringBuffer> wr(buffer);
	document.SetObject();
	Value jsonvalue;

	IModbus* modbus = mm->Find(connectorName);
	if (modbus!=NULL)
	{

		if (modbus->setHolding(devAddress,baseAddress,value))
		{
			jsonvalue.SetString("OK",document.GetAllocator());
			document.AddMember("Result",jsonvalue,document.GetAllocator());
		}
		else
		{
			jsonvalue.SetString("Error",document.GetAllocator());
			document.AddMember("Result",jsonvalue,document.GetAllocator());
			jsonvalue.SetString("Modbus setHolding failed",document.GetAllocator());
			document.AddMember("Message",jsonvalue,document.GetAllocator());
		}
	}
	else
	{
		jsonvalue.SetString("Error",document.GetAllocator());
		document.AddMember("Result",jsonvalue,document.GetAllocator());
		jsonvalue.SetString("Connector not found",document.GetAllocator());
		document.AddMember("Message",jsonvalue,document.GetAllocator());
	}
	document.Accept(wr);
	std::string json = buffer.GetString();
	*res = new http_response(http_response_builder(json, 200,"application/json").string_response());
}
Ejemplo n.º 16
0
void MyListener::handle_get(http_request message)
{
	web::uri req_uri = message.request_uri();
	utility::string_t req_query = req_uri.query();
	auto req_split_query = web::uri::split_query(req_query);
	//utility::string_t params;
	std::string error;
	for (auto it = req_split_query.begin(); it != req_split_query.end(); ++it)
	{
		//params += (*it).first + utility::conversions::to_string_t(": ") + (*it).second + utility::conversions::to_string_t("\n");
		// ***** Проверка логина *****
		if (utility::conversions::to_utf8string((*it).first) == "login")
		{
			std::string login = utility::conversions::to_utf8string((*it).second);
			for (auto iter = login.begin(); iter != login.end(); ++iter)
			{
				if (!(*iter >= 'a' && *iter <= 'z'))
					error += "Error in login. Unacceptable symbols\n";
			}
		}
		// ***** Проверка пароля *****
		if (utility::conversions::to_utf8string((*it).first) == "password")
		{
		
			std::string pass = utility::conversions::to_utf8string((*it).second);
			if (pass.length() < 8)
				error += "Error in password. Insufficient password length\n";
			for (auto iter = pass.begin(); iter != pass.end(); ++iter)
			{
				//if (!isdigit(*iter) && !isalpha(*iter) && !ispunct(*iter))
				if (!(*iter >= 33 && *iter <= 126))
				{			
					error += "Error in password. Unacceptable symbols\n";
				}	
			}
		}
	}
	if (error == "")
		message.reply(status_codes::OK, "OK");// "OK\n" + utility::conversions::to_utf8string(params));
	else
		message.reply(status_codes::BadRequest, error);// + '\n' + utility::conversions::to_utf8string(params));
	
		
	////message.reply(status_codes::OK, params);
}
Ejemplo n.º 17
0
void RootResource::render(const http_request &request, http_response **response) {
    // Execute the appropriate handler function depending on the path or return a 404
    std::string path = request.get_path();
    std::string method = request.get_method();

    if (this->paths.find(path) != this->paths.end()) {
        // Found path - do we have an entry for the HTTP method being used?
        if (this->paths[path].find(method) != this->paths[path].end()) {
            // Found method so execute it and return
            // Sorry - this is dirty!
            (this->*(this->paths[path][method]))(request, response);
            return;
        }
    }

    // If we fall through to here then we didn't find anything - return 404
    *response = new http_response(http_response_builder("Not Found", 404).string_response());
}
Ejemplo n.º 18
0
//using the render method you are able to catch each type of request you receive
void cat_resource::render(const http_request& req, http_response** res)
{
    string file = req.get_arg("file");
    cout << "file: " << file << endl;

    //it is possible to send a response initializing an http_string_response
    //that reads the content to send in response from a string.
    *res = new http_response(http_response_builder(file, 200).file_response());
}
Ejemplo n.º 19
0
void CasaLens::fetch_data(http_request message, const std::wstring& postal_code, const std::wstring& location)
{
    json::value resp_data;

    try
    {
        m_rwlock.lock_read();
        resp_data = m_data[postal_code];
        m_rwlock.unlock();

        if (resp_data.is_null())
        {
            std::vector<pplx::task<json::value>> tasks;

            tasks.push_back(get_events(postal_code));
            tasks.push_back(get_weather(postal_code));
            tasks.push_back(get_pictures(location, U("4")));
            tasks.push_back(get_movies(postal_code));

            pplx::when_all(tasks.begin(), tasks.end()).wait();
            resp_data = json::value::object();

            for (auto& iter : tasks)
            {
                auto jval = iter.get();
                auto key = jval.as_object().begin()->first;
                resp_data[key] = jval.as_object().begin()->second;
            }

            m_rwlock.lock();
            m_data[postal_code] = resp_data;
            m_rwlock.unlock();
        }

        // Reply with the aggregated JSON data
        message.reply(status_codes::OK, resp_data).then([](pplx::task<void> t) { handle_error(t); });
    }
    catch (...)
    {
        message.reply(status_codes::InternalError).then([](pplx::task<void> t) { handle_error(t); });
    }
}
Ejemplo n.º 20
0
void
RestRollupsUri::handle_put(http_request request)
{
    std::cout << request.method() << " : " << request.absolute_uri().path() << std::endl;
    int rc = 0;
    std::string resultstr;
    std::pair<bool, std::string> result {true, std::string()};

    char json[1024];

    // extract json from request
    snprintf(json, sizeof(json), "%s", request.extract_string(true).get().c_str());
    std::cout << "JSON:\n" << json << std::endl;

    rapidjson::Document document; 
    if (document.Parse(json).HasParseError())
    {
        rc = 1;
        resultstr += "document invalid";
    }

    rapidjson::SchemaValidator validator(*_schema);
    if (!document.Accept(validator)) {
        rc = 1;
        resultstr += get_schema_validation_error(&validator);
    }

    rapidjson::Value::MemberIterator name = document.FindMember("name");
    rapidjson::Value::MemberIterator parameters = document.FindMember("parameters");

    // Execute Ivy Engine command
    if (rc == 0)
    {
        std::unique_lock<std::mutex> u_lk(goStatementMutex);
        std::pair<int, std::string> 
        rslt = m_s.edit_rollup(name->value.GetString(), parameters->value.GetString());
    }

    http_response response(status_codes::OK);
    make_response(response, resultstr, result);
    request.reply(response);
}
Ejemplo n.º 21
0
void BlackJackDealer::word_article_get(http_request message)
{
//  message.method()

  auto r_uri = message.request_uri();
  uri_builder uri_b(r_uri);
  string s_q = uri_b.query();

//  stringstream ss;
//  auto json = dictHandler->PrefixMatch();
//  json.serialize(ss);
//  auto str = ss.str();
  UrlParameter url_par(s_q);

  string s_res;
  dictHandler->FindArticle(url_par.value, s_res);
  cout << s_res << endl;




  QString qt_str = QString::fromStdString(s_res);
  QDomDocument qdoc;
  qdoc.setContent(qt_str);

  QDomNode child = qdoc.firstChild();

  QString body_str;
  QTextStream stream(&body_str);
  child.save(stream, QDomNode::CDATASectionNode /* = 4 */);



  s_res = body_str.toUtf8().constData();;
  http_response http_resp(status_codes::OK);
//  http_resp.set_body(s_res);
  http_resp.set_body(s_res);
  http_resp.headers().add("Access-Control-Allow-Origin", "*");
  http_resp.headers().add("Content-Type","application/json");
  message.reply(http_resp);

}
void MetaCDNReceiver::handle_register(http_request message) {
	/*
	-when a new CDN joins, it has to register itself to Meta Server

	JSON Format
	Request
	{
		"Type": 0, //0=for cdn, 1=for fss
		"IP": "1.1.1.1:4000", //the sender CDN's IP address + port(listening to incoming requests)
		"Lat": 23.00, //the sender CDN's location
		"Lng": 148.12
	}
	Response
	{
		"CdnId": 1 //the assigned id for the cdn
	}

	*/
	try {

		int assignedId = -1;
		if(message.headers().content_type()==U("application/json")) {
			cout << endl << "---------------"<< endl;
			cout << message.to_string() << endl <<endl;

			json::value jsonObj = message.extract_json().get();
			if(jsonObj.at(U("Type")).as_integer() == 0) {
				string ipAddr = utility::conversions::to_utf8string(jsonObj.at(U("IP")).as_string());
				//TODO: validate ip address
				Address cdnAddr(make_pair(jsonObj.at(U("Lat")).as_double(), jsonObj.at(U("Lng")).as_double()), ipAddr);
				assignedId = m_meta->registerCdn(cdnAddr);
				json::value respFinal = json::value::object();
				respFinal[U("CdnId")] = json::value::number(assignedId);
				message.reply(assignedId!=-1? status_codes::OK : status_codes::NotFound, respFinal);
			} else if(jsonObj.at(U("Type")).as_integer() == 1){
				string ipAddr = utility::conversions::to_utf8string(jsonObj.at(U("IP")).as_string());
				//TODO: validate ip address
				Address fssAddr(make_pair(jsonObj.at(U("Lat")).as_double(), jsonObj.at(U("Lng")).as_double()), ipAddr);
				m_meta->setFssAddr(fssAddr);
				message.reply(status_codes::OK, "FSS registration complete");
			} else {
				message.reply(status_codes::Forbidden, U("Invalid type"));
			}
		} else {
			message.reply(status_codes::Forbidden, U("Json object is required"));
		}
	} catch(json::json_exception &e) {
		message.reply(status_codes::Forbidden, U("Invalid json object"));
		return;
	}
}
Ejemplo n.º 23
0
void server_respond(http_server::pipe_t &pipe, const http_request &request, bool is_tls)
{
  auto m = response_map.find(request.method_str()); // is it GET, POST, etc...?
  if (m != response_map.end())
  {
    auto e = m->second.find(request.get_url_field(UF_PATH));
    if (e != m->second.end())
    {
      e->second->call(pipe, request);
      return;
    }
  }

  anon_log("returning 404 for \"" << request.method_str() << " " << request.get_url_field(UF_PATH) << "\"");

  http_response response;
  response.add_header("Content-Type", "text/plain");
  response << "404 - not found\n";
  response << request.get_url_field(UF_PATH) << "\n";
  pipe.respond(response);
}
void MetaCDNReceiver::handle_delete(http_request message) {
	/*
	Use cases:
	1. when CDN deletes a file from itself to store some other file because of its limited capacity

	JSON Format
	Request
	{
		"FileName": "a.txt",
		"CdnId" : 2
	}

	Response: status OK or Forbidden (no json object included)
	*/
	try {
		int result;
		if(message.headers().content_type()==U("application/json")) {
			cout << endl << "---------------"<< endl;
			cout << message.to_string() << endl <<endl;

			json::value jsonObj = message.extract_json().get();
			int cdnId = jsonObj.at(U("CdnId")).as_integer();
			string fileName = utility::conversions::to_utf8string(jsonObj.at(U("FileName")).as_string());
			result = m_meta->deleteCdnFromMetaEntry(fileName, cdnId);
			message.reply(status_codes::OK, result==0? U("Deleted successfully") : U("Delete failed"));
		} else {
			message.reply(status_codes::Forbidden, U("Json object is required"));
		}
	} catch(json::json_exception &e) {
		message.reply(status_codes::Forbidden, U("Invalid json object"));
		return;
	}
}
Ejemplo n.º 25
0
//using the render method you are able to catch each type of request you receive
void hello_world_resource::render(const http_request& req, http_response** res)
{
    //it is possible to store data inside the resource object that can be altered
    //through the requests
    std::cout << "Data was: " << data << std::endl;
    std::string datapar = req.get_arg("data");
    set_some_data(datapar == "" ? "no data passed!!!" : datapar);
    std::cout << "Now data is:" << data << std::endl;

    //it is possible to send a response initializing an http_string_response
    //that reads the content to send in response from a string.
    *res = new http_response(http_response_builder("Hello World!!!", 200).string_response());
}
Ejemplo n.º 26
0
		HTTPRequest(http_request& request)
			: request(request)
		{
			// store all argument keys as lower case to be ensure we support any spelling
			auto& f = std::use_facet<std::ctype<utility::char_t>>(std::locale());
			map<string_t, string_t> srcArguments = uri::split_query(uri::decode(request.request_uri().query()));
			for (const auto& srcArg : srcArguments)
			{
				string_t key = srcArg.first;
				f.tolower(&key[0], &key[0] + key.size());
				arguments[string(key.begin(), key.end())] = string(srcArg.second.begin(), srcArg.second.end());
			}
		}
Ejemplo n.º 27
0
//
// A POST of the dealer resource creates a new table and returns a resource for
// that table.
// 
void BlackJackDealer::handle_post(http_request message)
{
    ucout <<  message.to_string() << endl;

    auto paths = uri::split_path(uri::decode(message.relative_uri().path()));
    
    if (paths.empty())
    {
        utility::ostringstream_t nextIdString;
        nextIdString << nextId;

        std::shared_ptr<DealerTable> tbl = std::make_shared<DealerTable>(nextId, 8, 6);
        s_tables[nextIdString.str()] = tbl;
        nextId += 1;

        message.reply(status_codes::OK, BJPutResponse(ST_PlaceBet, tbl->AsJSON()).AsJSON());
        return;
    }
    utility::string_t wtable_id = paths[0];
    const utility::string_t table_id = wtable_id;

    // Join an existing table.
    auto found = s_tables.find(table_id);
    if (found == s_tables.end())
    {
        message.reply(status_codes::NotFound);
        return;
    }

    auto table = std::static_pointer_cast<DealerTable>(found->second);

    if ( table->Players.size() < table->Capacity )
    {
        std::map<utility::string_t, utility::string_t> query = uri::split_query(uri::decode(message.request_uri().query()));

        auto cntEntry = query.find(QUERY_NAME);

        if (cntEntry != query.end() && !cntEntry->second.empty())
        {
            table->AddPlayer(Player(cntEntry->second));
            message.reply(status_codes::OK, BJPutResponse(ST_PlaceBet, table->AsJSON()).AsJSON());
        }
        else
        {
            message.reply(status_codes::Forbidden, U("Player name is required in query"));
        }
    }
    else
    {
        utility::ostringstream_t os;
        os << U("Table ") << table->Id << U(" is full");
        message.reply(status_codes::Forbidden, os.str());
    }
};
Ejemplo n.º 28
0
void FoldersService::render_PUT(const http_request& req, http_response** res)
{
	if (req.get_user()=="a" && req.get_pass()=="a")
	{
		string strid = req.get_arg("id");
		string content = req.get_content();

		if (UpdateFolder(strid,content))
		{
			*res = new http_string_response("", 200, "application/json");
			return;
		}
	}
	else
	{
		string message = "Autentication error";
		*res = new http_string_response(message.c_str(), 401, "application/json");
		return;
	}

	*res = new http_string_response("", 403, "application/json");

}
Ejemplo n.º 29
0
void BlackJackDealer::handle_get(http_request message)
{
//    UrlParameters pars(message.request_uri());
    auto q_str = message.request_uri().query();
    UrlParameter url_par(q_str);


    stringstream ss;
    auto json = dictHandler->PrefixMatch(url_par.value);
    json.serialize(ss);
    auto str = ss.str();





    http_response http_resp(status_codes::OK);
    http_resp.set_body(str);
    http_resp.headers().add("Access-Control-Allow-Origin", "*");
    http_resp.headers().add("Content-Type","application/json");
    message.reply(http_resp);

}
Ejemplo n.º 30
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");
}