Advertisement
keyz182

Simplified Example

Dec 30th, 2011
239
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 8.03 KB | None | 0 0
  1. //
  2. // HTTPFormServer.cpp
  3. //
  4. // $Id: //poco/Main/Net/samples/HTTPFormServer/src/HTTPFormServer.cpp#5 $
  5. //
  6. // This sample demonstrates the HTTPServer and HTMLForm classes.
  7. //
  8. // Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
  9. // and Contributors.
  10. //
  11. // Permission is hereby granted, free of charge, to any person or organization
  12. // obtaining a copy of the software and accompanying documentation covered by
  13. // this license (the "Software") to use, reproduce, display, distribute,
  14. // execute, and transmit the Software, and to prepare derivative works of the
  15. // Software, and to permit third-parties to whom the Software is furnished to
  16. // do so, all subject to the following:
  17. //
  18. // The copyright notices in the Software and this entire statement, including
  19. // the above license grant, this restriction and the following disclaimer,
  20. // must be included in all copies of the Software, in whole or in part, and
  21. // all derivative works of the Software, unless such copies or derivative
  22. // works are solely in the form of machine-executable object code generated by
  23. // a source language processor.
  24. //
  25. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  26. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  27. // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
  28. // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
  29. // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
  30. // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  31. // DEALINGS IN THE SOFTWARE.
  32. //
  33.  
  34.  
  35. #include "Poco/Net/HTTPServer.h"
  36. #include "Poco/Net/HTTPRequestHandler.h"
  37. #include "Poco/Net/HTTPRequestHandlerFactory.h"
  38. #include "Poco/Net/HTTPServerParams.h"
  39. #include "Poco/Net/HTTPServerRequest.h"
  40. #include "Poco/Net/HTTPServerResponse.h"
  41. #include "Poco/Net/HTTPServerParams.h"
  42. #include "Poco/Net/HTMLForm.h"
  43. #include "Poco/Net/PartHandler.h"
  44. #include "Poco/Net/MessageHeader.h"
  45. #include "Poco/Net/ServerSocket.h"
  46. #include "Poco/CountingStream.h"
  47. #include "Poco/NullStream.h"
  48. #include "Poco/StreamCopier.h"
  49. #include "Poco/Exception.h"
  50. #include "Poco/Util/ServerApplication.h"
  51. #include "Poco/Util/Option.h"
  52. #include "Poco/Util/OptionSet.h"
  53. #include "Poco/Util/HelpFormatter.h"
  54. #include "Poco/URIStreamOpener.h"
  55. #include "Poco/Path.h"
  56. #include "Poco/URI.h"
  57. #include "Poco/Net/HTTPStreamFactory.h"
  58. #include "Poco/Net/FTPStreamFactory.h"
  59. #include <iostream>
  60. #include <memory>
  61. #include <string>
  62.  
  63.  
  64. using Poco::URIStreamOpener;
  65. using Poco::Path;
  66. using Poco::URI;
  67. using Poco::Exception;
  68. using Poco::Net::HTTPStreamFactory;
  69. using Poco::Net::FTPStreamFactory;
  70. using Poco::Net::ServerSocket;
  71. using Poco::Net::HTTPRequestHandler;
  72. using Poco::Net::HTTPRequestHandlerFactory;
  73. using Poco::Net::HTTPServer;
  74. using Poco::Net::HTTPServerRequest;
  75. using Poco::Net::HTTPServerResponse;
  76. using Poco::Net::HTTPServerParams;
  77. using Poco::Net::MessageHeader;
  78. using Poco::Net::HTMLForm;
  79. using Poco::Net::NameValueCollection;
  80. using Poco::Util::ServerApplication;
  81. using Poco::Util::Application;
  82. using Poco::Util::Option;
  83. using Poco::Util::OptionSet;
  84. using Poco::Util::HelpFormatter;
  85. using Poco::CountingInputStream;
  86. using Poco::NullOutputStream;
  87. using Poco::StreamCopier;
  88.  
  89.  
  90. class MyPartHandler: public Poco::Net::PartHandler
  91. {
  92. public:
  93.     MyPartHandler():
  94.         _length(0)
  95.     {
  96.     }
  97.    
  98.     void handlePart(const MessageHeader& header, std::istream& stream)
  99.     {
  100.         _type = header.get("Content-Type", "(unspecified)");
  101.         if (header.has("Content-Disposition"))
  102.         {
  103.             std::string disp;
  104.             NameValueCollection params;
  105.             MessageHeader::splitParameters(header["Content-Disposition"], disp, params);
  106.             _name = params.get("name", "(unnamed)");
  107.             _fileName = params.get("filename", "(unnamed)");
  108.         }
  109.        
  110.         CountingInputStream istr(stream);
  111.         NullOutputStream ostr;
  112.         StreamCopier::copyStream(istr, ostr);
  113.         _length = istr.chars();
  114.     }
  115.    
  116.     int length() const
  117.     {
  118.         return _length;
  119.     }
  120.    
  121.     const std::string& name() const
  122.     {
  123.         return _name;
  124.     }
  125.  
  126.     const std::string& fileName() const
  127.     {
  128.         return _fileName;
  129.     }
  130.    
  131.     const std::string& contentType() const
  132.     {
  133.         return _type;
  134.     }
  135.    
  136. private:
  137.     int _length;
  138.     std::string _type;
  139.     std::string _name;
  140.     std::string _fileName;
  141. };
  142.  
  143.  
  144. class FormRequestHandler: public HTTPRequestHandler
  145.     /// Return a HTML document with the current date and time.
  146. {
  147. public:
  148.     FormRequestHandler()
  149.     {
  150.     }
  151.    
  152.     void handleRequest(HTTPServerRequest& request, HTTPServerResponse& response)
  153.     {
  154.         Application& app = Application::instance();
  155.         app.logger().information("Request from " + request.clientAddress().toString());
  156.  
  157.                 HTTPStreamFactory::registerFactory();
  158.                 FTPStreamFactory::registerFactory();
  159.                
  160.                 try
  161.             {
  162.                 URI uri("http://mdesk001.cs.cf.ac.uk/a");
  163.                 std::auto_ptr<std::istream> pStr(URIStreamOpener::defaultOpener().open(uri));
  164.                         StreamCopier::copyStream(*pStr.get(),response.send());
  165.             }
  166.             catch (Exception& exc)
  167.             {
  168.                 std::cerr << exc.displayText() << std::endl;
  169.                 return;
  170.             }
  171.     }
  172. };
  173.  
  174.  
  175. class FormRequestHandlerFactory: public HTTPRequestHandlerFactory
  176. {
  177. public:
  178.     FormRequestHandlerFactory()
  179.     {
  180.     }
  181.  
  182.     HTTPRequestHandler* createRequestHandler(const HTTPServerRequest& request)
  183.     {
  184.         return new FormRequestHandler;
  185.     }
  186. };
  187.  
  188.  
  189. class HTTPFormServer: public Poco::Util::ServerApplication
  190.     /// The main application class.
  191.     ///
  192.     /// This class handles command-line arguments and
  193.     /// configuration files.
  194.     /// Start the HTTPFormServer executable with the help
  195.     /// option (/help on Windows, --help on Unix) for
  196.     /// the available command line options.
  197.     ///
  198.     /// To use the sample configuration file (HTTPFormServer.properties),
  199.     /// copy the file to the directory where the HTTPFormServer executable
  200.     /// resides. If you start the debug version of the HTTPFormServer
  201.     /// (HTTPFormServerd[.exe]), you must also create a copy of the configuration
  202.     /// file named HTTPFormServerd.properties. In the configuration file, you
  203.     /// can specify the port on which the server is listening (default
  204.     /// 9980) and the format of the date/Form string sent back to the client.
  205.     ///
  206.     /// To test the FormServer you can use any web browser (http://localhost:9980/).
  207. {
  208. public:
  209.     HTTPFormServer(): _helpRequested(false)
  210.     {
  211.     }
  212.    
  213.     ~HTTPFormServer()
  214.     {
  215.     }
  216.  
  217. protected:
  218.     void initialize(Application& self)
  219.     {
  220.         loadConfiguration(); // load default configuration files, if present
  221.         ServerApplication::initialize(self);
  222.     }
  223.        
  224.     void uninitialize()
  225.     {
  226.         ServerApplication::uninitialize();
  227.     }
  228.  
  229.     void defineOptions(OptionSet& options)
  230.     {
  231.         ServerApplication::defineOptions(options);
  232.        
  233.         options.addOption(
  234.             Option("help", "h", "display help information on command line arguments")
  235.                 .required(false)
  236.                 .repeatable(false));
  237.     }
  238.  
  239.     void handleOption(const std::string& name, const std::string& value)
  240.     {
  241.         ServerApplication::handleOption(name, value);
  242.  
  243.         if (name == "help")
  244.             _helpRequested = true;
  245.     }
  246.  
  247.     void displayHelp()
  248.     {
  249.         HelpFormatter helpFormatter(options());
  250.         helpFormatter.setCommand(commandName());
  251.         helpFormatter.setUsage("OPTIONS");
  252.         helpFormatter.setHeader("A web server that shows how to work with HTML forms.");
  253.         helpFormatter.format(std::cout);
  254.     }
  255.  
  256.     int main(const std::vector<std::string>& args)
  257.     {
  258.         if (_helpRequested)
  259.         {
  260.             displayHelp();
  261.         }
  262.         else
  263.         {
  264.             unsigned short port = (unsigned short) config().getInt("HTTPFormServer.port", 9980);
  265.            
  266.             // set-up a server socket
  267.             ServerSocket svs(port);
  268.             // set-up a HTTPServer instance
  269.             HTTPServer srv(new FormRequestHandlerFactory, svs, new HTTPServerParams);
  270.             // start the HTTPServer
  271.             srv.start();
  272.             // wait for CTRL-C or kill
  273.             waitForTerminationRequest();
  274.             // Stop the HTTPServer
  275.             srv.stop();
  276.         }
  277.         return Application::EXIT_OK;
  278.     }
  279.    
  280. private:
  281.     bool _helpRequested;
  282. };
  283.  
  284.  
  285. int main(int argc, char** argv)
  286. {
  287.     HTTPFormServer app;
  288.     return app.run(argc, argv);
  289. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement