Example #1
1
Poco::AutoPtr<Poco::XML::Document> Twitter::invoke(const std::string& httpMethod, const std::string& twitterMethod, Poco::Net::HTMLForm& form)
{
    // Create the request URI.
    // We use the XML version of the Twitter API.
    Poco::URI uri(_uri + twitterMethod + ".xml");
    std::string path(uri.getPath());

    Poco::Net::HTTPClientSession session(uri.getHost(), uri.getPort());
    Poco::Net::HTTPRequest req(httpMethod, path, Poco::Net::HTTPMessage::HTTP_1_1);

    // Add username and password (HTTP basic authentication) to the request.
    Poco::Net::HTTPBasicCredentials cred(_username, _password);
    cred.authenticate(req);

    // Send the request.
    form.prepareSubmit(req);
    std::ostream& ostr = session.sendRequest(req);
    form.write(ostr);

    // Receive the response.
    Poco::Net::HTTPResponse res;
    std::istream& rs = session.receiveResponse(res);

    // Create a DOM document from the response.
    Poco::XML::DOMParser parser;
    parser.setFeature(Poco::XML::DOMParser::FEATURE_FILTER_WHITESPACE, true);
    parser.setFeature(Poco::XML::XMLReader::FEATURE_NAMESPACES, false);
    Poco::XML::InputSource source(rs);
    Poco::AutoPtr<Poco::XML::Document> pDoc = parser.parse(&source);

    // If everything went fine, return the XML document.
    // Otherwise look for an error message in the XML document.
    if (res.getStatus() == Poco::Net::HTTPResponse::HTTP_OK)
    {
        return pDoc;
    }
    else
    {
        std::string error(res.getReason());
        Poco::AutoPtr<Poco::XML::NodeList> pList = pDoc->getElementsByTagName("error");
        if (pList->length() > 0)
        {
            error += ": ";
            error += pList->item(0)->innerText();
        }
        throw Poco::ApplicationException("Twitter Error", error);
    }
}
/** Process any HTTP errors states.

@param res : The http response
@param rs : The iutput stream from the response
@param url : The url originally called

@exception Mantid::Kernel::Exception::InternetError : Coded for the failure
state.
*/
int InternetHelper::processErrorStates(const Poco::Net::HTTPResponse &res,
                                       std::istream &rs,
                                       const std::string &url) {
  int retStatus = res.getStatus();
  g_log.debug() << "Answer from web: " << res.getStatus() << " "
                << res.getReason() << std::endl;

  // get github api rate limit information if available;
  int rateLimitRemaining;
  DateAndTime rateLimitReset;
  try {
    rateLimitRemaining =
        boost::lexical_cast<int>(res.get("X-RateLimit-Remaining", "-1"));
    rateLimitReset.set_from_time_t(
        boost::lexical_cast<int>(res.get("X-RateLimit-Reset", "0")));
  } catch (boost::bad_lexical_cast const &) {
    rateLimitRemaining = -1;
  }

  if (retStatus == HTTP_OK) {
    throw Exception::InternetError("Response was ok, processing should never "
                                   "have entered processErrorStates",
                                   retStatus);
  } else if (retStatus == HTTP_FOUND) {
    throw Exception::InternetError("Response was HTTP_FOUND, processing should "
                                   "never have entered processErrorStates",
                                   retStatus);
  } else if (retStatus == HTTP_MOVED_PERMANENTLY) {
    throw Exception::InternetError("Response was HTTP_MOVED_PERMANENTLY, "
                                   "processing should never have entered "
                                   "processErrorStates",
                                   retStatus);
  } else if (retStatus == HTTP_NOT_MODIFIED) {
    throw Exception::InternetError("Not modified since provided date" +
                                       rateLimitReset.toSimpleString(),
                                   retStatus);
  } else if ((retStatus == HTTP_FORBIDDEN) && (rateLimitRemaining == 0)) {
    throw Exception::InternetError(
        "The Github API rate limit has been reached, try again after " +
            rateLimitReset.toSimpleString(),
        retStatus);
  } else {
    std::stringstream info;
    std::stringstream ss;
    Poco::StreamCopier::copyStream(rs, ss);
    if (retStatus == HTTP_NOT_FOUND)
      info << "Failed to download " << url << " with the link "
           << "<a href=\"" << url << "\">.\n"
           << "Hint. Check that link is correct</a>";
    else {
      // show the error
      info << res.getReason();
      info << ss.str();
      g_log.debug() << ss.str();
    }
    throw Exception::InternetError(info.str() + ss.str(), retStatus);
  }
}
Example #3
0
    bool verify(const std::string& token) override
    {
        const std::string url = _authVerifyUrl + token;
        Log::debug("Verifying authorization token from: " + url);
        Poco::URI uri(url);
        Poco::Net::HTTPClientSession session(uri.getHost(), uri.getPort());
        Poco::Net::HTTPRequest request(Poco::Net::HTTPRequest::HTTP_GET, url, Poco::Net::HTTPMessage::HTTP_1_1);
        Poco::Net::HTTPResponse response;
        session.sendRequest(request);
        std::istream& rs = session.receiveResponse(response);
        Log::info() << "Status: " <<  response.getStatus() << " " << response.getReason() << Log::end;
        std::string reply(std::istreambuf_iterator<char>(rs), {});
        Log::info("Response: " + reply);

        //TODO: Parse the response.
        /*
        // This is used for the demo site.
        const auto lastLogTime = std::strtoul(reply.c_str(), nullptr, 0);
        if (lastLogTime < 1)
        {
            //TODO: Redirect to login page.
            return;
        }
        */

        return true;
    }
