Пример #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;
}
Пример #2
0
    void handleRequest(Poco::Net::HTTPServerRequest &request, Poco::Net::HTTPServerResponse &response)
    {
        if(request.getURI()=="/command") {
            EachInputValue(request, [&](const char *id, const char *command){
                wdmEventData tmp = {std::atoi(id), command};
                wdmSystem::getInstance()->addEvent(tmp);
            });
            response.setContentType("text/plain");
            response.setContentLength(2);
            std::ostream &ostr = response.send();
            ostr.write("ok", 3);
        }
        else if(request.getURI()=="/data") {
            std::vector<wdmID> nodes;
            nodes.push_back(_wdmGetRootNode()->getID());
            EachNodeValue(request, [&](const char *id){
                nodes.push_back(std::atoi(id));
            });

            wdmString json;
            wdmJSONRequest request = {false, false, &json, nodes.empty() ? NULL : &nodes[0], (uint32_t)nodes.size()};
            wdmSystem::getInstance()->requestJSON(request);
            while(!request.done) { Poco::Thread::sleep(2); }
            if(request.canceled) { json="[]"; }

            response.setContentType("application/json");
            response.setContentLength(json.size());
            std::ostream &ostr = response.send();
            ostr.write(&json[0], json.size());
        }
    }
Пример #3
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();
    }


}
Пример #4
0
		static void streamFile(Poco::Net::HTTPServerResponse & response, std::string file, std::string mime) {
			response.setContentType(mime);
			response.setChunkedTransferEncoding(true);
			std::ostream & o = response.send();
			std::ifstream docf(file.c_str());
			Poco::StreamCopier::copyStream(docf, o);
		}
Пример #5
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()));
 }
Пример #6
0
void TimeHandler::handleRequest(Poco::Net::HTTPServerRequest& request, Poco::Net::HTTPServerResponse& response)
{
    response.setChunkedTransferEncoding(true);
    response.setContentType("text/html");

    Poco::Net::HTMLForm form(request, request.stream());
    std::ostream& responseStream = response.send();
    responseStream << "";
    responseStream << "\n";
    responseStream << "";
    responseStream << "\n";
    responseStream << "\n";
    responseStream << "";
#line 6 "/ws/poco-1.3/PageCompiler/samples/HTTPTimeServer/src/TimeHandler.cpsp"

    Poco::DateTime now;
    std::string dt(Poco::DateTimeFormatter::format(now, "%W, %e %b %y %H:%M:%S %Z"));
    responseStream << "\n";
    responseStream << "<html>\n";
    responseStream << "<head>\n";
    responseStream << "<title>HTTPTimeServer powered by POCO C++ Libraries and PageCompiler</title>\n";
    responseStream << "<meta http-equiv=\"refresh\" content=\"1\">\n";
    responseStream << "</head>\n";
    responseStream << "<body>\n";
    responseStream << "<p style=\"text-align: center; font-size: 48px;\">";
#line 16 "/ws/poco-1.3/PageCompiler/samples/HTTPTimeServer/src/TimeHandler.cpsp"
    responseStream << ( dt );
    responseStream << "</p>\n";
    responseStream << "</body>\n";
    responseStream << "</html>\n";
    responseStream << "";
}
Пример #7
0
	void handleRequest(Poco::Net::HTTPServerRequest& request, Poco::Net::HTTPServerResponse& response) 
	{ 
		response.setContentType("text/xml");
		std::ostream& ostr = response.send();
		redis r;
		r.arg("zrange");
		r.arg("history");
		r.arg("0");
		r.arg("-1");
		std::list<std::string> result;
		r.exec_array(result);

		std::string rss;
		rss =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
"<rss version=\"2.0\">"
"  <channel>"
"    <title>rss</title>"
"    <link>http://localhost/</link>"
"    <description>merge rss feeds</description>";

		for (std::list<std::string>::reverse_iterator it = result.rbegin(), end = result.rend(); it != end; ++it)
		{
			r.arg("hget");
			r.arg("items");
			r.arg(*it);
			rss += r.exec_string().second;
		}
		rss += "</channel></rss>";
		ostr << rss << std::flush;
	} 
