bool GalaxyFDSClient::doesObjectExist(const string& bucketName, const string&
    objectName) {
  string uri = formatUri(_pConfig->getBaseUri(), bucketName + "/" + objectName,
      _emptySubResources);
  URI pocoUri(uri);

  shared_ptr<HTTPClientSession> pSession(_pSessionFacotry->createClientSession(
        pocoUri));
  pSession->setHost(pocoUri.getHost());
  pSession->setPort(pocoUri.getPort());
  HTTPRequest request(HTTPRequest::HTTP_HEAD, uri, HTTPMessage::HTTP_1_1);
  prepareRequestHeaders(uri, HTTPRequest::HTTP_HEAD, "", _emptyStream,
      *_pEmptyMetadata, request);
  HTTPResponse response;

  pSession->sendRequest(request);
  istream& rs = pSession->receiveResponse(response);

  if (response.getStatus() == HTTPResponse::HTTP_OK) {
    return true;
  } else if (response.getStatus() == HTTPResponse::HTTP_NOT_FOUND) {
    return false;
  } else {
    stringstream msg;
    msg << "Check object existence failed, status=" << response.getStatus()
      << ", reason=";
    StreamCopier::copyStream(rs, msg);
    throw GalaxyFDSClientException(response.getStatus(), msg.str());
  }
}
void GalaxyFDSClient::refreshObject(const string& bucketName, const string&
    objectName) {
  string uri = formatUri(_pConfig->getBaseUri(), bucketName + "/" + objectName,
      _emptySubResources);
  uri += "?refresh";
  URI pocoUri(uri);

  shared_ptr<HTTPClientSession> pSession(_pSessionFacotry->createClientSession(
        pocoUri));
  pSession->setHost(pocoUri.getHost());
  pSession->setPort(pocoUri.getPort());
  HTTPRequest request(HTTPRequest::HTTP_PUT, uri, HTTPMessage::HTTP_1_1);
  prepareRequestHeaders(uri, HTTPRequest::HTTP_PUT, "", _emptyStream,
    *_pEmptyMetadata, request);
  HTTPResponse response;

  pSession->sendRequest(request);
  istream& rs = pSession->receiveResponse(response);

  if (response.getStatus() != HTTPResponse::HTTP_OK) {
    stringstream msg;
    msg << "Prefetch object failed, status=" << response.getStatus() << ", reason=";
    StreamCopier::copyStream(rs, msg);
    throw GalaxyFDSClientException(response.getStatus(), msg.str());
  }
}
Ejemplo n.º 3
0
/**
* Calls a web service to get a full path to a file.
* Only returns a full path string if the file exists
* @param fName :: The file name.
* @return The path to the file or an empty string in case of error/non-existing
* file.
*/
std::string ISISDataArchive::getPath(const std::string &fName) const {
  g_log.debug() << "ISISDataArchive::getPath() - fName=" << fName << "\n";
  if (fName.empty())
    return ""; // Avoid pointless call to service

  URI uri(URL_PREFIX + fName);
  std::string path(uri.getPathAndQuery());

  HTTPClientSession session(uri.getHost(), uri.getPort());
  HTTPRequest req(HTTPRequest::HTTP_GET, path, HTTPMessage::HTTP_1_1);
  session.sendRequest(req);

  HTTPResponse res;
  std::istream &rs = session.receiveResponse(res);
  const HTTPResponse::HTTPStatus status = res.getStatus();
  g_log.debug() << "HTTP response=" << res.getStatus() << "\n";
  if (status == HTTPResponse::HTTP_OK) {
    std::ostringstream os;
    Poco::StreamCopier::copyStream(rs, os);
    os << Poco::Path::separator() << fName;
    try {
      const std::string expectedPath = os.str();
      if (Poco::File(expectedPath).exists())
        return expectedPath;
    } catch (Poco::Exception &) {
    }
  }
  return "";
}
shared_ptr<FDSObjectMetadata> GalaxyFDSClient::getObjectMetadata(const string&
    bucketName, const string& objectName) {
  vector<string> subResources;
  subResources.push_back(SubResource::METADATA);
  string uri = formatUri(_pConfig->getBaseUri(), bucketName + "/" + objectName,
      subResources);
  URI pocoUri(uri);

  shared_ptr<HTTPClientSession> pSession(_pSessionFacotry->createClientSession(
        pocoUri));
  pSession->setHost(pocoUri.getHost());
  pSession->setPort(pocoUri.getPort());
  HTTPRequest request(HTTPRequest::HTTP_GET, uri, HTTPMessage::HTTP_1_1);
  prepareRequestHeaders(uri, HTTPRequest::HTTP_GET, "", _emptyStream,
      *_pEmptyMetadata, request);
  HTTPResponse response;

  pSession->sendRequest(request);
  istream& rs = pSession->receiveResponse(response);

  if (response.getStatus() != HTTPResponse::HTTP_OK) {
    stringstream msg;
    msg << "Get object metadata failed, status=" << response.getStatus()
      << ", reason=";
    StreamCopier::copyStream(rs, msg);
    throw GalaxyFDSClientException(response.getStatus(), msg.str());
  }

  return parseMetadata(response);
}
shared_ptr<FDSObjectListing> GalaxyFDSClient::listObjects(const string&
    bucketName, const string& prefix, const string& delimiter) {
  string uri = formatUri(_pConfig->getBaseUri(), bucketName, _emptySubResources);
  uri += "?prefix=" + prefix + "&delimiter=" + delimiter;
  URI pocoUri(uri);

  shared_ptr<HTTPClientSession> pSession(_pSessionFacotry
      ->createClientSession(pocoUri));
  pSession->setHost(pocoUri.getHost());
  pSession->setPort(pocoUri.getPort());
  HTTPRequest request(HTTPRequest::HTTP_GET, uri, HTTPMessage::HTTP_1_1);
  prepareRequestHeaders(uri, HTTPRequest::HTTP_GET, "", _emptyStream,
      *_pEmptyMetadata, request);
  HTTPResponse response;

  ostream& os = pSession->sendRequest(request);
  istream& rs = pSession->receiveResponse(response);

  if (response.getStatus() != HTTPResponse::HTTP_OK) {
    stringstream msg;
    msg << "List objects failed, status=" << response.getStatus() << ", reason=";
    StreamCopier::copyStream(rs, msg);
    throw GalaxyFDSClientException(response.getStatus(), msg.str());
  }

  return FDSObjectListing::deserialize(rs);
}
Ejemplo n.º 6
0
 void runDelete(){
     try{
         std::string result;
         URI uri("http://jsonplaceholder.typicode.com/posts/" + std::to_string(request->getPostID()) );
         std::string path(uri.getPathAndQuery());
         HTTPClientSession session(uri.getHost(), uri.getPort());
         HTTPRequest hrequest(HTTPRequest::HTTP_DELETE, path, HTTPMessage::HTTP_1_1);
         HTTPResponse response;
         session.sendRequest(hrequest);
         std::istream& rs = session.receiveResponse(response);
         if(response.getStatus() == Poco::Net::HTTPResponse::HTTP_OK){
             Response *res = new Response;
             res->setReqID(reqID);
             res->setHTTPStatus(HTTPResponse::HTTP_OK);
             observer.responseQueue.enqueueNotification(new ResponseNotification(res));
             {
                 FastMutex::ScopedLock lock(Observer::observerMutex);
                 observer.setResponseAvailable(true);
             }
         }
         else {
             Response *res = new Response;
             res->setHTTPStatus(response.getStatus());
             res->setReqID(reqID);
             observer.responseQueue.enqueueNotification(new ResponseNotification(res));
             {
                 FastMutex::ScopedLock lock(Observer::observerMutex);
                 observer.setResponseAvailable(true);
             }
         }
     }
     catch(Exception& exc){
         std::cerr<< exc.displayText() << std::endl;
     }
 }