void ServerAccess::masksReady(std::string uuid, std::string message)
{
    Poco::URI uri(server_address + "/api/calibrations/" + uuid + "/masksReady");
    //std::string url = server_address + "/api/screens";
    Poco::Net::HTTPClientSession session(uri.getHost(), uri.getPort());

    //prepare path
    std::string path(uri.getPath());
    //prepare and send request
    std::string reqBody(message);
    Poco::Net::HTTPRequest req(Poco::Net::HTTPRequest::HTTP_POST, path, Poco::Net::HTTPMessage::HTTP_1_1);
    req.setContentType("application/json");
    req.setContentLength(reqBody.length());
    req.setKeepAlive(true);
    std::ostream& oustr = session.sendRequest(req);
    //oustr << results;
    oustr << reqBody;
    req.write(std::cout);

    //get response
    Poco::Net::HTTPResponse res;

    std::cout << res.getStatus() << res.getReason() << std::endl;

    std::istream &is = session.receiveResponse(res);
    Poco::StreamCopier::copyStream(is, std::cout);
}
Example #5
0
bool myClientInteractor::sendRequest(Poco::Net::HTTPClientSession& session, Poco::Net::HTTPRequest& request, Poco::Net::HTTPResponse& response){
	//tracker->stringify(std::cout, 0);
	try{
	str.clear();
	tracker->stringify(str, 0);
	str >> json;
	//std::cout << "Sending: " << json << std::endl;
	std::cout << response.getStatus() << " " << response.getReason() << std::endl;
	
	if (response.getStatus() != Poco::Net::HTTPResponse::HTTP_UNAUTHORIZED)
	{
		std::ostream& os = session.sendRequest(request);
		//std::cout << "HERE NO PROBLEMS!!" << std::endl;	
		os << json;


		return true;
	}
	else
	{
		//std::cout << "NULL!!!!" << std::endl;
		Poco::NullOutputStream null;
		//StreamCopier::copyStream(rs, null);
		return false;
	}
	
	}catch(Exception& exc)
	{
		std::cerr << exc.displayText() << std::endl;
		return 1;
	}
}
Example #6
0
	void ForecastSensor::parse() {
		r.clear();
		try {
			std::cout << "get url: " << url << std::endl;

			//http://www.yr.no/place/Czech_Republic/Central_Bohemia/%C4%8Cerven%C3%A9_Pe%C4%8Dky/forecast_hour_by_hour.xml
			Poco::URI uri(url);

			std::string path(uri.getPathAndQuery());

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

			session.sendRequest(request);

			std::istream& rs = session.receiveResponse(response);

			std::cout << response.getStatus() << " " << response.getReason() << std::endl;
			if (response.getStatus() != Poco::Net::HTTPResponse::HTTP_OK) {
				throw Poco::Exception("Cannot get remote data");
			}

			//Poco::StreamCopier::copyStream(rs, std::cout);


			Poco::XML::InputSource src(rs);

			ForecastParser handler;
			handler.Forecast += Poco::delegate(this, &ForecastSensor::onData);

			Poco::XML::SAXParser parser;
			parser.setContentHandler(&handler);

			try {
				std::cout << "parse" << std::endl;
				parser.parse(&src);
			} catch (Poco::Exception& e) {
				std::cerr << e.displayText() << std::endl;
			}
			handler.Forecast -= Poco::delegate(this, &ForecastSensor::onData);

		} catch (Poco::Exception& exc) {
			std::cerr << exc.displayText() << std::endl;
		}

	}