Пример #8
0
void GetHighScoreDeleteForm::generateResponse(Poco::Net::HTTPServerRequest& inRequest, Poco::Net::HTTPServerResponse& outResponse)
{
    std::string body;
    ReadEntireFile("html/delete.html", body);
    outResponse.setContentLength(body.size());
    outResponse.send() << body;
}
void ConsoleRequestHandler::handleRequest(Poco::Net::HTTPServerRequest& request, Poco::Net::HTTPServerResponse& response)
{
	try
	{
		std::string username;
		Poco::OSP::Web::WebSession::Ptr pSession;
		{
			Poco::OSP::ServiceRef::Ptr pWebSessionManagerRef = _pContext->registry().findByName(Poco::OSP::Web::WebSessionManager::SERVICE_NAME);
			if (pWebSessionManagerRef)
			{
				Poco::OSP::Web::WebSessionManager::Ptr pWebSessionManager = pWebSessionManagerRef->castedInstance<Poco::OSP::Web::WebSessionManager>();
				pSession = pWebSessionManager->find(_pContext->thisBundle()->properties().getString("websession.id"), request);
				username = pSession->getValue<std::string>("username", "");
			}
		}	
	
		if (!username.empty())
		{
			Poco::Net::WebSocket webSocket(request, response);
			_pContext->logger().information(Poco::format("Console WebSocket connection established with %s.", request.clientAddress().toString()));
			forwardMessages(webSocket);
		}
		else
		{
			response.setStatusAndReason(Poco::Net::HTTPResponse::HTTP_UNAUTHORIZED);
			response.setContentLength(0);
			response.send();
		}
	}
	catch (Poco::Net::WebSocketException& exc)
	{
		_pContext->logger().log(exc);
		switch (exc.code())
		{
		case Poco::Net::WebSocket::WS_ERR_HANDSHAKE_UNSUPPORTED_VERSION:
			response.set("Sec-WebSocket-Version", Poco::Net::WebSocket::WEBSOCKET_VERSION);
			// fallthrough
		case Poco::Net::WebSocket::WS_ERR_NO_HANDSHAKE:
		case Poco::Net::WebSocket::WS_ERR_HANDSHAKE_NO_VERSION:
		case Poco::Net::WebSocket::WS_ERR_HANDSHAKE_NO_KEY:
			response.setStatusAndReason(Poco::Net::HTTPResponse::HTTP_BAD_REQUEST);
			response.setContentLength(0);
			response.send();
			break;
		}
	}
}
Пример #10
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";
        }
	virtual void handleRequest(Poco::Net::HTTPServerRequest &request, Poco::Net::HTTPServerResponse &response)
	{
		if (request.getURI() == "/name")
		{
			response.setContentType("application/json");
			response.send() << " { \"hanwenfang\"} ";
		}
	}
