void HTTPServerTest::testLoleafletPost()
{
    std::unique_ptr<Poco::Net::HTTPClientSession> session(helpers::createSession(_uri));

    Poco::Net::HTTPRequest request(Poco::Net::HTTPRequest::HTTP_POST, "/loleaflet/dist/loleaflet.html");
    Poco::Net::HTMLForm form;
    form.set("access_token", "2222222222");
    form.prepareSubmit(request);
    std::ostream& ostr = session->sendRequest(request);
    form.write(ostr);

    Poco::Net::HTTPResponse response;
    std::istream& rs = session->receiveResponse(response);
    CPPUNIT_ASSERT_EQUAL(Poco::Net::HTTPResponse::HTTP_OK, response.getStatus());

    std::string html;
    Poco::StreamCopier::copyToString(rs, html);

    CPPUNIT_ASSERT(html.find(form["access_token"]) != std::string::npos);
    CPPUNIT_ASSERT(html.find(_uri.getHost()) != std::string::npos);
}
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;
}
Exemple #3
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;
    }
void HTTPServerTest::testScriptsAndLinksPost()
{
    std::unique_ptr<Poco::Net::HTTPClientSession> session(helpers::createSession(_uri));

    Poco::Net::HTTPRequest request(Poco::Net::HTTPRequest::HTTP_POST, "/loleaflet/dist/loleaflet.html");
    std::string body;
    request.setContentLength((int) body.length());
    session->sendRequest(request) << body;

    Poco::Net::HTTPResponse response;
    std::istream& rs = session->receiveResponse(response);
    CPPUNIT_ASSERT_EQUAL(Poco::Net::HTTPResponse::HTTP_OK, response.getStatus());

    std::string html;
    Poco::StreamCopier::copyToString(rs, html);

    Poco::RegularExpression script("<script.*?src=\"(.*?)\"");
    assertHTTPFilesExist(_uri, script, html, "application/javascript");

    Poco::RegularExpression link("<link.*?href=\"(.*?)\"");
    assertHTTPFilesExist(_uri, link, html);
}
    /**
     * Downloads datafiles from the archives, and saves to the users save default directory.
     * @param URL :: The URL of the file to download.
     * @param fileName :: The name of the file to save to disk.
     * @return The full path to the saved file.
     */
    std::string CatalogDownloadDataFiles::doDownloadandSavetoLocalDrive(const std::string& URL,const std::string& fileName)
    {
      std::string pathToDownloadedDatafile;

      clock_t start;

      try
      {
        Poco::URI uri(URL);

        std::string path(uri.getPathAndQuery());
        start=clock();

        Poco::SharedPtr<Poco::Net::InvalidCertificateHandler> certificateHandler = new Poco::Net::AcceptCertificateHandler(true);
        // Currently do not use any means of authentication. This should be updated IDS has signed certificate.
        const Poco::Net::Context::Ptr context = new Poco::Net::Context(Poco::Net::Context::CLIENT_USE, "", "", "", Poco::Net::Context::VERIFY_NONE);
        // Create a singleton for holding the default context. E.g. any future requests to publish are made to this certificate and context.
        Poco::Net::SSLManager::instance().initializeClient(NULL, certificateHandler,context);
        Poco::Net::HTTPSClientSession session(uri.getHost(), uri.getPort(), context);

        Poco::Net::HTTPRequest request(Poco::Net::HTTPRequest::HTTP_GET, path, Poco::Net::HTTPMessage::HTTP_1_1);
        session.sendRequest(request);

        // Close the request by requesting a response.
        Poco::Net::HTTPResponse response;
        // Store the response for use IF an error occurs (e.g. 404).
        std::istream& responseStream = session.receiveResponse(response);

        // Obtain the status returned by the server to verify if it was a success.
        Poco::Net::HTTPResponse::HTTPStatus HTTPStatus = response.getStatus();
        // The error message returned by the IDS (if one exists).
        std::string IDSError = CatalogAlgorithmHelper().getIDSError(HTTPStatus, responseStream);
        // Cancel the algorithm and display the message if it exists.
        if(!IDSError.empty())
        {
          // As an error occurred we must cancel the algorithm to prevent success message.
          this->cancel();
          // Output an appropriate error message from the JSON object returned by the IDS.
          g_log.error(IDSError);
          return "";
        }

        // Save the file to local disk if no errors occurred on the IDS.
        pathToDownloadedDatafile = saveFiletoDisk(responseStream,fileName);

        clock_t end=clock();
        float diff = float(end - start)/CLOCKS_PER_SEC;
        g_log.information()<<"Time taken to download file "<< fileName<<" is "<<std::fixed << std::setprecision(2) << diff <<" seconds" << std::endl;

      }
      catch(Poco::Net::SSLException& error)
      {
        throw std::runtime_error(error.displayText());
      }
      // A strange error occurs (what returns: {I/O error}, while message returns: { 9: The BIO reported an error }.
      // This bug has been fixed in POCO 1.4 and is noted - http://sourceforge.net/p/poco/bugs/403/
      // I have opted to catch the exception and do nothing as this allows the load/download functionality to work.
      // However, the port the user used to download the file will be left open.
      catch(Poco::Exception&) {}

      return pathToDownloadedDatafile;
    }
/**
 * @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;
				}


			}