Example #7
0
bool doRequest(Poco::Net::HTTPClientSession & session, Poco::Net::HTTPRequest & request, Poco::Net::HTTPResponse & response)
{
	session.sendRequest(request);
	std::istream& rs = session.receiveResponse(response);
	std::cout << response.getStatus() << " " << response.getReason() << std::endl;
	if (response.getStatus() != Poco::Net::HTTPResponse::HTTP_UNAUTHORIZED)
	{
		//std::ofstream ofs("Poco_banner.jpg", std::fstream::binary);
		//StreamCopier::copyStream(rs, ofs);
		// Print to standard output
		cout << "RECEIVED:" << endl;
		std::copy(std::istream_iterator<char>(rs), std::istream_iterator<char>(), std::ostream_iterator<char>(std::cout) );
		cout << endl;
		return true;
	}
	else
	{
		//it went wrong ?
		return false;
	}
}
std::vector <std::string> ServerAccess::getScreenIds()
{
    std::vector<std::string> screenIds;
    Poco::URI uri(server_address + "/api/screens");
    //std::string url = server_address + "/api/screens";
    Poco::Net::HTTPClientSession session(uri.getHost(), uri.getPort());

    //prepare path
    std::string path(uri.getPath());

    //prepare and send request
    Poco::Net::HTTPRequest req(Poco::Net::HTTPRequest::HTTP_GET, path, Poco::Net::HTTPMessage::HTTP_1_1);
    session.sendRequest(req);

    //get response
    Poco::Net::HTTPResponse res;

    std::cout << res.getStatus() << res.getReason() << std::endl;

    std::istream &is = session.receiveResponse(res);
    std::string response_body;
    Poco::StreamCopier::copyToString(is, response_body);

    //Parsing
    rapidjson::Document d;
    d.Parse(response_body.c_str());

    assert(d.IsObject());

    assert(d.HasMember("screens"));
    {
        const rapidjson::Value& screens = d["screens"];
        assert(screens.IsArray());
        for (rapidjson::Value::ConstValueIterator itr = screens.Begin(); itr != screens.End(); ++itr) {
            screenIds.push_back(itr->GetString());
        }
    }

    return screenIds;
}
Example #9
0
    //TODO: This MUST be done over TLS to protect the token.
    bool getAccessToken(const std::string& authorizationCode) override
    {
        std::string url = _tokenEndPoint
                        + "?client_id=" + _clientId
                        + "&client_secret=" + _clientSecret
                        + "&grant_type=authorization_code"
                        + "&code=" + authorizationCode;
                        // + "&redirect_uri="

        Poco::URI uri(url);
        Poco::Net::HTTPClientSession session(uri.getHost(), uri.getPort());
        Poco::Net::HTTPRequest request(Poco::Net::HTTPRequest::HTTP_POST, url, Poco::Net::HTTPMessage::HTTP_1_1);
        Poco::Net::HTTPResponse response;
        session.sendRequest(request);
        std::istream& rs = session.receiveResponse(response);
        Log::info() << "Status: " <<  response.getStatus() << " " << response.getReason() << Log::end;
        std::string reply(std::istreambuf_iterator<char>(rs), {});
        Log::info("Response: " + reply);
        //TODO: Parse the token.

        return true;
    }
