int name_value_collection___index(lua_State *L) { NameValueCollection *collection = GetCollection(L, 1); const char *name = luaL_checkstring(L, 2); if (strcmp(name, "Count") == 0) { lua_pushunsigned(L, collection->GetCount()); } else if (strcmp(name, "AllKeys") == 0) { StringVectorToLuaArray(L, collection->AllKeys()); } else if (strcmp(name, "Add") == 0) { lua_pushlightuserdata(L, (void *)collection); lua_pushcclosure(L, name_value_collection_Add, 1); } else if (strcmp(name, "Get") == 0) { lua_pushlightuserdata(L, (void *)collection); lua_pushcclosure(L, name_value_collection_Get, 1); } else if (strcmp(name, "GetKey") == 0) { lua_pushlightuserdata(L, (void *)collection); lua_pushcclosure(L, name_value_collection_GetKey, 1); } else if (strcmp(name, "GetValues") == 0) { lua_pushlightuserdata(L, (void *)collection); lua_pushcclosure(L, name_value_collection_GetValues, 1); } else if (strcmp(name, "Clear") == 0) { lua_pushlightuserdata(L, (void *)collection); lua_pushcclosure(L, name_value_collection_Clear, 1); } else if (strcmp(name, "Set") == 0) { lua_pushlightuserdata(L, (void *)collection); lua_pushcclosure(L, name_value_collection_Set, 1); } else if (strcmp(name, "Remove") == 0) { lua_pushlightuserdata(L, (void *)collection); lua_pushcclosure(L, name_value_collection_Remove, 1); } else { lua_pushstring(L, "Unknown property or method."); lua_error(L); } return 1; }
/// private methods implementation void BatchFilter::validateProperties( NameValueCollection& transportHeaders ) { if ( !m_Properties.ContainsKey( BatchFilter::BatchFILE ) ) throw invalid_argument( "Required parameter missing : BatchFILE" ); //Set Parameters for BatchFile int xlstParamsCount = transportHeaders.getCount(); if ( xlstParamsCount > 0 ) { DEBUG( "The Batch has " << xlstParamsCount << " parameters." ); vector< DictionaryEntry > params = transportHeaders.getData(); for( int i = 0; i < xlstParamsCount; i++ ) { if ( StringUtil::StartsWith( params[i].first, BatchFilter::BatchPARAM ) ) { DEBUG( "Filter param [" << params[i].first << "] value is [" << params[i].second << "]" ); getTransformer()->setStylesheetParam( params[i].first.data(), params[i].second.data() ); } else if ( ( params[i].first == BatchFilter::BatchUSEEXT ) && !m_ExtensionsInstalled ) { DEBUG( "Using extension functions from http://extensions.bisnet.ro" ); const XalanDOMString theNamespace( "http://extensions.bisnet.ro" ); getTransformer()->installExternalFunction( theNamespace, XalanDOMString( "replace" ), FunctionReplace() ); getTransformer()->installExternalFunction( theNamespace, XalanDOMString( "fill" ), FunctionFill() ); m_ExtensionsInstalled = true; } } } else DEBUG( "The Batch doesn't have parameters" ); }
void fetchAccountPage(HTTPSClientSession& clientSession, NameValueCollection& cookies) { HTTPRequest request(HTTPRequest::HTTP_GET, "/royalgreenwich/account", HTTPMessage::HTTP_1_1); request.setCookies(cookies); HTTPResponse response; std::ostream& ostr = clientSession.sendRequest(request); std::istream& rs = clientSession.receiveResponse(response); int statusCode = response.getStatus(); poco_information_f1(logger(), "Status %d", statusCode); std::vector<HTTPCookie> newCookies; response.getCookies(newCookies); for (HTTPCookie cookie : newCookies) { poco_information_f1(logger(), "Cookie %s", cookie.toString()); if (cookies.has(cookie.getName())) { cookies.set(cookie.getName(), cookie.getValue()); } else { cookies.add(cookie.getName(), cookie.getValue()); } } StreamCopier::copyStream(rs, std::cout); }
void BatchFilter::replyOutputFormat( NameValueCollection& transportHeaders, int format ) { XALAN_USING_XALAN( FormatterListener ); string formatAsString = ""; switch( format ) { case FormatterListener::OUTPUT_METHOD_TEXT : formatAsString = BatchFilter::OUTPUT_METHOD_TEXT; break; case FormatterListener::OUTPUT_METHOD_XML : case FormatterListener::OUTPUT_METHOD_DOM : formatAsString = BatchFilter::OUTPUT_METHOD_XML; break; default : formatAsString = BatchFilter::OUTPUT_METHOD_NONE; break; } if ( transportHeaders.ContainsKey( BatchOUTPUTFORMAT ) ) transportHeaders[ BatchOUTPUTFORMAT ] = formatAsString; else transportHeaders.Add( BatchOUTPUTFORMAT, formatAsString ); }
//------------------------------------------------------------------------------ void ofxHTTPBaseRequest::addFormFields(const NameValueCollection& formFields) { NameValueCollection::ConstIterator iter = formFields.begin(); while(iter != formFields.end()) { addFormField((*iter).first,(*iter).second); ++iter; } }
//------------------------------------------------------------------------------ void ofxHTTPBaseRequest::addHeaders(const NameValueCollection& _headers) { NameValueCollection::ConstIterator iter = _headers.begin(); while(iter != _headers.end()) { addHeader((*iter).first,(*iter).second); ++iter; } }
void fetchLoginPage(HTTPSClientSession& clientSession, NameValueCollection& cookies) { HTTPRequest request(HTTPRequest::HTTP_GET, "/royalgreenwich/login?message=borrowerservices_notloggedin&referer=https%3A%2F%2Fcapitadiscovery.co.uk%2Froyalgreenwich%2Faccount", HTTPMessage::HTTP_1_1); request.setCookies(cookies); HTTPResponse response; std::ostream& ostr = clientSession.sendRequest(request); std::istream& rs = clientSession.receiveResponse(response); int statusCode = response.getStatus(); poco_information_f1(logger(), "Status %d", statusCode); std::vector<HTTPCookie> newCookies; response.getCookies(newCookies); for (HTTPCookie cookie : newCookies) { poco_information_f1(logger(), "Cookie %s", cookie.toString()); if (cookies.has(cookie.getName())) { cookies.set(cookie.getName(), cookie.getValue()); } else { cookies.add(cookie.getName(), cookie.getValue()); } } }
void submitLoginPage(HTTPSClientSession& clientSession, NameValueCollection& cookies) { HTTPRequest request(HTTPRequest::HTTP_POST, "/royalgreenwich/sessions", HTTPMessage::HTTP_1_1); request.setCookies(cookies); HTTPResponse response; HTMLForm loginForm; loginForm.add("barcode", "28028005913354"); loginForm.add("pin", "3347"); loginForm.prepareSubmit(request); std::ostream& ostr = clientSession.sendRequest(request); loginForm.write(ostr); std::istream& rs = clientSession.receiveResponse(response); int statusCode = response.getStatus(); poco_information_f1(logger(), "Status %d", statusCode); std::vector<HTTPCookie> newCookies; response.getCookies(newCookies); for (HTTPCookie cookie : newCookies) { poco_information_f1(logger(), "Cookie %s", cookie.toString()); if (cookies.has(cookie.getName())) { cookies.set(cookie.getName(), cookie.getValue()); } else { cookies.add(cookie.getName(), cookie.getValue()); } } }
int name_value_collection_GetKey(lua_State *L) { NameValueCollection *collection = GetCollection(L, lua_upvalueindex(1)); lua_Unsigned index = luaL_checkunsigned(L, 1); std::string key; if (collection->GetKey(index, &key)) lua_pushlstring(L, key.data(), key.length()); else lua_pushnil(L); return 1; }
int name_value_collection_Add(lua_State *L) { NameValueCollection *collection = GetCollection(L, lua_upvalueindex(1)); // TODO: permit nil const char *name = luaL_checkstring(L, 1); const char *value = luaL_checkstring(L, 2); lua_pushboolean(L, collection->Add(name, value)); return 1; }
std::string WebSessionManager::getId(const std::string& appName, const Poco::Net::HTTPServerRequest& request) { std::string id; std::string name(cookieName(appName)); NameValueCollection cookies; request.getCookies(cookies); NameValueCollection::ConstIterator it = cookies.find(name); if (it != cookies.end()) id = it->second; return id; }
void HTTPRequest::setCookies(const NameValueCollection& cookies) { std::string cookie; cookie.reserve(64); for (NameValueCollection::ConstIterator it = cookies.begin(); it != cookies.end(); ++it) { if (it != cookies.begin()) cookie.append("; "); cookie.append(it->first); cookie.append("="); cookie.append(it->second); } add(COOKIE, cookie); }
HTTPCookie::HTTPCookie(const NameValueCollection& nvc): _version(0), _secure(false), _maxAge(-1), _httpOnly(false) { for (NameValueCollection::ConstIterator it = nvc.begin(); it != nvc.end(); ++it) { const std::string& name = it->first; const std::string& value = it->second; if (icompare(name, "comment") == 0) { setComment(value); } else if (icompare(name, "domain") == 0) { setDomain(value); } else if (icompare(name, "path") == 0) { setPath(value); } else if (icompare(name, "max-age") == 0) { setMaxAge(NumberParser::parse(value)); } else if (icompare(name, "secure") == 0) { setSecure(true); } else if (icompare(name, "expires") == 0) { int tzd; DateTime exp = DateTimeParser::parse(value, tzd); Timestamp now; setMaxAge((int) ((exp.timestamp() - now) / Timestamp::resolution())); } else if (icompare(name, "version") == 0) { setVersion(NumberParser::parse(value)); } else if (icompare(name, "HttpOnly") == 0) { setHttpOnly(true); } else { setName(name); setValue(value); } } }
//------------------------------------------------------------------------------ bool ofxWebServerBaseRouteHandler::isValidRequest(const Settings& settings, HTTPServerRequest& request, HTTPServerResponse& response) { string sessionId = ""; // extract cookie from request NameValueCollection cookies; request.getCookies(cookies); NameValueCollection::ConstIterator it = cookies.find(settings.sessionCookieName); if (it != cookies.end()) { sessionId = it->second; } else { sessionId = ofxWebServerSessionManager::generateSessionKey(request); HTTPCookie cookie(settings.sessionCookieName,sessionId); cookie.setPath("/"); // set no age, so it expires @ end of session response.addCookie(cookie); } // TODO: update session manager URI uri(request.getURI()); const string path = uri.getPath(); // just get the path if(settings.requireAuthentication) { if(request.hasCredentials()) { HTTPBasicCredentials credentials(request); const string& user = credentials.getUsername(); const string& pwd = credentials.getPassword(); if(settings.username == credentials.getUsername() && settings.password == credentials.getPassword()) { // add an authentication cookie? return true; } else { response.setStatusAndReason(HTTPResponse::HTTP_UNAUTHORIZED); sendErrorResponse(response); return false; } } else { response.requireAuthentication(settings.realm); response.setContentLength(0); response.send(); return false; } } else { return true; } }
TEST(MessageHeader, testSplitParameters) { std::string s; std::string v; NameValueCollection p; MessageHeader::splitParameters(s, v, p); EXPECT_TRUE (v.empty()); EXPECT_TRUE (p.empty()); s = "multipart/related"; MessageHeader::splitParameters(s, v, p); EXPECT_TRUE (v == "multipart/related"); EXPECT_TRUE (p.empty()); s = "multipart/related; boundary=MIME_boundary_01234567"; MessageHeader::splitParameters(s, v, p); EXPECT_TRUE (v == "multipart/related"); EXPECT_TRUE (p.size() == 1); EXPECT_TRUE (p["boundary"] == "MIME_boundary_01234567"); s = "multipart/related; boundary=\"MIME_boundary_76543210\""; MessageHeader::splitParameters(s, v, p); EXPECT_TRUE (v == "multipart/related"); EXPECT_TRUE (p.size() == 1); EXPECT_TRUE (p["boundary"] == "MIME_boundary_76543210"); s = "text/plain; charset=us-ascii"; MessageHeader::splitParameters(s, v, p); EXPECT_TRUE (v == "text/plain"); EXPECT_TRUE (p.size() == 1); EXPECT_TRUE (p["charset"] == "us-ascii"); s = "value; p1=foo; p2=bar"; MessageHeader::splitParameters(s, v, p); EXPECT_TRUE (v == "value"); EXPECT_TRUE (p.size() == 2); EXPECT_TRUE (p["p1"] == "foo"); EXPECT_TRUE (p["p2"] == "bar"); s = "value; p1=\"foo; bar\""; MessageHeader::splitParameters(s, v, p); EXPECT_TRUE (v == "value"); EXPECT_TRUE (p.size() == 1); EXPECT_TRUE (p["p1"] == "foo; bar"); s = "value ; p1=foo ; p2=bar "; MessageHeader::splitParameters(s, v, p); EXPECT_TRUE (v == "value"); EXPECT_TRUE (p.size() == 2); EXPECT_TRUE (p["p1"] == "foo"); EXPECT_TRUE (p["p2"] == "bar"); }
void handlePart(const MessageHeader& header, std::istream& stream) { _type = header.get("Content-Type", "(unspecified)"); if (header.has("Content-Disposition")) { std::string disp; NameValueCollection params; MessageHeader::splitParameters(header["Content-Disposition"], disp, params); _name = params.get("name", "(unnamed)"); _fileName = params.get("filename", "(unnamed)"); } CountingInputStream istr(stream); NullOutputStream ostr; StreamCopier::copyStream(istr, ostr); _length = istr.chars(); }
void AppSettings::ReadSettings(string iniFile) { NameValueCollection settings = ReadIniSection(Name.c_str(), iniFile.c_str()); // expand indirect values first for (NameValueCollection::iterator itr = settings.begin(), end = settings.end(); itr != end; ++itr) itr->second = GetIndirectValue(itr->second.c_str()); // next expand qualifiers for (NameValueCollection::iterator itr = settings.begin(), end = settings.end(); itr != end; ++itr) itr->second = ExpandQualifiers(itr->second.c_str(), settings); // finally expand environment variables, last because it clobbers my custom qualifier expansion for (NameValueCollection::iterator itr = settings.begin(), end = settings.end(); itr != end; ++itr) itr->second = ExpandEnvironment(itr->second); std::swap(Environment, settings); rootPath = GetSetting<string>("RootPath"); rootPaths = TokenizeString(GetSetting<string>("RootPaths").c_str(), ";"); searchPaths = TokenizeString(GetSetting<string>("TextureSearchPaths").c_str(), ";"); extensions = TokenizeString(GetSetting<string>("TextureExtensions").c_str(), ";"); textureRootPaths = TokenizeString(GetSetting<string>("TextureRootPaths").c_str(), ";"); Skeleton = GetSetting<string>("Skeleton"); useSkeleton = GetSetting<bool>("UseSkeleton", useSkeleton); goToSkeletonBindPosition = GetSetting<bool>("GoToSkeletonBindPosition", goToSkeletonBindPosition); disableCreateNubsForBones = GetSetting<bool>("DisableCreateNubsForBones", disableCreateNubsForBones); applyOverallTransformToSkinAndBones = GetSetting<int>("ApplyOverallTransformToSkinAndBones", -1); dummyNodeMatches = TokenizeString(GetSetting<string>("DummyNodeMatches").c_str(), ";"); }
HTTPCookie::HTTPCookie(const NameValueCollection& nvc): _version(0), _secure(false), _maxAge(-1), _httpOnly(false) { for (NameValueCollection::ConstIterator it = nvc.begin(); it != nvc.end(); ++it) { const std::string& name = it->first; const std::string& value = it->second; if (icompare(name, "comment") == 0) { setComment(value); } else if (icompare(name, "domain") == 0) { setDomain(value); } else if (icompare(name, "path") == 0) { setPath(value); } else if (icompare(name, "priority") == 0) { setPriority(value); } else if (icompare(name, "max-age") == 0) { throw NotImplementedException("HTTPCookie::HTTPCookie max-age"); } else if (icompare(name, "secure") == 0) { setSecure(true); } else if (icompare(name, "expires") == 0) { throw NotImplementedException("HTTPCookie::HTTPCookie expires"); } else if (icompare(name, "version") == 0) { throw NotImplementedException("HTTPCookie::HTTPCookie version"); } else if (icompare(name, "HttpOnly") == 0) { setHttpOnly(true); } else { setName(name); setValue(value); } } }
void HTMLForm::readMultipart(std::istream& istr, PartHandler& handler) { static const int eof = std::char_traits<char>::eof(); int fields = 0; MultipartReader reader(istr, _boundary); while (reader.hasNextPart()) { if (_fieldLimit > 0 && fields == _fieldLimit) throw HTMLFormException("Too many form fields"); MessageHeader header; reader.nextPart(header); std::string disp; NameValueCollection params; if (header.has("Content-Disposition")) { std::string cd = header.get("Content-Disposition"); MessageHeader::splitParameters(cd, disp, params); } if (params.has("filename")) { handler.handlePart(header, reader.stream()); // Ensure that the complete part has been read. while (reader.stream().good()) reader.stream().get(); } else { std::string name = params["name"]; std::string value; std::istream& istr = reader.stream(); int ch = istr.get(); while (ch != eof) { value += (char) ch; ch = istr.get(); } add(name, value); } ++fields; } }
int name_value_collection_Get(lua_State *L) { NameValueCollection *collection = GetCollection(L, lua_upvalueindex(1)); // TODO: permit nil if (lua_type(L, 1) == LUA_TNUMBER) { lua_Unsigned index = luaL_checkunsigned(L, 1); std::string value; if (collection->Get(index, &value)) lua_pushlstring(L, value.data(), value.length()); else lua_pushnil(L); } else { const char *name = luaL_checkstring(L, 1); std::string value; if (collection->Get(name, &value)) lua_pushlstring(L, value.data(), value.length()); else lua_pushnil(L); } return 1; }
void MessageHeader::splitParameters(const std::string& s, std::string& value, NameValueCollection& parameters) { value.clear(); parameters.clear(); std::string::const_iterator it = s.begin(); std::string::const_iterator end = s.end(); while (it != end && Poco::Ascii::isSpace(*it)) ++it; while (it != end && *it != ';') value += *it++; Poco::trimRightInPlace(value); if (it != end) ++it; splitParameters(it, end, parameters); }
int name_value_collection_GetValues(lua_State *L) { NameValueCollection *collection = GetCollection(L, lua_upvalueindex(1)); const NameValueCollection::value_list_type *values; // TODO: permit nil if (lua_type(L, 1) == LUA_TNUMBER) { lua_Unsigned index = luaL_checkunsigned(L, 1); if (collection->GetValues(index, &values)) StringVectorToLuaArray(L, *values); else lua_pushnil(L); } else { luaL_checktype(L, 1, LUA_TSTRING); const char *name = luaL_checkstring(L, 1); if (collection->GetValues(name, &values)) StringVectorToLuaArray(L, *values); else lua_pushnil(L); } return 1; }
void EventsWatcherDbOp::SetConfigCfgSection( const NameValueCollection& cfgSection ) { if ( cfgSection.ContainsKey( "provider" ) ) { string provider = cfgSection[ "provider" ]; // create a provider if necessary if ( m_DatabaseProvider == NULL ) m_DatabaseProvider = DatabaseProvider::GetFactory( provider ); } m_ConfigConnectionString.setDatabaseName( cfgSection[ "database" ] ); m_ConfigConnectionString.setUserName( cfgSection[ "user" ] ); m_ConfigConnectionString.setUserPassword( cfgSection[ "password" ] ); }
void MessageHeader::splitParameters(const std::string::const_iterator& begin, const std::string::const_iterator& end, NameValueCollection& parameters) { std::string pname; std::string pvalue; pname.reserve(32); pvalue.reserve(64); std::string::const_iterator it = begin; while (it != end) { pname.clear(); pvalue.clear(); while (it != end && Poco::Ascii::isSpace(*it)) ++it; while (it != end && *it != '=' && *it != ';') pname += *it++; Poco::trimRightInPlace(pname); if (it != end && *it != ';') ++it; while (it != end && Poco::Ascii::isSpace(*it)) ++it; while (it != end && *it != ';') { if (*it == '"') { ++it; while (it != end && *it != '"') { if (*it == '\\') { ++it; if (it != end) pvalue += *it++; } else pvalue += *it++; } if (it != end) ++it; } else if (*it == '\\') { ++it; if (it != end) pvalue += *it++; } else pvalue += *it++; } Poco::trimRightInPlace(pvalue); if (!pname.empty()) parameters.add(pname, pvalue); if (it != end) ++it; } }
void AppSettings::ReadSettings(tstring iniFile) { NameValueCollection settings = ReadIniSection(Name.c_str(), iniFile.c_str()); // expand indirect values first for (NameValueCollection::iterator itr = settings.begin(), end = settings.end(); itr != end; ++itr) itr->second = GetIndirectValue(itr->second.c_str()); // next expand qualifiers for (NameValueCollection::iterator itr = settings.begin(), end = settings.end(); itr != end; ++itr) itr->second = ExpandQualifiers(itr->second.c_str(), settings); // finally expand environment variables, last because it clobbers my custom qualifier expansion for (NameValueCollection::iterator itr = settings.begin(), end = settings.end(); itr != end; ++itr) itr->second = ExpandEnvironment(itr->second); std::swap(Environment, settings); NiVersion = GetSetting<tstring>(TEXT("NiVersion"), TEXT("20.0.0.5")); NiUserVersion = GetSetting<int>(TEXT("NiUserVersion"), 0); NiUserVersion2 = GetSetting<int>(TEXT("NiUserVersion2"), 0); rootPath = GetSetting<tstring>(TEXT("RootPath")); rootPaths = TokenizeString(GetSetting<tstring>(TEXT("RootPaths")).c_str(), TEXT(";")); searchPaths = TokenizeString(GetSetting<tstring>(TEXT("TextureSearchPaths")).c_str(), TEXT(";")); extensions = TokenizeString(GetSetting<tstring>(TEXT("TextureExtensions")).c_str(), TEXT(";")); textureRootPaths = TokenizeString(GetSetting<tstring>(TEXT("TextureRootPaths")).c_str(), TEXT(";")); materialRootPaths = TokenizeString(GetSetting<tstring>(TEXT("MaterialPaths")).c_str(), TEXT(";")); Skeleton = GetSetting<tstring>(TEXT("Skeleton")); useSkeleton = GetSetting<bool>(TEXT("UseSkeleton"), useSkeleton); skeletonSearchPaths = TokenizeString(GetSetting<tstring>(TEXT("SkeletonSearchPaths"), TEXT(".")).c_str(), TEXT(";")); goToSkeletonBindPosition = GetSetting<bool>(TEXT("GoToSkeletonBindPosition"), goToSkeletonBindPosition); disableCreateNubsForBones = GetSetting<bool>(TEXT("DisableCreateNubsForBones"), disableCreateNubsForBones); applyOverallTransformToSkinAndBones = GetSetting<int>(TEXT("ApplyOverallTransformToSkinAndBones"), -1); textureUseFullPath = GetSetting<int>(TEXT("TextureUseFullPath"), textureUseFullPath); dummyNodeMatches = TokenizeString(GetSetting<tstring>(TEXT("DummyNodeMatches")).c_str(), TEXT(";")); rotate90Degrees = TokenizeString(GetSetting<tstring>(TEXT("Rotate90Degrees")).c_str(), TEXT(";")); supportPrnStrings = GetSetting<bool>(TEXT("SupportPrnStrings"), supportPrnStrings); doNotReuseExistingBones = GetSetting<bool>(TEXT("DoNotReuseExistingBones"), doNotReuseExistingBones); skeletonCheck = GetSetting<tstring>(TEXT("SkeletonCheck")); }
// ---------------------------------------------------------------------- ofxHttpResponse ofxHttpUtils::getUrl(string url){ ofxHttpResponse response; try{ URI uri(url.c_str()); std::string path(uri.getPathAndQuery()); if (path.empty()) path = "/"; HTTPRequest req(HTTPRequest::HTTP_GET, path, HTTPMessage::HTTP_1_1); if(auth.getUsername()!="") auth.authenticate(req); if(sendCookies){ for(unsigned i=0; i<cookies.size(); i++){ NameValueCollection reqCookies; reqCookies.add(cookies[i].getName(),cookies[i].getValue()); req.setCookies(reqCookies); } } HTTPResponse res; ofPtr<HTTPSession> session; istream * rs; if(uri.getScheme()=="https"){ HTTPSClientSession * httpsSession = new HTTPSClientSession(uri.getHost(), uri.getPort());//,context); httpsSession->setTimeout(Poco::Timespan(timeoutSeconds,0)); httpsSession->sendRequest(req); rs = &httpsSession->receiveResponse(res); session = ofPtr<HTTPSession>(httpsSession); }else{ HTTPClientSession * httpSession = new HTTPClientSession(uri.getHost(), uri.getPort()); httpSession->setTimeout(Poco::Timespan(timeoutSeconds,0)); httpSession->sendRequest(req); rs = &httpSession->receiveResponse(res); session = ofPtr<HTTPSession>(httpSession); } response=ofxHttpResponse(res, *rs, url); if(sendCookies){ cookies.insert(cookies.begin(),response.cookies.begin(),response.cookies.end()); } if(response.status>=300 && response.status<400){ Poco::URI uri(req.getURI()); uri.resolve(res.get("Location")); response.location = uri.toString(); } ofNotifyEvent( newResponseEvent, response, this ); //std::cout << res.getStatus() << " " << res.getReason() << std::endl; //StreamCopier::copyStream(rs, std::cout); }catch (Exception& exc){ ofLogError("ofxHttpUtils") << exc.displayText(); response.status = -1; response.reasonForStatus = exc.displayText(); ofNotifyEvent(newResponseEvent, response, this); } return response; }
//------------------------------------------------------------------------------ HTTPRequestHandler* ofxIpVideoServerRoute::createRequestHandler(const HTTPServerRequest& request) { URI uri(request.getURI()); if(ofxIpVideoServerRouteHandler::matchRoute(uri,settings.route)) { ofxIpVideoServerFrame::Settings targetSettings; string query = uri.getQuery(); NameValueCollection queryMap = ofGetQueryMap(uri); if(queryMap.has("vflip")) { string vflip = queryMap.get("vflip"); targetSettings.bFlipVertical = icompare(vflip,"1") == 0 || icompare(vflip,"true") == 0 || icompare(vflip,"t") == 0 || icompare(vflip,"y") == 0 || icompare(vflip,"yes") == 0; } if(queryMap.has("hflip")) { string hflip = queryMap.get("hflip"); targetSettings.bFlipHorizontal = icompare(hflip,"1") == 0 || icompare(hflip,"true") == 0 || icompare(hflip,"t") == 0 || icompare(hflip,"y") == 0 || icompare(hflip,"yes") == 0; } if(queryMap.has("size")) { string size = queryMap.get("size"); toLowerInPlace(size); vector<string> tokens = ofSplitString(size,"x"); if(tokens.size() == 2) { int width = ofToInt(tokens[0]); int height = ofToInt(tokens[1]); if(width > 0 && height > 0) { width = MIN(width,MAX_VIDEO_DIM); height = MIN(height,MAX_VIDEO_DIM); targetSettings.width = width; targetSettings.height = height; } } } if(queryMap.has("quality")) { string quality = queryMap.get("quality"); if(icompare(quality,"best")) { targetSettings.quality = OF_IMAGE_QUALITY_BEST; } else if(icompare(quality,"high")) { targetSettings.quality = OF_IMAGE_QUALITY_HIGH; } else if(icompare(quality,"medium")) { targetSettings.quality = OF_IMAGE_QUALITY_MEDIUM; } else if(icompare(quality,"low")) { targetSettings.quality = OF_IMAGE_QUALITY_LOW; } else if(icompare(quality,"worst")) { targetSettings.quality = OF_IMAGE_QUALITY_WORST; } else { // no change } } ofxIpVideoServerFrameQueue* queue = new ofxIpVideoServerFrameQueue(targetSettings); queues.push_back(queue); return new ofxIpVideoServerRouteHandler(settings,*queue); } else { return NULL; } }
void run() { Stopwatch sw; std::vector<HTTPCookie> cookies; for (int i = 0; i < _repetitions; ++i) { try { int usec = 0; std::string path(_uri.getPathAndQuery()); if (path.empty()) path = "/"; HTTPClientSession session(_uri.getHost(), _uri.getPort()); HTTPRequest req(HTTPRequest::HTTP_GET, path, HTTPMessage::HTTP_1_1); if (_cookies) { NameValueCollection nvc; std::vector<HTTPCookie>::iterator it = cookies.begin(); for(; it != cookies.end(); ++it) nvc.add((*it).getName(), (*it).getValue()); req.setCookies(nvc); } HTTPResponse res; sw.restart(); session.sendRequest(req); std::istream& rs = session.receiveResponse(res); NullOutputStream nos; StreamCopier::copyStream(rs, nos); sw.stop(); _success += HTTPResponse::HTTP_OK == res.getStatus() ? 1 : 0; if (_cookies) res.getCookies(cookies); usec = int(sw.elapsed()); if (_verbose) { FastMutex::ScopedLock lock(_mutex); std::cout << _uri.toString() << ' ' << res.getStatus() << ' ' << res.getReason() << ' ' << usec/1000.0 << "ms" << std::endl; } _usec += usec; } catch (Exception& exc) { FastMutex::ScopedLock lock(_mutex); std::cerr << exc.displayText() << std::endl; } } { FastMutex::ScopedLock lock(_mutex); _gSuccess += _success; _gUsec += _usec; } if (_verbose) printStats(_uri.toString(), _repetitions, _success, _usec); }
//------------------------------------------------------------------------------ void ofxWebServerUploadRouteHandler::handlePart(const MessageHeader& header, std::istream& stream) { NameValueCollection::ConstIterator iter = header.begin(); // while(iter != header.end()) { // cout << (*iter).first << "=" << (*iter).second << endl; // ++iter; // } // if(header.has("Content-Type")) { string contentType = header["Content-Type"]; if(!isContentTypeValid(contentType)) { ofLogError("ofxWebServerUploadRouteHandler::handlePart") << "Invalid content type: " << contentType; return; // reject } } else { ofLogError("ofxWebServerUploadRouteHandler::handlePart") << "No Content-Type header."; return; } // is this an uploaded file? if(header.has("Content-Disposition")) {// && header.has("form-data")) { string contentDisposition = header["Content-Disposition"]; NameValueCollection parameters; MessageHeader::splitParameters(contentDisposition.begin(),contentDisposition.end(),parameters); if(parameters.has("filename")) { try { ofFile file(settings.uploadFolder + "/" + parameters["filename"], ofFile::WriteOnly); cout << file.getAbsolutePath() << endl; streamsize sz = StreamCopier::copyStream(stream,file); // The section below is from StreamCopier::copyStream, // and can be used for upload progress feedback // int bufferSize = 8192; // Buffer<char> buffer(bufferSize); // streamsize len = 0; // stream.read(buffer.begin(), bufferSize); // streamsize n = stream.gcount(); // while (n > 0) { // len += n; // file.write(buffer.begin(), n); // if (stream && file) { // stream.read(buffer.begin(), bufferSize); // n = stream.gcount(); // cout << n << endl; // } // else n = 0; // } file.close(); } catch(const Exception& exc) { ofLogError("ofxWebServerUploadRouteHandler::handlePart") << exc.displayText(); } catch(const exception& exc) { ofLogError("ofxWebServerUploadRouteHandler::handlePart") << exc.what(); } catch(...) { ofLogError("ofxWebServerUploadRouteHandler::handlePart") << "Uncaught thread exception: Unknown exception."; } } else { // error } } }
void handleRequest(HTTPServerRequest& request, HTTPServerResponse& response) { HTMLForm form(request, request.stream()); response.setContentType("text/html"); response.setChunkedTransferEncoding(true); std::ostream& ostr = response.send(); URI requestURI(request.getURI()); ostr << "<html><head><title>Echo HTTP Headers and HTML Form Information</title>" "<link rel=\"stylesheet\" href=\"css/styles.css\" type=\"text/css\"/></head><body>" "<div class=\"header\">" "<h1 class=\"category\">Open Service Platform</h1>" "<h1 class=\"title\">Echo HTTP Headers and HTML Form Information</H1>" "</div>" "<div class=\"body\">"; // echo the items available by method ostr << "<h2>Request</h2>" << "<ul>" << "<li><b>Method:</b> " << request.getMethod() << "</li>" << "<li><b>URI Path:</b> " << requestURI.getPath() << "</li>" << "<li><b>URI Query:</b> " << requestURI.getQuery() << "</li>" << "<li><b>HTTP Version:</b> " << request.getVersion() << "</li>" << "<li><b>Host:</b> " << request.getHost() << "</li>" << "<li><b>Content Type:</b> " << request.getContentType() << "</li>" << "<li><b>Chunked:</b> " << (request.getChunkedTransferEncoding() ? "true" : "false") << "</li>" << "<li><b>Keep Alive:</b> " << (request.getKeepAlive() ? "true" : "false") << "</li>" << "<li><b>Transfer Encoding:</b> " << request.getTransferEncoding() << "</li>" << "<li><b>Client Address:</b> " << request.clientAddress().toString() << "</li>"; if (request.hasContentLength()) { ostr << "<li><b>Content Length:</b> " << request.getContentLength64() << "</li>"; } ostr << "</ul>"; // echo the request headers { ostr << "<hr>" "<h2>Request Headers</h2><ul>\n"; NameValueCollection headers; NameValueCollection::ConstIterator itr(request.begin()); NameValueCollection::ConstIterator itrEnd(request.end()); for (; itr != itrEnd; ++itr) { ostr << "<li><b>" << htmlize(itr->first) << "</b>: " << htmlize(itr->second) << "</li>"; } ostr << "</ul>"; } // echo any cookies { NameValueCollection cookies; request.getCookies(cookies); if (!cookies.empty()) { ostr << "<hr>"; ostr << "<h2>Cookies</h2><ul>\n"; NameValueCollection::ConstIterator itr(cookies.begin()); NameValueCollection::ConstIterator itrEnd(cookies.end()); for (; itr != itrEnd; ++itr) { ostr << "<li><b>" << htmlize(itr->first) << "</b>: " << htmlize(itr->second) << "</li>"; } ostr << "</ul>"; } } // echo any form data (GETs or POSTs) if (!form.empty()) { ostr << "<hr>" "<h2>Form Data</h2><ul>\n"; NameValueCollection::ConstIterator itr(form.begin()); NameValueCollection::ConstIterator itrEnd(form.end()); for (; itr != itrEnd; ++itr) { ostr << "<li><b>" << htmlize(itr->first) << "</b>: " << htmlize(itr->second) << "</li>\n"; } ostr << "</ul>"; } ostr << "<hr>" << "<h2>Response</h2>" << "<ul>" << "<li><b>Status:</b> " << response.getStatus() << "</li>" << "<li><b>Reason:</b> " << response.getReason() << "</li>" << "</ul>"; // echo the response headers { ostr << "<hr>" "<h2>Response Headers</h2><ul>\n"; NameValueCollection headers; NameValueCollection::ConstIterator itr(response.begin()); NameValueCollection::ConstIterator itrEnd(response.end()); for (; itr != itrEnd; ++itr) { ostr << "<li><b>" << htmlize(itr->first) << "</b>: " << htmlize(itr->second) << "</li>"; } ostr << "</ul>"; } ostr << "</div></body></html>"; }