void GalaxyFDSClient::setObjectAcl(const string& bucketName, const string&
    objectName, const AccessControlList& acl) {
  vector<string> subResources;
  subResources.push_back(SubResource::ACL);
  string uri = formatUri(_pConfig->getBaseUri(), bucketName + "/" + objectName,
      subResources);
  URI pocoUri(uri);

  shared_ptr<HTTPClientSession> pSession(_pSessionFacotry->createClientSession(
        pocoUri));
  pSession->setHost(pocoUri.getHost());
  pSession->setPort(pocoUri.getPort());
  HTTPRequest request(HTTPRequest::HTTP_PUT, uri, HTTPMessage::HTTP_1_1);
  stringstream ss(AccessControlList::serialize(acl));
  prepareRequestHeaders(uri, HTTPRequest::HTTP_PUT, "application/json", ss,
      *_pEmptyMetadata, request);
  HTTPResponse response;

  ostream& os = pSession->sendRequest(request);
  StreamCopier::copyStream(ss, os);
  istream& rs = pSession->receiveResponse(response);

  if (response.getStatus() != HTTPResponse::HTTP_OK) {
    stringstream msg;
    msg << "Set Object acl failed, status=" << response.getStatus()
      << ", reason=";
    StreamCopier::copyStream(rs, msg);
    throw GalaxyFDSClientException(response.getStatus(), msg.str());
  }
}
Ejemplo n.º 8
0
ofHttpResponse ofURLFileLoader::handleRequest(ofHttpRequest request) {
	try {
		URI uri(request.url);
		std::string path(uri.getPathAndQuery());
		if (path.empty()) path = "/";

		HTTPRequest req(HTTPRequest::HTTP_GET, path, HTTPMessage::HTTP_1_1);
		HTTPResponse res;
		ofPtr<HTTPSession> session;
		istream * rs;
		if(uri.getScheme()=="https"){
			 //const Poco::Net::Context::Ptr context( new Poco::Net::Context( Poco::Net::Context::CLIENT_USE, "", "", "rootcert.pem" ) );
			HTTPSClientSession * httpsSession = new HTTPSClientSession(uri.getHost(), uri.getPort());//,context);
			httpsSession->setTimeout(Poco::Timespan(20,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(20,0));
			httpSession->sendRequest(req);
			rs = &httpSession->receiveResponse(res);
			session = ofPtr<HTTPSession>(httpSession);
		}
		if(!request.saveTo){
			return ofHttpResponse(request,*rs,res.getStatus(),res.getReason());
		}else{
			ofFile saveTo(request.name,ofFile::WriteOnly,true);
			char aux_buffer[1024];
			rs->read(aux_buffer, 1024);
			std::streamsize n = rs->gcount();
			while (n > 0){
				// we resize to size+1 initialized to 0 to have a 0 at the end for strings
				saveTo.write(aux_buffer,n);
				if (rs->good()){
					rs->read(aux_buffer, 1024);
					n = rs->gcount();
				}
				else n = 0;
			}
			return ofHttpResponse(request,res.getStatus(),res.getReason());
		}

	} catch (const Exception& exc) {
        ofLogError("ofURLFileLoader") << "handleRequest(): "+ exc.displayText();

        return ofHttpResponse(request,-1,exc.displayText());

    } catch (...) {
    	return ofHttpResponse(request,-1,"ofURLFileLoader: fatal error, couldn't catch Exception");
    }

	return ofHttpResponse(request,-1,"ofURLFileLoader: fatal error, couldn't catch Exception");
	
}	
Ejemplo n.º 9
0
	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());
			}
		}
	}
Ejemplo n.º 10
0
	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());
			}
		}
	}
Ejemplo n.º 11
0
	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);
	}
int main(int argc, char **argv) { 
  // using `web` as provider
  URI uri("https://yboss.yahooapis.com/ysearch/web?q=cat");

  // init the creds, I think the empty token and token secret are important
  OAuth10Credentials creds(
      "dj0yJmk9eGx5RzFQOVAwcDZpJmQ9WVdrOWVVUkhWamhwTkdVbWNHbzlNQS0tJnM9Y29uc3VtZXJzZWNyZXQmeD0wYw--", 
      "2bf8a4682c4948fb4f7add9598eef5f86b57cf93", "", "");
  
  HTTPRequest request(HTTPRequest::HTTP_GET, uri.getPathEtc());
  
  // put the `q` as param
  HTMLForm params;
  params.set("q", "cat");

  creds.authenticate(request, uri, params);
  std::string auth = request.get("Authorization");
  std::cout << auth << std::endl;

  const Context::Ptr context = new Context(Context::CLIENT_USE, "", "", "", Context::VERIFY_NONE, 9, false, "ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
  HTTPSClientSession session(uri.getHost(), uri.getPort(), context);
  session.sendRequest(request);

  HTTPResponse response;
  std::istream& rs = session.receiveResponse(response);
  std::cout << response.getStatus() << " " << response.getReason() << std::endl;
  StreamCopier::copyStream(rs, std::cout);
  return 0;
}
Ejemplo n.º 13
0
int main(int argc, char** argv)
{
	if (argc != 2)
	{
		Path p(argv[0]);
		std::cout << "usage: " << p.getBaseName() << " <uri>" << std::endl;
		std::cout << "       fetches the resource identified by <uri> and print it to the standard output" << std::endl;
		return 1;
	}

	try
	{
		URI uri(argv[1]);
		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);
		session.sendRequest(req);
		HTTPResponse res;
		std::istream& rs = session.receiveResponse(res);
		std::cout << res.getStatus() << " " << res.getReason() << std::endl;
		StreamCopier::copyStream(rs, std::cout);
	}
	catch (Exception& exc)
	{
		std::cerr << exc.displayText() << std::endl;
		return 1;
	}
	return 0;
}
Ejemplo n.º 14
0
shared_ptr<FDSObject> GalaxyFDSClient::getObject(const string& bucketName,
    const string& objectName, long pos, long len) {
  string uri = formatUri(_pConfig->getDownloadBaseUri(), bucketName + "/" +
      objectName, vector<string>());
  URI pocoUri(uri);

  shared_ptr<HTTPClientSession> pSession(_pSessionFacotry
      ->createClientSession(pocoUri));
  pSession->setHost(pocoUri.getHost());
  pSession->setPort(pocoUri.getPort());
  HTTPRequest request(HTTPRequest::HTTP_GET, uri, HTTPMessage::HTTP_1_1);
  FDSObjectMetadata metadata;
  if (pos >= 0 || len > 0) {
    std::ostringstream os;
    os << "bytes=" << pos << "-";
    if (len > 0) {
      os << (pos + len - 1); // inclusive
    }
    metadata.add(Constants::RANGE, os.str());
  }
  prepareRequestHeaders(uri, HTTPRequest::HTTP_GET, "",  _emptyStream,
      metadata, request);
  HTTPResponse response;

  pSession->sendRequest(request);
  istream& rs = pSession->receiveResponse(response);

  if (response.getStatus() != HTTPResponse::HTTP_OK &&
      response.getStatus() != HTTPResponse::HTTP_PARTIAL_CONTENT) {
    stringstream msg;
    msg << "Get object failed, status=" << response.getStatus() << ", reason=";
    StreamCopier::copyStream(rs, msg);
    throw GalaxyFDSClientException(response.getStatus(), msg.str());
  }

  shared_ptr<FDSObjectSummary> pObjectSummary(new FDSObjectSummary());
  pObjectSummary->setBucketName(bucketName);
  pObjectSummary->setObjectName(objectName);
  pObjectSummary->setSize(response.getContentLength());
  shared_ptr<FDSObject> pObject(new FDSObject());
  pObject->setObjectSummary(pObjectSummary);
  pObject->setObjectMetadata(this->parseMetadata(response));
  pObject->setSession(pSession);
  pObject->setObjectContent(rs);

  return pObject;
}
Ejemplo n.º 15
0
 void runUpdate(){
     try{
         std::string result;
         URI uri("http://jsonplaceholder.typicode.com/posts/" + std::to_string(request->getPostID()));
         std::string path(uri.getPathAndQuery());
         HTTPClientSession session(uri.getHost(), uri.getPort());
         session.setKeepAlive(true);
         HTTPRequest hrequest(HTTPRequest::HTTP_PUT, path, HTTPMessage::HTTP_1_1);
         hrequest.setKeepAlive(true);
         hrequest.setContentType("application/x-www-form-urlencoded");
         std::string requestBody("id="+std::to_string(request->getPostID())+"&title="+request->getPostTitle()+"&body="+request->getPostBody()+"&userID="+std::to_string(request->getPostUserID()));
         hrequest.setContentLength(requestBody.length());
         HTTPResponse response;
         std::ostream& ostreamSession = session.sendRequest(hrequest);
         ostreamSession << requestBody;
         std::istream& rs = session.receiveResponse(response);
         if(response.getStatus() == Poco::Net::HTTPResponse::HTTP_OK){
             StreamCopier::copyToString(rs, result);
             Response *res = new Response;
             res->setResponseString(result);
             res->setReqID(reqID);
             res->setHTTPStatus(HTTPResponse::HTTP_OK);
             observer.responseQueue.enqueueNotification(new ResponseNotification(res));
             {
                 FastMutex::ScopedLock lock(Observer::observerMutex);
                 observer.setResponseAvailable(true);
             }
         } 
         else {
             Response *res = new Response;
             res->setHTTPStatus(response.getStatus());
             res->setReqID(reqID);
             observer.responseQueue.enqueueNotification(new ResponseNotification(res));
             {
                 FastMutex::ScopedLock lock(Observer::observerMutex);
                 observer.setResponseAvailable(true);
             }
         }
         
     }
     catch(Exception& exc){
         std::cerr<< exc.displayText() << std::endl;
     }
 }