Example #10
0
bool doRequest(Poco::Net::HTTPClientSession & session, string requestBody, Poco::Net::HTTPRequest & request, Poco::Net::HTTPResponse & response)
{
	session.setKeepAlive(true);
	request.setKeepAlive(true);
	request.setContentType("application/x-www-form-urlencoded");
	request.setContentLength(requestBody.length());

	session.sendRequest(request) << requestBody;
	std::istream& rs = session.receiveResponse(response);
	std::cout << response.getStatus() << " " << response.getReason() << std::endl;
	if (response.getStatus() != Poco::Net::HTTPResponse::HTTP_UNAUTHORIZED)
	{
		
		//std::ofstream ofs("Poco_banner.jpg", std::fstream::binary);
		//StreamCopier::copyStream(rs, ofs);
		// Print to standard output
		cout << "RECEIVED:" << endl;
		//std::copy(std::istream_iterator<char>(rs), std::istream_iterator<char>(), std::ostream_iterator<char>(std::cout));
		string received = "";
		string temp;
		//rec << rs.rdbuf();
		
		while (std::getline(rs, temp))
		{
			received += temp + "\n";
		}

		cout << received << endl;
		return true;
	}
	else
	{
		//it went wrong ?
		return false;
	}
}
void
Engine::setUriEngine(const std::string& uri, const ProtocolInfo& protInfo)
{
    Poco::URI uriParsed(uri);
    _playlist.clear();
    _duration = 0.0;
    if (protInfo.getMimeString() == Mime::PLAYLIST) {
        LOG(upnpav, debug, "renderer engine got playlist");

        Poco::Net::HTTPClientSession session(uriParsed.getHost(), uriParsed.getPort());

        Poco::Net::HTTPRequest request("GET", uriParsed.getPath());
        session.sendRequest(request);
        std::stringstream requestHeader;
        request.write(requestHeader);
        LOG(upnpav, debug, "request header:\n" + requestHeader.str());

        Poco::Net::HTTPResponse response;
        std::istream& istr = session.receiveResponse(response);

        LOG(upnpav, information, "HTTP " + Poco::NumberFormatter::format(response.getStatus()) + " " + response.getReason());
        std::stringstream responseHeader;
        response.write(responseHeader);
        LOG(upnpav, debug, "response header:\n" + responseHeader.str());

        std::string line;
        while(std::getline(istr, line)) {
            _playlist.push_back(line);
        }
        setAtomicUriEngine(_playlist[_trackNumberInPlaylist]);
    }
    else if (preferStdStream()) {
        Poco::Net::HTTPClientSession session(uriParsed.getHost(), uriParsed.getPort());
        Poco::Net::HTTPRequest request("GET", uriParsed.getPath());
        session.sendRequest(request);
        std::stringstream requestHeader;
        request.write(requestHeader);
        LOG(upnpav, debug, "request header:\n" + requestHeader.str());

        Poco::Net::HTTPResponse response;
        std::istream& istr = session.receiveResponse(response);

        LOG(upnpav, information, "HTTP " + Poco::NumberFormatter::format(response.getStatus()) + " " + response.getReason());
        std::stringstream responseHeader;
        response.write(responseHeader);
        LOG(upnpav, debug, "response header:\n" + responseHeader.str());
        setUri(istr, protInfo);
    }
    else {
        setAtomicUriEngine(uri, protInfo);
    }
}
Example #12
0
/**
 * @param filenames : List of files to search
 * @param exts : List of extensions to check against
 * @return list of archive locations
 */
std::string SNSDataArchive::getArchivePath(const std::set<std::string>& filenames, const std::vector<std::string>& exts) const
{
  std::set<std::string>::const_iterator iter = filenames.begin();
  std::string filename = *iter;

  //ICAT4 web service take upper case filename such as HYSA_2662
  std::transform(filename.begin(),filename.end(),filename.begin(),toupper);

  std::vector<std::string>::const_iterator iter2 = exts.begin();
  for(; iter2!=exts.end(); ++iter2)
  {
    g_log.debug() << *iter2 << ";";
  }
  g_log.debug()  << "\n";

  std::string baseURL("http://icat.sns.gov:8080/icat-rest-ws/datafile/filename/");

  std::string URL(baseURL + filename);
  g_log.debug() << "URL: " << URL << "\n";

  Poco::URI uri(URL);
  std::string path(uri.getPathAndQuery());

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

  Poco::Net::HTTPResponse res;
  std::istream& rs = session.receiveResponse(res);
  g_log.debug() << "res.getStatus(): " << res.getStatus() << "\n";

  // Create a DOM document from the response.
  Poco::XML::DOMParser parser;
  Poco::XML::InputSource source(rs);
  Poco::AutoPtr<Poco::XML::Document> pDoc = parser.parse(&source);

  std::vector<std::string> locations;

  // If everything went fine, return the XML document.
  // Otherwise look for an error message in the XML document.
  if (res.getStatus() == Poco::Net::HTTPResponse::HTTP_OK)
  {
    std::string location;
    Poco::AutoPtr<Poco::XML::NodeList> pList = pDoc->getElementsByTagName("location");
    for(unsigned long i = 0 ; i < pList->length(); i++)
    {
      location = pList->item(i)->innerText();
      g_log.debug() << "location: " << location << "\n";
      locations.push_back(location);
    }
  }
  else
  {
    std::string error(res.getReason());
    throw Poco::ApplicationException("HTTPRequest Error", error);
  }

  std::vector<std::string>::const_iterator ext = exts.begin();
  for (; ext != exts.end(); ++ext)
  {
    std::string datafile = filename + *ext;
    std::vector<std::string>::const_iterator iter = locations.begin();
    for(; iter!=locations.end(); ++iter)
    {
      if (boost::algorithm::ends_with((*iter), datafile))
      {
        return *iter;
      } // end if
    } // end for iter

  }  // end for ext
  return "";
}
			void EventConnection::internalProcess()
			{
				try
				{
					Poco::URI uri(_eventReceiverURI);

                    // prepare session
					Poco::Net::HTTPClientSession session(uri.getHost(), uri.getPort());
        		    session.setKeepAlive(false);

					if(_soapAction.find("ErrorEvent") != std::string::npos)
					{
						session.setTimeout(Poco::Timespan(10,0,0,0,0));
					}
                
                    // prepare request
                    std::string path (uri.getPathAndQuery());
				    if(path.empty())
				    {
                        path = "/";
				    }
					Poco::Net::HTTPRequest request(Poco::Net::HTTPRequest::HTTP_POST, path, Poco::Net::HTTPMessage::HTTP_1_1);
				    request.setContentLength(_content.length());
					request.setContentType("text/xml; charset=utf-8");
					request.setKeepAlive(false);

                    request.set("SOAPAction","\"" + _soapAction + "\"");

                    // send request
                    std::ostream& outStream = session.sendRequest(request);
                    outStream << _content;

                    // get response
                    Poco::Net::HTTPResponse response;
                    std::istream& inStream = session.receiveResponse(response);

					std::ostringstream responseContentStream;
					Poco::StreamCopier::copyStream(inStream, responseContentStream);
					_responseContent = responseContentStream.str();

					if(response.getStatus() != 200)
					{
						std::ostringstream strout;
						strout << "EventConnection HTTP-Error: " << response.getStatus() << " - " << response.getReason();
						_errorMessage = strout.str();
						_error = true;
					}

					while(session.connected())
					{
						session.abort();
					}

					_finished = true;
				}
                catch (std::exception e)
				{
					std::ostringstream strout;
					strout << "EventConnection Exception: " << e.what();
					_errorMessage = strout.str();
					_error = true;
					_finished = true;
				}


			}