Пример #12
0
	void process(Poco::Net::HTTPServerRequest& request, Poco::Net::HTTPServerResponse& response, const std::string& path, std::istream& resourceStream, Poco::OSP::Bundle::ConstPtr pBundle)
	{
		std::string content;
		Poco::StreamCopier::copyToString(resourceStream, content);
		std::string dateTime = Poco::DateTimeFormatter::format(Poco::DateTime(), Poco::DateTimeFormat::HTTP_FORMAT);
		Poco::replaceInPlace(content, std::string("$$DATETIME$$"), dateTime);
		response.setContentType("text/html");
		response.send() << content;
	}
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;
}
Пример #14
0
void DefaultRequestHandler(Poco::Net::HTTPServerRequest& request, Poco::Net::HTTPServerResponse& response)
{
  response.setStatusAndReason(Poco::Net::HTTPResponse::HTTP_OK);
  response.setContentType(Poco::Net::MediaType("text/plain"));
  response.setKeepAlive(true);
  auto& os = response.send();

  os << "It Works! " << request.getURI() << std::flush;
}
Пример #15
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();
}
Пример #16
0
void ShowCaptchaPage::handleRequest(Poco::Net::HTTPServerRequest &request, Poco::Net::HTTPServerResponse &response)
{
	m_log->trace("ShowCaptchaPage::handleRequest from "+request.clientAddress().toString());

	std::map<std::string,QueryVar> queryvars;

	CreateQueryVarMap(request,queryvars);

	if(request.getVersion()==Poco::Net::HTTPRequest::HTTP_1_1)
	{
		response.setChunkedTransferEncoding(true);
	}

	std::string content="";
	if(queryvars.find("UUID")!=queryvars.end())
	{
		std::string uuid=(*queryvars.find("UUID")).second.GetData();
		SQLite3DB::Statement st=m_db->Prepare("SELECT MimeType,PuzzleData FROM tblIntroductionPuzzleRequests WHERE UUID=?;");
		st.Bind(0,uuid);
		st.Step();

		if(st.RowReturned())
		{
			std::string mime;
			std::string b64data;
			std::vector<unsigned char> data;

			st.ResultText(0,mime);
			st.ResultText(1,b64data);
			Base64::Decode(b64data,data);

			// mime type should be short and have a / in it - otherwise skip
			if(mime.size()<50 && mime.find('/')!=std::string::npos)
			{
				std::string fname(uuid);
				if(mime=="image/bmp")
				{
					fname+=".bmp";
				}
				else if(mime=="audio/x-wav")
				{
					fname+=".wav";
				}
				response.setContentType(mime);
				response.setContentLength(data.size());
				response.set("Content-Disposition","attachment; filename="+fname);
				content+=std::string(data.begin(),data.end());
			}
		}
	}

	std::ostream &ostr = response.send();
	ostr << content;
}
Пример #17
0
bool Utility::isAuthenticated(Poco::OSP::Web::WebSession::Ptr pSession, Poco::Net::HTTPServerResponse& response)
{
    if (!pSession || !pSession->has("username"))
    {
        response.setStatusAndReason(Poco::Net::HTTPResponse::HTTP_UNAUTHORIZED);
        response.setContentLength(0);
        response.setChunkedTransferEncoding(false);
        response.send();
        return false;
    }
    return true;
}
Пример #18
0
bool Utility::isAuthenticated(Poco::OSP::Web::WebSession::Ptr pSession, const Poco::Net::HTTPServerRequest& request, Poco::Net::HTTPServerResponse& response)
{
	if (!pSession || !pSession->has("username") || request.get("X-XSRF-TOKEN", "") != pSession->csrfToken())
	{
		response.setStatusAndReason(Poco::Net::HTTPResponse::HTTP_UNAUTHORIZED);
		response.setContentLength(0);
		response.setChunkedTransferEncoding(false);
		response.send();
		return false;
	}
	return true;
}
Пример #19
0
void LoggingHandler::displayMessages(const std::vector<Poco::Message>& msg, int offset, int numEntries, std::size_t maxEntries, Poco::Net::HTTPServerResponse& response)
{
	std::ostream& out = response.send();
	out << "<html><head><title>POCO Logging Server</title>";
	out << "<link rel=\"stylesheet\" href=\"css/styles.css\" type=\"text/css\"/>";
	//out << "<link rel=\"alternate\" type=\"application/rss+xml\" title=\"RSS\" href=\"logs/LoggingServer.rss\" />";
	out << "</head>";
	out << "<body><div class=\"header\">";
	out << "<h1 class=\"software\">POCO Logging Server</h1>";
	out << "<h1 class=\"view\">Messages</h1></div>";
	out << "<div class=\"body\">";
	writeTable(msg, offset, numEntries, maxEntries, out);
	out << "</div>";
	out << "<div class=\"nav\"><a href=\"/\">Overview</a> | <a href=\"about.html\">About</a> | <a href=\"docs.html\">Documentation</a></div><p class=\"footer\">POCO Logging Server 1.0<br>Copyright &copy 2007, <a href=\"http://www.appinf.com\">Applied Informatics Software Engineering GmbH.</p></div></body></html>";
}
Пример #20
0
 // Define handler
 virtual void handleRequest(
   Poco::Net::HTTPServerRequest& request,
   Poco::Net::HTTPServerResponse& response) {
   {
     response.setChunkedTransferEncoding(true);
     response.setContentType("text/html");
     std::ostream& ostr = response.send();
     ostr << "<html><head><title>"
          << "My 1st POCO HTTP Server"
          << "</title></head>"
          << "<body><h1>"
          << _helloMsg
          << "</h1></body></html>";
   }
 }
