Ejemplo n.º 1
0
void GenericFileHandler::handleRequest(Poco::Net::HTTPServerRequest & req, Poco::Net::HTTPServerResponse & resp) {

	std::ifstream file;

	try {
		file.open(fileName.c_str(), std::ifstream::in);
	} catch (...) {
	}

	if (!file.is_open()) {
		resp.setStatus(Poco::Net::HTTPResponse::HTTP_NOT_FOUND);
		resp.send();
		return;
	}

	std::string wsdl;
	while (!file.eof()) {
		std::string tmp;
		std::getline(file, tmp);
		wsdl += tmp;
	}
	file.close();

	resp.setStatus(Poco::Net::HTTPResponse::HTTP_OK);
	resp.setContentType("application/xml");
	resp.setChunkedTransferEncoding(false);
	resp.setContentLength(wsdl.length());

	std::ostream & out = resp.send();
	out << wsdl << std::flush;
}
Ejemplo n.º 2
0
 void ShowDevices::operator()(const PlaceHolders &&, ServerRequest &request,
                              Poco::Net::HTTPServerResponse &response) {
     response.setStatus(Poco::Net::HTTPResponse::HTTP_OK);
     BOOST_LOG_TRIVIAL(info) << "ShowDevices";
     const auto &producer = MediaTypeProducerFactory::getMediaType(request.getContentType());
     producer.produce(response.send(), ZDevicesPT(singletons.getZDevices()));
 }
Ejemplo n.º 3
0
        void FixedPathHandler::handleRequest(Poco::Net::HTTPServerRequest &, Poco::Net::HTTPServerResponse &response) {
            Poco::Net::MediaType mediaType("text", "plain");
            response.setContentType(mediaType);
            response.setStatus(Poco::Net::HTTPResponse::HTTP_OK);

            std::ostream &stream = response.send();
            stream << "value";
        }
void server::BasicHandler::handleRequest( Poco::Net::HTTPServerRequest & request,
					  Poco::Net::HTTPServerResponse & response) {
  std::cout << "Received Request!" << std::endl;

  response.setContentType("text/txt");
  response.setStatus(Poco::Net::HTTPResponse::HTTP_OK);
  std::ostream& os = response.send();
  os << "12345 this is all pretty weird" << std::endl;
}
Ejemplo n.º 5
0
void DenyRequestHandler::handleRequest(Poco::Net::HTTPServerRequest& request, Poco::Net::HTTPServerResponse& response)
{
  Poco::Logger& logger = Poco::Logger::get("mq.web.access");

  std::string ip = request.clientAddress().host().toString();
  logger.warning(Poco::Logger::format("$0 : HTTP_FORBIDDEN", ip));

  response.setStatus(Poco::Net::HTTPResponse::HTTP_FORBIDDEN);
  response.send();
}
Ejemplo n.º 6
0
void FileRequestHandler::handleRequest(Poco::Net::HTTPServerRequest& request, Poco::Net::HTTPServerResponse& response)
{
    setContentType(request, response);
    std::ostream& ostr = response.send();
    try {
        Poco::Path basedir = Poco::Util::Application::instance().config().getString("application.dir");
        basedir.append("web");
        basedir.append(request.getURI());
        Poco::FileInputStream fis(basedir.toString());
        Poco::StreamCopier::copyStream(fis, ostr);
        response.setStatus(Poco::Net::HTTPResponse::HTTPStatus::HTTP_OK);
    }
    catch (Poco::Exception& ex) {
        response.setStatus(Poco::Net::HTTPResponse::HTTPStatus::HTTP_NOT_FOUND);
        ostr << ex.displayText();
        _logger.error("Request failed: %s: %s", request.getURI(), ex.displayText());
    }

}
Ejemplo n.º 7
0
void
BufferHandler::handleRequest(Poco::Net::HTTPServerRequest &req, Poco::Net::HTTPServerResponse &resp)
{
    prepareResponse(resp);
    resp.set("ETag", etag);
    resp.set("Cache-Control", "max-age=300, private");

    if (req.get("If-None-Match", "") == etag) {
        // ETag matched. No content to send;
        resp.setStatus(Poco::Net::HTTPResponse::HTTP_NOT_MODIFIED);
        resp.setReason("Not Modified");

        resp.send().flush();
        return;
    }

    resp.setStatus(Poco::Net::HTTPResponse::HTTP_OK);
    resp.setContentType(contentType);
    resp.setContentLength(bufferLen);

    std::ostream & out = resp.send();
    out.write(reinterpret_cast<const char*>(buffer), bufferLen);
    out.flush();
};
Ejemplo n.º 8
0
void RESTHandler::handleRequest(Poco::Net::HTTPServerRequest &request,
                                Poco::Net::HTTPServerResponse &response) {
    if (verbose) {
        std::clog << "HTTP request " << request.getURI() << std::endl;
        std::clog << "Context id: " << client.context_id() << std::endl;
    }
    zmqpp::message msg, reply;
    /// Connect to broker if not connected
    client.connect(broker);
    Poco::URI url(request.getURI());
    Poco::Net::HTMLForm form(request);
    /// Filter by black list
    if (black_list.find(url.getPath()) != black_list.end()) {
        return error_black_list(response);
    }
    if (!build_message(request, form, url, msg)) {
        return error_parse(response);
    }
    if (!client.send_request(msg, reply, (form.has("timeout") ? std::stoi(form.get("timeout")) : timeout))) {
        return error_timeout(response);
    }
    /// Render response
    response.setStatus(Poco::Net::HTTPServerResponse::HTTPStatus::HTTP_OK);
    if (form.get("type", "json") == "json") {
        /// JSON in single line (FastWriter)
        std::string jsonp_callback = form.get("jsonp", form.get("callback", ""));
        Json::Value packet(Json::ValueType::arrayValue);
        response.setContentType("application/json");
        std::ostream &out = response.send();
        if (!jsonp_callback.empty())
            out << jsonp_callback << "(";
        for (size_t part = 0; part < reply.parts(); ++part)
            packet.append(reply.get(part));
        auto txt = writer.write(packet);
        if (txt[txt.size() - 1] == '\n') // Cheat for EOL in serialization
            txt = txt.substr(0, txt.size() - 1);
        out << txt << (!jsonp_callback.empty() ? ")" : "") << std::flush;
    } else {
        /// Plain text wihtout delimiters
        response.setContentType("text/plain");
        std::ostream &out = response.send();
        for (size_t part = 0; part < reply.parts(); ++part)
            out.write((char *) reply.raw_data(part), reply.size(part));
        out.flush();
    }


}
Ejemplo n.º 9
0
   /* virtual*/ void handleRequest(Poco::Net::HTTPServerRequest &req, Poco::Net::HTTPServerResponse &resp)
    {
        resp.setStatus(Poco::Net::HTTPResponse::HTTP_OK);       //Sets the HTTP status code, Why?
        resp.setContentType("text/html");                       // set the content type of the message

        ostream& out = resp.send();        //Returns an output stream for sending the response body. The returned stream is valid until the response object is destroyed.
        out << "<h1>Hello world!</h1>"     //Body of the repsonse
       // << "<p>Count: "  << ++count         << "</p>"
        << "<p>Host: "   << req.getHost()   << "</p>"       //Returns the value of the Host header field.
        << "<p>Method: " << req.getMethod() << "</p>"
        << "<p>URI: "    << req.getURI() << "</p>";
        out.flush();
        cout << endl
        //<< "Response sent for count=" << count
        << " Response sent for URI=" << req.getURI() << endl;
    }
Ejemplo n.º 10
0
void AppRequestHandler::handleRequest(Poco::Net::HTTPServerRequest& request, Poco::Net::HTTPServerResponse& response)
{
	// Check for the favicon.ico request, we don't have one for now,
	// so set status code to HTTP_NOT_FOUND
	if ( request.getURI().compare("/favicon.ico") == 0 )
	{
		response.setStatus(Poco::Net::HTTPResponse::HTTP_NOT_FOUND);
		response.send();
		return;
	}

	std::string lastModifiedHeader = request.get("If-Modified-Since", "");

	Poco::URI uri(request.getURI());

	Poco::Util::Application& app = Poco::Util::Application::instance();
	std::string staticPathname = app.config().getString("mq.web.app", "");
	if ( staticPathname.empty() )
	{
		Poco::Logger& logger = Poco::Logger::get("mq.web");
		logger.error("mq.web.app property not defined. Check your configuration.");
		response.setStatus(Poco::Net::HTTPResponse::HTTP_INTERNAL_SERVER_ERROR);
		response.send();
		return;
	}

	Poco::Path staticPath(staticPathname);
	staticPath.makeDirectory();

	std::vector<std::string> uriPathSegments;
	uri.getPathSegments(uriPathSegments);
	std::vector<std::string>::iterator it = uriPathSegments.begin();
	it++;
	for(; it != uriPathSegments.end(); ++it)
	{
		staticPath.append(*it);
	}
	if (staticPath.isDirectory())
	{
		staticPath.append("index.html");
	}

	Poco::File staticFile(staticPath);

	Poco::Logger& logger = Poco::Logger::get("mq.web.access");
	if ( staticFile.exists() )
	{
		if ( !lastModifiedHeader.empty() )
		{
			Poco::DateTime lastModifiedDate;
			int timeZoneDifferential = 0;
			if ( Poco::DateTimeParser::tryParse(Poco::DateTimeFormat::HTTP_FORMAT, lastModifiedHeader, lastModifiedDate, timeZoneDifferential) )
			{
				if ( staticFile.getLastModified() <= lastModifiedDate.timestamp() )
				{
					logger.information(Poco::Logger::format("$0 : HTTP_NOT_MODIFIED", staticPath.toString()));
					response.setStatus(Poco::Net::HTTPResponse::HTTP_NOT_MODIFIED);
					response.send();
					return;
				}
			}
		}

		logger.information(Poco::Logger::format("$0 : HTTP_OK", staticPath.toString()));

		std::string mimeType;
		if ( staticPath.getExtension().compare("gif") == 0 )
		{
			mimeType = "image/gif";
		}
		else if ( staticPath.getExtension().compare("css") == 0 )
		{
			mimeType = "text/css";
		}
		else if ( staticPath.getExtension().compare("html") == 0 || staticPath.getExtension().compare("htm") == 0)
		{
			mimeType = "text/html";
		}
		else if ( staticPath.getExtension().compare("js") == 0 )
		{
			mimeType = "text/javascript";
		}
		else if ( staticPath.getExtension().compare("png") == 0 )
		{
			mimeType = "image/png";
		}
		else if ( staticPath.getExtension().compare("jpg") == 0 || staticPath.getExtension().compare("jpeg") == 0)
		{
			mimeType = "image/jpeg";
		}

		try
		{
			response.sendFile(staticPath.toString(), mimeType);
		}
		catch(Poco::FileNotFoundException&)
		{
			// We can't get here normally ... but you never know :)
			response.setStatusAndReason(Poco::Net::HTTPResponse::HTTP_NOT_FOUND, Poco::Logger::format("Can't find file $0", staticPath.toString()));
		}
		catch(Poco::OpenFileException&)
		{
			response.setStatusAndReason(Poco::Net::HTTPResponse::HTTP_INTERNAL_SERVER_ERROR, Poco::Logger::format("Can't open file $0", staticPath.toString()));
		}
		return;
	}

	logger.error(Poco::Logger::format("$0 : HTTP_NOT_FOUND", staticFile.path()));
	response.setStatus(Poco::Net::HTTPResponse::HTTP_NOT_FOUND);
	response.send();
}
Ejemplo n.º 11
0
void
RemoveByAttributesHandler::handleRequest(Poco::Net::HTTPServerRequest &req, Poco::Net::HTTPServerResponse &resp)
{
    prepareApiResponse(resp);

    if (req.getMethod() != "POST") {
        resp.setStatus(Poco::Net::HTTPResponse::HTTP_BAD_REQUEST);
        resp.setReason("Bad Request");

        Error error("Only POST requests are supported");

        std::ostream & out = resp.send();
        out << error;
        out.flush();
        return;
    }


    auto job = std::make_shared<Job>(Job::Type::REMOVE_BY_ATTRIBUTES);
    try {
        // read the whole request body into memory
        std::stringstream bodystream;
        bodystream << req.stream().rdbuf();

        // parse received json into the job object
        job->fromString( bodystream.str() );
    }
    catch (std::exception &e) {
        resp.setStatus(Poco::Net::HTTPResponse::HTTP_BAD_REQUEST);
        resp.setReason("Bad Request");
        
        Error error(e.what());
        poco_warning(logger, e.what());

        std::ostream & out = resp.send();
        out << error;
        out.flush();
        return;
    }

    // return 404 if layer does not exist
    try {
        auto layer = configuration->getLayer(job->getLayerName());
    }
    catch (ConfigurationError) {
        // layer does not exist
        resp.setStatus(Poco::Net::HTTPResponse::HTTP_NOT_FOUND);
        resp.setReason("Not Found");
        
        std::stringstream msgstream;
        msgstream << "Layer \"" << job->getLayerName() << "\" does not exist";

        Error error(msgstream.str());
        poco_warning(logger, error.getMessage());

        std::ostream & out = resp.send();
        out << error;
        out.flush();
        return;
    }


    if (auto jobstorage = jobs.lock()) {
        poco_debug(logger, "pushing job to jobstorage");
        jobstorage->push(job);
    }
    else {
        resp.setStatus(Poco::Net::HTTPResponse::HTTP_INTERNAL_SERVER_ERROR);
        resp.setReason("Internal Server Error");
        
        const char * emsg = "Could not get a lock on jobstorage";
        Error error(emsg);
        poco_error(logger, emsg);

        std::ostream & out = resp.send();
        out << error;
        out.flush();
        return;
    }

    resp.setStatus(Poco::Net::HTTPResponse::HTTP_OK);
    std::ostream & out = resp.send();
    out << *job;
    out.flush();
};