Ejemplo n.º 16
0
vector<shared_ptr<FDSBucket> > GalaxyFDSClient::listBuckets() {
  string uri = formatUri(_pConfig->getBaseUri(), "", _emptySubResources);
  URI pocoUri(uri);

  shared_ptr<HTTPClientSession> pSession(_pSessionFacotry
      ->createClientSession(pocoUri));
  pSession->setHost(pocoUri.getHost());
  pSession->setPort(pocoUri.getPort());
  HTTPRequest request(HTTPRequest::HTTP_GET, uri, HTTPMessage::HTTP_1_1);
  prepareRequestHeaders(uri, HTTPRequest::HTTP_GET, "", _emptyStream,
      *_pEmptyMetadata, request);
  HTTPResponse response;

  ostream& os = pSession->sendRequest(request);
  istream& rs = pSession->receiveResponse(response);

  if (response.getStatus() != HTTPResponse::HTTP_OK) {
    stringstream msg;
    msg << "List buckets failed, status=" << response.getStatus() << ", reason=";
    StreamCopier::copyStream(rs, msg);
    throw GalaxyFDSClientException(response.getStatus(), msg.str());
  }

  vector<shared_ptr<FDSBucket> > res;
  Parser parser;
  parser.parse(rs);
  Var result = parser.result();
  Object::Ptr pObject = result.extract<Object::Ptr>();
  Object::Ptr pOwnerObject = pObject->getObject("owner");
  stringstream ss;
  pOwnerObject->stringify(ss);
  shared_ptr<Owner> pOwner = Owner::deserialize(ss);
  Array::Ptr pBucketsArray = pObject->getArray("buckets");
  for (size_t i = 0; i < pBucketsArray->size(); i++) {
    string bucketName = pBucketsArray->getObject(i)->getValue<string>("name");
    shared_ptr<FDSBucket> pBucket(new FDSBucket(bucketName));
    pBucket->setOwner(*pOwner);
    res.push_back(pBucket);
  }

  return res;
}
Ejemplo n.º 17
0
ofHttpResponse ofURLFileLoader::handleRequest(ofHttpRequest request) {
	try {
		URI uri(request.url);
		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);
		session.setTimeout(Poco::Timespan(20,0));
		session.sendRequest(req);
		HTTPResponse res;
		istream& rs = session.receiveResponse(res);
		if(!request.saveTo){
			return ofHttpResponse(request,rs,res.getStatus(),res.getReason());
		}else{
			ofFile saveTo(request.name,ofFile::WriteOnly,true);
			char aux_buffer[1024];
			rs.read(aux_buffer, 1024);
			std::streamsize n = rs.gcount();
			while (n > 0){
				// we resize to size+1 initialized to 0 to have a 0 at the end for strings
				saveTo.write(aux_buffer,n);
				if (rs){
					rs.read(aux_buffer, 1024);
					n = rs.gcount();
				}
				else n = 0;
			}
			return ofHttpResponse(request,res.getStatus(),res.getReason());
		}

	} catch (const Exception& exc) {
        ofLog(OF_LOG_ERROR, "ofURLFileLoader " + exc.displayText());

        return ofHttpResponse(request,-1,exc.displayText());

    } catch (...) {
    	return ofHttpResponse(request,-1,"ofURLFileLoader fatal error, couldn't catch Exception");
    }

	
}	
Ejemplo n.º 18
0
int InternetHelper::processRelocation(const HTTPResponse &response,
                                      std::ostream &responseStream) {
  std::string newLocation = response.get("location", "");
  if (!newLocation.empty()) {
    g_log.information() << "url relocated to " << newLocation;
    return this->sendRequest(newLocation, responseStream);
  } else {
    g_log.warning("Apparent relocation did not give new location\n");
    return response.getStatus();
  }
}
Ejemplo n.º 19
0
void HTTPResponseTest::testRead1()
{
	std::string s("HTTP/1.1 500 Internal Server Error\r\n\r\n");
	std::istringstream istr(s);
	HTTPResponse response;
	response.read(istr);
	assert (response.getStatus() == HTTPResponse::HTTP_INTERNAL_SERVER_ERROR);
	assert (response.getReason() == "Internal Server Error");
	assert (response.getVersion() == HTTPMessage::HTTP_1_1);
	assert (response.empty());
	assert (istr.get() == -1);
}
Ejemplo n.º 20
0
POCO_HttpClient_response POCO_HttpClient::POST_request(string param_uri)
{
	_mutex.lock();

	URI uri(param_uri);
	string path(uri.getPath());
	if (path.empty()) path = "/";
	string requestBody = uri.getQuery();
	HTTPClientSession session(uri.getHost(), uri.getPort());
	HTTPRequest request(HTTPRequest::HTTP_POST, path, HTTPMessage::HTTP_1_1);
	HTTPResponse response;

	session.setKeepAlive(true);
	request.setKeepAlive(true);
	request.setContentType("application/x-www-form-urlencoded");
	request.setContentLength(requestBody.length());


	string state = "";
	string reason = "";
	string received = "";
	HTTPResponse::HTTPStatus status = HTTPResponse::HTTPStatus::HTTP_NOT_FOUND;

	try 
	{
		session.sendRequest(request) << requestBody;
		std::istream& rs = session.receiveResponse(response);
		status = response.getStatus();
		reason = response.getReason();
		received = "";
		string temp;
		while (getline(rs, temp))
		{
			received += temp + "\n";
		}
		state = "success";
	}
	catch (NetException e)
	{
		state = "exception";
		received = e.displayText();
	}
	catch (...)
	{
		state = "exception";
		received = "exception";
	}
	
	_mutex.unlock();

	return POCO_HttpClient_response(state, received, status, reason);
}
Ejemplo n.º 21
0
 void runGetID(){
     try{
         std::string result;
         URI uri("http://jsonplaceholder.typicode.com/posts/" + std::to_string(request->getPostID()));
         std::string path(uri.getPathAndQuery());
         HTTPClientSession session(uri.getHost(), uri.getPort());
         HTTPRequest request(HTTPRequest::HTTP_GET, path, HTTPMessage::HTTP_1_1);
         HTTPResponse response;
         session.sendRequest(request);
         std::istream& rs = session.receiveResponse(response);
         if (response.getStatus() == Poco::Net::HTTPResponse::HTTP_OK) {
             StreamCopier::copyToString(rs, result);
             Response *res = new Response;
             res->setResponseString(result);
             res->setReqID(reqID);
             res->setHTTPStatus(HTTPResponse::HTTP_OK);
             observer.responseQueue.enqueueNotification(new ResponseNotification(res));
             {
                 /*
                  * Observer object can be common among multiple threads, hence the need for locking while accessing it's variables.
                  */
                 FastMutex::ScopedLock lock(Observer::observerMutex);
                 observer.setResponseAvailable(true);
             }
         } else {
             Response *res = new Response;
             res->setHTTPStatus(response.getStatus());
             res->setReqID(reqID);
             observer.responseQueue.enqueueNotification(new ResponseNotification(res));
             {
                 FastMutex::ScopedLock lock(Observer::observerMutex);
                 observer.setResponseAvailable(true);
             }
         }
     }
     catch(Exception& exc){
         std::cerr<< exc.displayText() << std::endl;
     }
 }
