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; } }
// // 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()); } };
// 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)); } }); }
// // 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()); } };
// // A PUT to a table resource makes a card request (hit / stay). // void BlackJackDealer::handle_put(http_request message) { ucout << message.to_string() << endl; auto paths = uri::split_path(uri::decode(message.relative_uri().path())); auto query = uri::split_query(uri::decode(message.relative_uri().query())); auto queryItr = query.find(REQUEST); if (paths.empty() || queryItr == query.end()) { message.reply(status_codes::Forbidden, U("TableId and request are required.")); } utility::string_t wtable_id = paths[0]; utility::string_t request = queryItr->second; 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); } auto table = std::static_pointer_cast<DealerTable>(found->second); if ( request == BET ) { table->Bet(message); } else if ( request == DOUBLE ) { table->DoubleDown(message); } else if ( request == INSURE ) { table->Insure(message); } else if ( request == HIT ) { table->Hit(message); } else if ( request == STAY ) { table->Stay(message); } else if ( request == REFRESH ) { table->Wait(message); } else { message.reply(status_codes::Forbidden, U("Unrecognized request")); } };
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; } }
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); } }
// // A DELETE of the player resource leaves the table. // void BlackJackDealer::handle_delete(http_request message) { ucout << message.to_string() << endl; auto paths = uri::split_path(uri::decode(message.relative_uri().path())); if (paths.empty()) { message.reply(status_codes::Forbidden, U("TableId is required.")); 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); return; } auto table = std::static_pointer_cast<DealerTable>(found->second); 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() ) { if ( table->RemovePlayer(cntEntry->second) ) { message.reply(status_codes::OK); } else { message.reply(status_codes::NotFound); } } else { message.reply(status_codes::Forbidden, U("Player name is required in query")); } };
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); }
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); }
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); }); } }
// 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); }); } }
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); }); }
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; }
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); }
// 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)); } }
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 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); }
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); }
void RestEngineUri::handle_post(http_request request) { std::cout << request.method() << " : " << request.absolute_uri().path() << std::endl; std::cout << request.method() << " : " << request.headers()["Cookie"] << std::endl; int rc = 0; std::string resultstr; std::pair<bool, std::string> result {true, std::string()}; std::string cookie = request.headers()["Cookie"]; if (cookie != "session_cookie=" + _active_session_token) { //http_response response(status_codes::Locked); //make_response(response, resultstr, result); //request.reply(response); //return; } if (!is_session_owner(request)) { send_busy_response(request); return; } ostringstream o; o << "COOKIE:" << cookie << std::endl; o << "ACTIVE COOKIE:" << _active_session_token << std::endl; std::cout << o.str(); log (m_s.masterlogfile,o.str()); 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); } std::string select_str; std::string hosts_list; const Value& hosts = document["hosts"]; json_to_host_list(hosts, hosts_list); const Value& select = document["select"]; json_to_select_str(select, select_str); // Execute Ivy Engine command if (rc == 0) { std::unique_lock<std::mutex> u_lk(goStatementMutex); std::string outputfolder = m_s.get("output_folder_root").second; std::string testname = m_s.get("test_name").second; result = m_s.startup(outputfolder, testname, m_s.ivyscript_filename, hosts_list, select_str); } http_response response(status_codes::OK); make_response(response, resultstr, result); request.reply(response); }
void RestEngineUri::handle_get(http_request request) { std::cout << request.method() << " : " << request.absolute_uri().path() << std::endl; http_response response(status_codes::OK); std::string resultstr; std::pair<bool, std::string> result {true, std::string()}; bool get_hosts {false}; bool get_luns {false}; bool get_subsystems {false}; uri req_uri = request.absolute_uri(); std::map<utility::string_t, utility::string_t> qmap = req_uri.split_query(req_uri.query()); for (auto& kv : qmap) { std::cout << "key: " << kv.first << ", value: " << kv.second << std::endl; if (kv.first == "hosts" && kv.second == "true") get_hosts = true; else if (kv.first == "luns" && kv.second == "true") get_luns = true; else if (kv.first == "subsystems" && kv.second == "true") get_subsystems = true; else { resultstr = ivy_engine_get(kv.first); std::cout << "resultstr = " << resultstr << std::endl; make_response(response, resultstr, result); request.reply(response); return; } } // Hosts list rapidjson::Document jsonDoc; jsonDoc.SetObject(); rapidjson::Value hosts_array(rapidjson::kArrayType); rapidjson::Value subsystems_array(rapidjson::kArrayType); rapidjson::Value allluns_array(rapidjson::kArrayType); rapidjson::Value testluns_array(rapidjson::kArrayType); rapidjson::Value cmdluns_array(rapidjson::kArrayType); rapidjson::Document::AllocatorType& allocator = jsonDoc.GetAllocator(); if (get_hosts) { std::list<std::string>::iterator iter = m_s.hosts.begin(); std::list<std::string>::iterator eiter = m_s.hosts.end(); for (; iter != eiter; ++iter) { rapidjson::Value val((*iter).c_str(), jsonDoc.GetAllocator()); hosts_array.PushBack(val, allocator); } } // LUNS // allDiscoveredLUNs, availableTestLUNs, commandDeviceLUNs; if (get_luns) { for (auto it = m_s.allDiscoveredLUNs.LUNpointers.begin(); it != m_s.allDiscoveredLUNs.LUNpointers.end(); ++it) { rapidjson::Value val((*it)->toString().c_str(), jsonDoc.GetAllocator()); allluns_array.PushBack(val, allocator); } for (auto it = m_s.availableTestLUNs.LUNpointers.begin(); it != m_s.availableTestLUNs.LUNpointers.end(); ++it) { rapidjson::Value val((*it)->toString().c_str(), jsonDoc.GetAllocator()); testluns_array.PushBack(val, allocator); } for (auto it = m_s.commandDeviceLUNs.LUNpointers.begin(); it != m_s.commandDeviceLUNs.LUNpointers.end(); ++it) { rapidjson::Value val((*it)->toString().c_str(), jsonDoc.GetAllocator()); cmdluns_array.PushBack(val, allocator); } } // Subsystems list if (get_subsystems) { for (auto& kv : m_s.subsystems) { //std::cout << kv.first << " has value " << kv.second << std::endl; rapidjson::Value val(kv.first.c_str(), jsonDoc.GetAllocator()); subsystems_array.PushBack(val, allocator); } } if (get_hosts) jsonDoc.AddMember("Hosts", hosts_array, allocator); if (get_subsystems) jsonDoc.AddMember("Subsystems", subsystems_array, allocator); if (get_luns) jsonDoc.AddMember("AllDiscoveredLUNs", allluns_array, allocator); if (get_luns) jsonDoc.AddMember("AvailableTestLUNs", testluns_array, allocator); if (get_luns) jsonDoc.AddMember("CommandDeviceLUNs", cmdluns_array, allocator); rapidjson::StringBuffer strbuf; rapidjson::Writer<rapidjson::StringBuffer> writer(strbuf); jsonDoc.Accept(writer); response.headers().add(header_names::content_type, mime_types::application_json); response.headers().add(header_names::content_type, charset_types::utf8); response.set_body(strbuf.GetString()); request.reply(response); }
// Handler to process HTTP::GET requests. // Replies to the request with data. void odata_test_service::handle_get(http_request message) { try { bool is_async = false; auto prefer_header = message.headers().find(U("Prefer")); if (prefer_header != message.headers().end()) { if (prefer_header->second.find(U("respond-async")) != ::odata::utility::string_t::npos) { is_async = true; } } auto parsed_uri = m_uri_parser->parse_uri(message.relative_uri()); odata_message_writer writer(m_model, m_service_root); odata_context_url_builder context_url_builder(m_model, m_service_root); odata_metadata_builder metadata_builder(m_model, m_service_root); ::odata::utility::string_t content; if (parsed_uri->is_service_document()) { // Write service document content = writer.write_service_document(m_service_document); } else if (parsed_uri->is_metadata_document()) { // Write metadata document content = writer.write_metadata_document(); } else { if (parsed_uri->path()->size() >= 1) { if (parsed_uri->path()->segment_at(0)->segment_type() == odata_path_segment_type::EntitySet) { auto entity_set_segment = parsed_uri->path()->segment_at(0)->as<odata_entity_set_segment>(); if (entity_set_segment->entity_set()->get_name() == U("People")) { if (parsed_uri->path()->size() == 1) { auto people = get_people(); auto context_url = context_url_builder.get_context_uri_for_collection_of_entities(entity_set_segment->entity_set()); people->set_context_url(context_url); if (is_async) { std::unordered_map<string_t, string_t> headers; headers[U("OData-Version")] = U("4.0"); headers[U("Content-Type")] = U("application/json;odata.metadata=full"); content = writer.write_asynchronous_odata_value(people, 200, U("OK"), headers); } else { content = writer.write_odata_value(people); } } else if (parsed_uri->path()->segment_at(1)->segment_type() == odata_path_segment_type::Key) { auto key_segment = parsed_uri->path()->segment_at(1)->as<odata_key_segment>(); auto key = key_segment->keys()[0].second->as<::odata::utility::string_t>(); auto single_person = get_single_people(key); single_person->set_is_top_level(true); auto context_url = context_url_builder.get_context_uri_for_entity(entity_set_segment->entity_set()); single_person->set_context_url(context_url); auto id = metadata_builder.get_entity_id(single_person, entity_set_segment->entity_set()); single_person->set_id(id); auto read_link = metadata_builder.get_read_link(single_person, entity_set_segment->entity_set()); single_person->set_read_link(read_link); auto edit_link = metadata_builder.get_edit_link(single_person, entity_set_segment->entity_set()); single_person->set_edit_link(edit_link); content = writer.write_odata_value(single_person); } } } } } message.reply(status_codes::OK, content).then(std::bind(&handle_error, std::placeholders::_1)); } catch (::odata::core::odata_exception &e) { message.reply(status_codes::BadRequest, U("Exception: ") + e.what()).then(std::bind(&handle_error, std::placeholders::_1)); } ////Get odata objects from resorce and odata_path // }
// Check if the input text is a number or string. // If string => city name, use bing maps API to obtain the postal code for that city // number => postal code, use google maps API to obtain city name (location data) for that postal code. // then call fetch_data to query different services, aggregate movie, images, events, weather etc for that city and // respond to the request. void CasaLens::get_data(http_request message, const std::wstring& input_text) { if (!is_number(utility::conversions::to_utf8string(input_text))) { std::wstring bing_maps_url(casalens_creds::bmaps_url); uri_builder maps_builder; maps_builder.append_query(U("locality"), input_text); maps_builder.append_query(casalens_creds::bmaps_keyname, casalens_creds::bmaps_key); auto s = maps_builder.to_string(); http_client bing_client(bing_maps_url); bing_client.request(methods::GET, s) .then([=](http_response resp) { return resp.extract_json(); }) .then([=](json::value maps_result) mutable { auto coordinates = maps_result[U("resourceSets")][0][U("resources")][0][U("point")]; auto lattitude = coordinates[U("coordinates")][0].serialize(); auto longitude = coordinates[U("coordinates")][1].serialize(); uri_builder ub; ub.append_path(lattitude + U(",") + longitude) .append_query(casalens_creds::bmaps_keyname, casalens_creds::bmaps_key); auto s2 = ub.to_string(); return bing_client.request(methods::GET, s2); }) .then([](http_response resp) { return resp.extract_json(); }) .then([=](json::value maps_result) { auto postal_code = maps_result[U("resourceSets")][0][U("resources")][0][U("address")][U("postalCode")].as_string(); fetch_data(message, postal_code, input_text); }) .then([=](pplx::task<void> t) { try { t.get(); } catch (...) { message.reply(status_codes::InternalError, U("Failed to fetch the postal code")); } }); } else // get location from postal code { http_client client(casalens_creds::gmaps_url); uri_builder ub; ub.append_query(U("address"), input_text); ub.append_query(U("sensor"), U("false")); client.request(methods::GET, ub.to_string()) .then([](http_response resp) { return resp.extract_json(); }) .then([=](json::value jval) { auto locationstr = jval[U("results")][0][U("address_components")][1][U("long_name")].as_string(); fetch_data(message, input_text, locationstr); }) .then([=](pplx::task<void> t) { try { t.get(); } catch (...) { message.reply(status_codes::InternalError, U("Failed to fetch the location from postal code")); } }); } return; }
void MyListener::handle_post(http_request message) { string resp; json::value jvalue = message.extract_json().get(); if (jvalue.is_null()) message.reply(status_codes::BadRequest, "No json"); else { //utility::stringstream_t stream; std::stringstream stream; jvalue.serialize(stream); boost::property_tree::ptree pt; try { boost::property_tree::read_json(stream, pt); } catch (boost::property_tree::json_parser_error& error) { cout << error.message() << ": " << error.filename() << ", line " << error.line() << endl; } try { string login = pt.get<string>("login"); //// ***** Проверка логина **** for (auto iter = login.begin(); iter != login.end(); ++iter) { if (!(*iter >= 'a' && *iter <= 'z')) resp += "Error in login. Unacceptable symbols\n"; } string password = pt.get<string>("password"); // ***** Проверка пароля ***** if (password.length() < 8) resp += "Error in password. Insufficient password length\n"; for (auto iter = password.begin(); iter != password.end(); ++iter) { //if (!isdigit(*iter) && !isalpha(*iter) && !ispunct(*iter)) if (!(*iter >= 33 && *iter <= 126)) { resp += "Error in password. Unacceptable symbols\n"; } } //resp += login + " " + password; } catch (const boost::property_tree::ptree_bad_data& error) { //cout << error.what() << endl; resp += error.what(); } catch (const boost::property_tree::ptree_bad_path& error) { //cout << error.what() << endl; resp += error.what(); } ////message.reply(status_codes::OK, "Yes json"); //// ***** Проверка логина ***** //if (!jvalue[L"login"].is_null()) //{ // string login = utility::conversions::to_utf8string(jvalue[L"login"].as_string()); // for (auto iter = login.begin(); iter != login.end(); ++iter) // { // if (!(*iter >= 'a' && *iter <= 'z')) // resp += "Error in login. Unacceptable symbols\n"; // } //} //// ***** Проверка пароля ***** //if (!jvalue[L"password"].is_null()) //{ // string password = utility::conversions::to_utf8string(jvalue[L"password"].as_string()); // if (password.length() < 8) // resp += "Error in password. Insufficient password length\n"; // for (auto iter = password.begin(); iter != password.end(); ++iter) // { // //if (!isdigit(*iter) && !isalpha(*iter) && !ispunct(*iter)) // if (!(*iter >= 33 && *iter <= 126)) // { // resp += "Error in password. Unacceptable symbols\n"; // } // } //} if (resp.empty()) resp = "OK"; json::value response = json::value::string(utility::conversions::to_string_t(resp)); message.reply(status_codes::OK, response); //message.reply(status_codes::OK, message.to_string()); } }
void MetaCDNReceiver::handle_update(http_request message) { /* Use cases: 0. when CDN pulls a file from FSS (syncdown flow) 1. when CDN updates an existing file (syncup flow; need invalidation process) 2. when CDN creates a new file and stores in FSS and itself JSON Format Request { "Type": 0, // 0=CDN pulls a file from FSS, 1=CDN updates a file (+invalidation process), 2=CDN creates a new file and stores in FSS "FileName": "a.txt", "FileHash": "ahash", //could be empty string when Type=0 //only for type 1,2 "CdnId": 1 "TimeStamp": "12312312312" //REQUIRED for use case 1 and 2 } Response: status OK or Forbidden (no json object included) */ try { 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()); int result; if(jsonObj.at(U("Type")).as_integer() == 0) { result = m_meta->addCdnToMetaEntry(fileName, cdnId); } else if(jsonObj.at(U("Type")).as_integer() == 1) { string fileHash = utility::conversions::to_utf8string(jsonObj.at(U("FileHash")).as_string()); vector<int> newCdnList; newCdnList.push_back(cdnId); result = m_meta->updateMetaEntry(fileName, fileHash, newCdnList); if(result == 0) { result = m_meta->updateTimeStamp(fileName, jsonObj.at(U("TimeStamp")).as_string()); } else { cout<<"MetaCDNReceiver::handle_update() - failed to update meta entry"<<endl; return; } //now, send invalidation msgs to other cdns unordered_map<int, Address>::const_iterator itr = m_meta->getCdnIdToAddrMap().begin(); while(itr != m_meta->getCdnIdToAddrMap().end()) { if(itr->first == cdnId) { ++itr; continue; } http_client cdn_client = http_client("http://" + itr->second.ipAddr); http_response resp = cdn_client.request(methods::DEL, "cdn/cache"+fileName).get(); if (resp.status_code() != status_codes::OK) { cout<<"MetaCDNReceiver::handle_update() - failed to send invalidation message to "+itr->second.ipAddr<<endl; } ++itr; } } else if(jsonObj.at(U("Type")).as_integer() == 2) { string fileHash = utility::conversions::to_utf8string(jsonObj.at(U("FileHash")).as_string()); vector<int> newCdnList; newCdnList.push_back(cdnId); result = m_meta->addNewMetaEntry(fileName, fileHash, newCdnList); if(result == 0) result = m_meta->addNewTimeStamp(fileName, jsonObj.at(U("TimeStamp")).as_string()); } else { message.reply(status_codes::Forbidden, U("Undefined Type")); return; } message.reply(result==0? status_codes::OK : status_codes::NotFound, result==0? U("Updated successfully") : U("Update 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; } }
void details::http_listener_impl::handle_trace(http_request message) { utility::string_t data = message.to_string(); message.reply(status_codes::OK, data, U("message/http")); }
void details::http_listener_impl::handle_options(http_request message) { http_response response(status_codes::OK); response.headers().add(U("Allow"), get_supported_methods()); message.reply(response); }
void RestEngineUri::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()}; uri req_uri = request.absolute_uri(); std::map<utility::string_t, utility::string_t> qmap = req_uri.split_query(req_uri.query()); for (auto& kv : qmap) { if (kv.first == "output_folder_root" || kv.first == "test_name") { std::cout << kv.first << " = " << kv.second << std::endl; // Execute Ivy Engine command if (rc == 0) { std::unique_lock<std::mutex> u_lk(goStatementMutex); if (kv.first == "output_folder_root") m_s.outputFolderRoot = kv.second; if (kv.first == "test_name") m_s.testName = kv.second; http_response response(status_codes::OK); make_response(response, resultstr, result); request.reply(response); return; } } } 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 step = document.FindMember("stepname"); rapidjson::Value::MemberIterator warmup = document.FindMember("warmup_seconds"); rapidjson::Value::MemberIterator measure_seconds = document.FindMember("measure_seconds"); rapidjson::Value::MemberIterator subinterval = document.FindMember("subinterval_seconds"); rapidjson::Value::MemberIterator measure = document.FindMember("measure"); rapidjson::Value::MemberIterator accuracy = document.FindMember("accuracy_plus_minus"); rapidjson::Value::MemberIterator timeout_seconds = document.FindMember("timeout_seconds"); rapidjson::Value::MemberIterator max_wp = document.FindMember("max_wp"); rapidjson::Value::MemberIterator min_wp = document.FindMember("min_wp"); rapidjson::Value::MemberIterator max_wp_change = document.FindMember("max_wp_change"); rapidjson::Value::MemberIterator dfc = document.FindMember("dfc"); rapidjson::Value::MemberIterator low_IOPS = document.FindMember("low_IOPS"); rapidjson::Value::MemberIterator low_target = document.FindMember("low_target"); rapidjson::Value::MemberIterator high_IOPS = document.FindMember("high_IOPS"); rapidjson::Value::MemberIterator high_target = document.FindMember("high_target"); rapidjson::Value::MemberIterator target_value = document.FindMember("target_value"); std::ostringstream parameters; parameters << "stepname=\"" << step->value.GetString() << "\""; if (warmup != document.MemberEnd()) parameters << ", warmup_seconds=" << warmup->value.GetInt(); if (measure_seconds != document.MemberEnd()) parameters << ", measure_seconds=" << measure_seconds->value.GetInt(); if (subinterval != document.MemberEnd()) parameters << ", subinterval_seconds=" << subinterval->value.GetInt(); if (measure != document.MemberEnd()) parameters << ", measure=" << measure->value.GetString(); if (accuracy != document.MemberEnd()) parameters << ", accuracy_plus_minus=\"" << accuracy->value.GetString() << "\""; if (timeout_seconds != document.MemberEnd()) { if (timeout_seconds->value.IsString()) parameters << ", timeout_seconds=\"" << timeout_seconds->value.GetString() << "\""; else parameters << ", timeout_seconds=\"" << timeout_seconds->value.GetInt() << "\""; } if (max_wp != document.MemberEnd()) parameters << ", max_wp=\"" << max_wp->value.GetString() << "\""; if (min_wp != document.MemberEnd()) parameters << ", min_wp=\"" << min_wp->value.GetString() << "\""; if (max_wp_change != document.MemberEnd()) parameters << ", max_wp_change=\"" << max_wp_change->value.GetString() << "\""; if (dfc != document.MemberEnd()) parameters << ", dfc=" << dfc->value.GetString(); if (low_IOPS != document.MemberEnd()) parameters << ", low_IOPS=\"" << low_IOPS->value.GetString() << "\""; if (low_target != document.MemberEnd()) parameters << ", low_target=\"" << low_target->value.GetString() << "\""; if (high_IOPS != document.MemberEnd()) parameters << ", high_IOPS=\"" << high_IOPS->value.GetString() << "\""; if (high_target != document.MemberEnd()) parameters << ", high_target=\"" << high_target->value.GetString() << "\""; if (target_value != document.MemberEnd()) parameters << ", target_value=\"" << target_value->value.GetString() << "\""; // Execute Ivy Engine command if (rc == 0) { std::unique_lock<std::mutex> u_lk(goStatementMutex); result = m_s.go(parameters.str()); } //resultstr += (result.first ? "Successful" : "Failed"); //resultstr += " Reason: "; //resultstr += result.second; http_response response(status_codes::OK); make_response(response, resultstr, result); request.reply(response); }