Пример #21
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();
};
Пример #22
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;
    }
Пример #23
0
void LoggingHandler::handleRequest(Poco::Net::HTTPServerRequest& request, Poco::Net::HTTPServerResponse& response)
{
	bool reauth = true;
	if (request.hasCredentials())
	{
		std::string cred;
		std::string scheme;
		try
		{
			Poco::Net::HTTPBasicCredentials cred(request);
			std::string user = cred.getUsername();
			std::istringstream istr(cred.getPassword(), std::ios::binary);
			Poco::MD5Engine md5;
			Poco::DigestOutputStream dos(md5);
			Poco::StreamCopier::copyStream(istr, dos);
			dos.close();
			std::string pwd = Poco::DigestEngine::digestToHex(md5.digest());
			reauth = (pwd != _pwdHash || _user != user);
		}
		catch (...)
		{
			reauth = true;
		}
	}
	if (reauth)
	{
		response.requireAuthentication(TITLE);
		response.send();
		return;
	}
	Poco::Net::HTMLForm form(request);
	std::string offsetStr;
	Poco::Net::NameValueCollection::ConstIterator it = form.find(OFFSET);
	if (it != form.end())
		offsetStr = it->second;
	int offset(0);
	Poco::NumberParser::tryParse(offsetStr, offset);
	std::string numEntriesStr;
	it = form.find(NUMENTRIES);
	if (it != form.end())
		numEntriesStr = it->second;
	int numEntries = DEFAULT_NUMENTRIES;
	Poco::NumberParser::tryParse(numEntriesStr, numEntries);
	std::vector<Poco::Message> messages;
	_channel.getMessages(messages, offset, numEntries);
	displayMessages(messages, offset, numEntries, _channel.getCurrentSize(), response);
}
Пример #24
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());
    }

}
Пример #25
0
void PostHightScore::generateResponse(Poco::Net::HTTPServerRequest& inRequest,
                                      Poco::Net::HTTPServerResponse& outResponse)
{
    std::string requestBody;
    inRequest.stream() >> requestBody;

    Args args;
    GetArgs(requestBody, args);

    std::string name = URIDecode(GetArg(args, "name"));
    const std::string & score = GetArg(args, "score");

    Statement insert(getSession());
    insert << "INSERT INTO HighScores VALUES(NULL, strftime('%s', 'now'), ?, ?)", use(name), use(score);
    insert.execute();

    // Return an URL instead of a HTML page.
    // This is because the client is the JavaScript application in this case.
    std::string body = ResourceManager::Instance().getResourceLocation(GetResourceId());
    outResponse.setContentLength(body.size());
    outResponse.send() << body;
}
Пример #26
0
void DeleteHighScore::generateResponse(Poco::Net::HTTPServerRequest& inRequest,
                                       Poco::Net::HTTPServerResponse& outResponse)
{
    std::string requestBody;
    inRequest.stream() >> requestBody;

    GetLogger().information("Request body is: " + requestBody);

    std::string sql = Poco::replace<std::string>("DELETE FROM HighScores WHERE {{args}}",
                                                 "{{args}}",
                                                 Args2String(GetArgs(requestBody)));

    GetLogger().information("SQL statement is: " + sql);

    Statement insert(getSession());
    insert << sql;
    insert.execute();

    // Return a message indicating success.
    std::string body = "Succesfully performed the following SQL statement: " + sql;
    outResponse.setContentLength(body.size());
    outResponse.send() << body;
}
Пример #27
0
void chat::handleRequest(Poco::Net::HTTPServerRequest& request, Poco::Net::HTTPServerResponse& response)
{
	std::string nick;

	MyPartHandler partHandler;
	HTMLForm form(request, request.stream(), partHandler);

	response.setChunkedTransferEncoding(true);
	response.setContentType("text/html");

	if (!form.empty())
	{
		NameValueCollection::ConstIterator it;
		NameValueCollection::ConstIterator end;

		it = form.begin();
		end = form.end();
		for (; it != end; ++it)
		{
			if (it->first == "user")
				nick = it->second;
		}
	}

	std::ostream& responseStream = response.send();
	responseStream << "<!DOCTYPE html>\n";
	responseStream << "<html>\n";
	responseStream << "\t<head>\n";
	responseStream << "\t\t<link rel = \"stylesheet\" type = \"text/css\" href = \"styles.css\">\n";
	responseStream << "\t\t<title>Chat</title>\n";
	responseStream << "\t\t<script type = \"text/JavaScript\" src = \"jquery.js\"></script>\n";
	responseStream << "\t\t<script type = \"text/JavaScript\" src = \"jqueryui.js\"></script>\n";
	responseStream << "\t\t<script type = \"text/JavaScript\" src = \"script.js\"></script>\n";
	responseStream << "<script>\n";
	responseStream << "\tvar nick=\"" << nick << "\";\n";
	responseStream << "</script>\n";
	responseStream << "\t\t<link rel = \"stylesheet\" type = \"text/css\" href = \"jqueryuiss.css\">\n";
	responseStream << "\t</head>\n";
	responseStream << "\t<body>\n";
	responseStream << "\t\t<audio id=\"myAudio\">\n";
	responseStream << "\t\t\t<source src=\"newmessage.mp3\" type=\"audio/mpeg\">\n";
	responseStream << "\t\t\t<source src=\"newmessage.ogg\" type=\"audio/ogg\">\n";
	responseStream << "\t\t\tYour browser does not suport the audio tag\n";
	responseStream << "</audio>\n";
	responseStream << "\t\t<div id = \"FtHeader\">\n";
	responseStream << "\t\t\t<h1 align = \"center\"><img src = \"logo.jpg\" alt = \"some_text\"></h1>\n";
	responseStream << "\t\t</div>\n";
	responseStream << "\t\t<div id = \"chatTable2\">\n";
	responseStream << "\t\t\t<table align = \"center\">\n";
	responseStream << "\t\t\t\t<tr>\n";
	responseStream << "\t\t\t\t<td>\n";
	responseStream << "\t\t\t\t<div id=\"tabs\">\n";
	responseStream << "\t\t\t\t\t<ul>\n";
	responseStream << "\t\t\t\t\t\t<li><a href=\"#chatWindow\">Public</a></li>\n";
	responseStream << "\t\t\t\t\t\t<li><a href=\"#privateChatWindow\">Private</a></li>\n";
	responseStream << "\t\t\t\t\t</ul>\n";
	responseStream << "\t\t\t\t\t<div id = \"chatWindow\"></div>\n";
	responseStream << "\t\t\t\t\t<div id = \"privateChatWindow\"></div>\n";
	responseStream << "\t\t\t\t</div>\n";
	responseStream << "\t\t\t\t</td>\n";
	responseStream << "\t\t\t\t<td>\n";
	responseStream << "\t\t\t\t\t<div id = \"OnlineBox\">\n";
	responseStream << "\t\t\t\t\t</div>\n";
	responseStream << "\t\t\t\t</td>\n";
	responseStream << "\t\t\t\t</tr>\n";
	responseStream << "\t\t\t\t<tr>\n";
	responseStream << "\t\t\t\t<td>\n";
	responseStream << "\t\t\t\t\t<textarea maxlength = \"320\" id = \"TxTBox\" type = \"text\" style = \"resize:none\" name = \"TxTBox\" onkeypress = \"if(event.keyCode == 13){event.preventDefault(); sendMsgToServer();}\"></textarea>\n";
	responseStream << "\t\t\t\t</td>\n";
	responseStream << "\t\t\t\t<td>\n";
	responseStream << "\t\t\t\t\t<Button id = \"SendButton\" onclick = \"  sendMsgToServer();\"  onkeypress = \"if (event.keyCode == 13) {event.preventDefault(); sendMsgToServer(); }\">Send!</Button><br>\n";
	responseStream << "\t\t\t\t\t<form method=\"POST\" action=\"/\">\n";
	responseStream << "\t\t\t\t\t\t<input type=\"submit\" value=\"Logout\" id=\"LogoutButton\" onclick=\"loggingOut();\">\n";
	responseStream << "\t\t\t\t\t</form>\n";
	responseStream << "\t\t\t\t</td>\n";
	responseStream << "\t\t\t\t</tr>\n";
	responseStream << "\t\t\t</table>\n";
	responseStream << "\t\t</div>\n";
	responseStream << "\t</body>\n";
	responseStream << "</html>";
}
Пример #28
0
		void RedirectRequestHandler::handle(Poco::Net::HTTPServerRequest & request, Poco::Net::HTTPServerResponse & response){
			response.set("Location", to);
			response.setStatusAndReason(Poco::Net::HTTPServerResponse::HTTP_SEE_OTHER);
			response.setContentLength(0);
			response.send();
		}