void OAuthPrivate::resourceFile(const std::string method, const std::string url, const std::string & filename, const std::string status){
	std::string authStr = buildAuthHeader(method, url, Params());
	authStr = "OAuth " + authStr;

	URI uri(url);
	std::string path(uri.getPathAndQuery());
	if (path.empty()) path = "/";

	const Poco::Net::Context::Ptr context( new Poco::Net::Context(Poco::Net::Context::CLIENT_USE, "", "", "cacert.pem"));
	HTTPSClientSession session(uri.getHost(), uri.getPort(), context);
	HTTPRequest request(HTTPRequest::HTTP_POST, path, HTTPMessage::HTTP_1_1);
	HTTPResponse response;

	Poco::Net::HTMLForm form;
	form.setEncoding(Poco::Net::HTMLForm::ENCODING_MULTIPART);

	form.set("status", status);
	
	form.addPart("media[]", new Poco::Net::FilePartSource(filename, filename, "application/octet-stream"));
	form.prepareSubmit(request);

	request.set("Authorization", authStr);
	
	std::ostream & ostr = session.sendRequest(request);
	form.write(ostr);

	std::istream& rs = session.receiveResponse(response);
	std::cout << response.getStatus() << " " << response.getReason() << std::endl;

	if (response.getStatus() != Poco::Net::HTTPResponse::HTTP_UNAUTHORIZED)
	{
		StreamCopier::copyStream(rs, std::cout);
	}
	else
	{
		Poco::NullOutputStream null;
		StreamCopier::copyStream(rs, null);
	}
}
Ejemplo n.º 23
0
void HTTPResponseTest::testRead3()
{
	std::string s("HTTP/1.1 200 \r\nContent-Length: 0\r\n\r\n");
	std::istringstream istr(s);
	HTTPResponse response;
	response.read(istr);
	assert (response.getVersion() == HTTPMessage::HTTP_1_1);
	assert (response.getStatus() == HTTPResponse::HTTP_OK);
	assert (response.getReason() == "");
	assert (response.size() == 1);
	assert (response.getContentLength() == 0);
	assert (istr.get() == -1);
}
Ejemplo n.º 24
0
shared_ptr<PutObjectResult> GalaxyFDSClient::putObject(const string& bucketName,
    const string& objectName, istream& is, const FDSObjectMetadata&
    metadata) {
  PutObjectResult res;

  string mediaType = "application/octet-stream";
  map<string, string>::const_iterator iter = metadata.metadata().find(
      Constants::CONTENT_TYPE);
  if (iter != metadata.metadata().end()) {
    mediaType = iter->second;
  }

  string uri = formatUri(_pConfig->getUploadBaseUri(), bucketName + "/" +
      objectName, _emptySubResources);
  URI pocoUri(uri);

  shared_ptr<HTTPClientSession> pSession(_pSessionFacotry->createClientSession(
        pocoUri));
  pSession->setHost(pocoUri.getHost());
  pSession->setPort(pocoUri.getPort());
  HTTPRequest request(HTTPRequest::HTTP_PUT, uri, HTTPMessage::HTTP_1_1);
  prepareRequestHeaders(uri, HTTPRequest::HTTP_PUT, mediaType, is, metadata,
      request);
  HTTPResponse response;

  ostream& os = pSession->sendRequest(request);
  StreamCopier::copyStream(is, os);
  istream& rs = pSession->receiveResponse(response);

  if (response.getStatus() != HTTPResponse::HTTP_OK) {
    stringstream msg;
    msg << "Put object failed, status=" << response.getStatus() << ", reason=";
    StreamCopier::copyStream(rs, msg);
    throw GalaxyFDSClientException(response.getStatus(), msg.str());
  }

  return PutObjectResult::deserialize(rs);
}
Ejemplo n.º 25
0
BOOL SendRequest(std::string addUri)
{
    URI uri(addUri);
    auto path(uri.getPathAndQuery());

    HTTPClientSession session(uri.getHost(), uri.getPort());
    HTTPRequest request(HTTPRequest::HTTP_GET, path, HTTPMessage::HTTP_1_1);
    HTTPResponse response;

    session.sendRequest(request);
    session.receiveResponse(response);

    return (response.getStatus() == HTTPResponse::HTTP_OK) ? TRUE : FALSE;
}
Ejemplo n.º 26
0
void HTTPResponseTest::testRead2()
{
	std::string s("HTTP/1.0 301 Moved Permanently\r\nLocation: http://www.appinf.com/index.html\r\nServer: Poco/1.0\r\n\r\n");
	std::istringstream istr(s);
	HTTPResponse response;
	response.read(istr);
	assert (response.getStatus() == HTTPResponse::HTTP_MOVED_PERMANENTLY);
	assert (response.getReason() == "Moved Permanently");
	assert (response.getVersion() == HTTPMessage::HTTP_1_0);
	assert (response.size() == 2);
	assert (response["Location"] == "http://www.appinf.com/index.html");
	assert (response["Server"] == "Poco/1.0");
	assert (istr.get() == -1);
}
Ejemplo n.º 27
0
shared_ptr<FDSObjectListing> GalaxyFDSClient::listNextBatchOfObjects(const
    FDSObjectListing& previousObjectListing) {
  string bucketName = previousObjectListing.bucketName();
  string prefix = previousObjectListing.prefix();
  string delimiter = previousObjectListing.delimiter();
  string marker = previousObjectListing.nextMarker();
  int maxKeys = previousObjectListing.maxKeys();

  string uri = formatUri(_pConfig->getBaseUri(), bucketName, _emptySubResources);
  stringstream ss;
  ss << uri << "?prefix=" << prefix << "&delimiter=" << delimiter;
  ss << "&marker=" << marker << "&maxKeys=" << maxKeys;
  uri = ss.str();
  URI pocoUri(uri);

  shared_ptr<HTTPClientSession> pSession(_pSessionFacotry
      ->createClientSession(pocoUri));
  pSession->setHost(pocoUri.getHost());
  pSession->setPort(pocoUri.getPort());
  HTTPRequest request(HTTPRequest::HTTP_GET, uri, HTTPMessage::HTTP_1_1);
  prepareRequestHeaders(uri, HTTPRequest::HTTP_GET, "", _emptyStream,
      *_pEmptyMetadata, request);
  HTTPResponse response;

  ostream& os = pSession->sendRequest(request);
  istream& rs = pSession->receiveResponse(response);

  if (response.getStatus() != HTTPResponse::HTTP_OK) {
    stringstream msg;
    msg << "List objects failed, status=" << response.getStatus() << ", reason=";
    StreamCopier::copyStream(rs, msg);
    throw GalaxyFDSClientException(response.getStatus(), msg.str());
  }

  return FDSObjectListing::deserialize(rs);
}
 std::string doGet(int id){
     std::string result;
     URI uri("http://jsonplaceholder.typicode.com/posts/" + std::to_string(id));
     std::string path(uri.getPathAndQuery());
     HTTPClientSession session(uri.getHost(), uri.getPort());
     HTTPRequest request(HTTPRequest::HTTP_GET, path, HTTPMessage::HTTP_1_1);
     HTTPResponse response;
     session.sendRequest(request);
     std::istream& rs = session.receiveResponse(response);
     if(response.getStatus() == Poco::Net::HTTPResponse::HTTP_OK){
         StreamCopier::copyToString(rs, result);
         return result;
     }
     else
         return "";
 }
Ejemplo n.º 29
0
    TestResult testIncorrectPassword()
    {
        HTTPResponse response;
        std::string path(_uri.getPathAndQuery());
        HTTPRequest request(HTTPRequest::HTTP_GET, path);
        std::unique_ptr<HTTPClientSession> session(helpers::createSession(_uri));

        session->sendRequest(request);
        session->receiveResponse(response);
        TestResult res = TestResult::TEST_FAILED;
        if (response.getStatus() == HTTPResponse::HTTP_UNAUTHORIZED)
            res = TestResult::TEST_OK;

        Log::info(std::string("testIncorrectPassword: "******"OK" : "FAIL"));
        return res;
    }
Ejemplo n.º 30
0
StreamSocket HTTPClientSession::proxyConnect()
{
	HTTPClientSession proxySession(getProxyHost(), getProxyPort());
	proxySession.setTimeout(getTimeout());
	SocketAddress targetAddress(getHost(), getPort());
	HTTPRequest proxyRequest(HTTPRequest::HTTP_CONNECT, targetAddress.toString(), HTTPMessage::HTTP_1_1);
	HTTPResponse proxyResponse;
	proxyRequest.set("Proxy-Connection", "keep-alive");
	proxyRequest.set("Host", getHost());
	proxyAuthenticateImpl(proxyRequest);
	proxySession.setKeepAlive(true);
	proxySession.sendRequest(proxyRequest);
	proxySession.receiveResponse(proxyResponse);
	if (proxyResponse.getStatus() != HTTPResponse::HTTP_OK)
		throw HTTPException("Cannot establish proxy connection", proxyResponse.getReason());
	return proxySession.detachSocket();
}