Пример #29
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();
}
Пример #30
0
void ODBCHandler::handleRequest(Poco::Net::HTTPServerRequest & request, Poco::Net::HTTPServerResponse & response)
{
    Poco::Net::HTMLForm params(request, request.stream());
    LOG_TRACE(log, "Request URI: " + request.getURI());

    auto process_error = [&response, this](const std::string & message)
    {
        response.setStatusAndReason(Poco::Net::HTTPResponse::HTTP_INTERNAL_SERVER_ERROR);
        if (!response.sent())
            response.send() << message << std::endl;
        LOG_WARNING(log, message);
    };

    if (!params.has("query"))
    {
        process_error("No 'query' in request body");
        return;
    }

    if (!params.has("columns"))
    {
        process_error("No 'columns' in request URL");
        return;
    }

    if (!params.has("connection_string"))
    {
        process_error("No 'connection_string' in request URL");
        return;
    }

    UInt64 max_block_size = DEFAULT_BLOCK_SIZE;
    if (params.has("max_block_size"))
    {
        std::string max_block_size_str = params.get("max_block_size", "");
        if (max_block_size_str.empty())
        {
            process_error("Empty max_block_size specified");
            return;
        }
        max_block_size = parse<size_t>(max_block_size_str);
    }

    std::string columns = params.get("columns");
    std::unique_ptr<Block> sample_block;
    try
    {
        sample_block = parseColumns(std::move(columns));
    }
    catch (const Exception & ex)
    {
        process_error("Invalid 'columns' parameter in request body '" + ex.message() + "'");
        LOG_WARNING(log, ex.getStackTrace().toString());
        return;
    }

    std::string format = params.get("format", "RowBinary");
    std::string query = params.get("query");
    LOG_TRACE(log, "Query: " << query);

    std::string connection_string = params.get("connection_string");
    LOG_TRACE(log, "Connection string: '" << connection_string << "'");

    WriteBufferFromHTTPServerResponse out(request, response, keep_alive_timeout);
    try
    {
        BlockOutputStreamPtr writer = FormatFactory::instance().getOutput(format, out, *sample_block, *context);
        auto pool = getPool(connection_string);
        ODBCBlockInputStream inp(pool->get(), query, *sample_block, max_block_size);
        copyData(inp, *writer);
    }
    catch (...)
    {
        auto message = getCurrentExceptionMessage(true);
        response.setStatusAndReason(
            Poco::Net::HTTPResponse::HTTP_INTERNAL_SERVER_ERROR); // can't call process_error, bacause of too soon response sending
        writeStringBinary(message, out);
        tryLogCurrentException(log);
    }
}