POCO C++ Libraries Intro and Overview


Published on

Published in: Technology, Education
1 Like
  • Be the first to comment

No Downloads
Total Views
On Slideshare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

POCO C++ Libraries Intro and Overview

  1. 1. POCO C++ LibrariesIntro & OverviewGünter ObiltschnigFounder, POCO C++ Libraries ProjectApplied Informatics Software Engineering GmbHguenter@pocoproject.org
  2. 2. "Without a good library, mostinteresting tasks are hard to do in C++; but given a good library, almost any task can be made easy." Bjarne Stroustrup (designer and original implementor of C++)
  3. 3. The POCO C++ Libraries are... > a collection of C++ class libraries, similar in concept to the Java Class Library, the .NET Framework or Apples Cocoa; > focused on "internet-age" network-centric applications; > written in efficient, modern ANSI/ISO Standard C++ and based on the C++ Standard Library/STL; > highly portable and available on many different platforms; > Open Source, licensed under the Boost Software License, > and thus completely free for both commercial and non- commercial use.
  4. 4. Zip NetSSL Tools & Utilities Util Net Data MySQL SQLite ODBC XML Crypto FoundationApplication C++ and C Standard LibrariesPOSIX, WIN32, other (RT)OS API
  5. 5. POCO Objectives and Mission > POCO is a powerful, yet easy to use platform to build your applications upon > POCO allows you to build highly portable applications (write once – compile and run anywhere) > POCO is modular and scalable from embedded to enterprise applications (you only pay for what you use) > POCO provides consistent, comprehensive and comprehensible programming interfaces > POCO is written in fast, efficient C++
  6. 6. Objectives and Mission (contd) > POCO favors simplicity over complexity ("as simple as possible, but not simpler") > POCO aims for consistency in design, coding style and documentation > POCO emphasizes source code quality, in terms of readability, comprehensiveness, consistency, style and testability > POCO aims to make C++ programming fun again
  7. 7. Guiding Principles > Strong focus on code quality, style, consistency and code readability –all code must satisfy our coding styleguide (and it works – we frequently get compliments on our code quality) > Strong focus on tests (automated unit tests with high coverage) > Favor pragmatic and elegant design over "solving all the worlds problems" (if we can satisfy 95 % of all use cases with an elegant solution, and the remaining 5 % would require an overly complex design, we focus on the 95 %) > Build on top of solid foundations – use existing proven C libraries (e.g., expat, zlib, PCRE, SQLite) where it makes sense
  8. 8. History & Milestones 06.2006 boost license, new website08.2004 05.2006project started > 1000 downloads/month 02.2005 01.2006 11.2006 first release on sourceforge release 1.0 first major commercial user (> 100 devs) 03.2005 03.2006 first contributor release 1.1 applied informatics founded
  9. 9. History & Milestones 05.2012 joined wg21 > 5500 downloads/month01.2007 12.2010 08.2012> 2000 downloads/month release 1.4 work on 1.5/1.6 05.2007 01.2011 relese 1.3 > 5000 downloads/month 12.2008 bjarne mentions poco in interview
  10. 10. Windows WindowsXP/Vista/7/Server Embedded/Compact (CE) OS X iOS Linux Embedded Linux Server/Desktop Mobile/Embedded
  11. 11. POCO – Scalability Embedded > POCO is well-suited for embedded systems running under Embedded Linux, Windows Embedded CE or QNX. > POCO-based applications (using the built-in web server) run on 75 MHz ARM9-based Linux systems (uClibc) with 8 MB RAM and 4 MB Flash (e.g. Digi Connect ME 9210). > A typical POCO-based application using the web server from the Net library has a statically linked size of 2 MB and uses about 2 – 3 MB of RAM. > Typical mid-ranged embedded platforms (32 – 64 MB RAM, 16 – 64 MB Flash, 180 MHz ARM9) provide plenty of resources even for more complex applications (using OSP and Remoting).
  12. 12. POCO and Embedded – Code Size > POCO (including SSL/Crypto) + OSP + Remoting libraries use less than 4 MB of Flash storage (compressed jffs2 or squashfs). > The RAM overhead for such an application is below 8 MB.guenter@cis-digiel:~/ws/poco-1.3$ ls -l lib/Linux/armv5tejl/*.so.*-rwxr-xr-x 1 guenter guenter  103616 2009-03-03 18:48 lib/Linux/armv5tejl/libPocoBinary.so.6-rwxr-xr-x 1 guenter guenter  103752 2009-03-03 19:12 lib/Linux/armv5tejl/libPocoCrypto.so.6-rwxr-xr-x 1 guenter guenter 1582720 2009-03-03 18:43 lib/Linux/armv5tejl/libPocoFoundation.so.6-rwxr-xr-x 1 guenter guenter  907192 2009-03-03 18:47 lib/Linux/armv5tejl/libPocoNet.so.6-rwxr-xr-x 1 guenter guenter  293960 2009-03-03 19:11 lib/Linux/armv5tejl/libPocoNetSSL.so.6-rwxr-xr-x 1 guenter guenter  685008 2009-03-03 18:54 lib/Linux/armv5tejl/libPocoOSP.so.2-rwxr-xr-x 1 guenter guenter  196264 2009-03-03 18:48 lib/Linux/armv5tejl/libPocoRemoting.so.6-rwxr-xr-x 1 guenter guenter  182932 2009-03-03 18:48 lib/Linux/armv5tejl/libPocoSoapLite.so.6-rwxr-xr-x 1 guenter guenter  281048 2009-03-03 18:45 lib/Linux/armv5tejl/libPocoUtil.so.6-rwxr-xr-x 1 guenter guenter  577588 2009-03-03 18:44 lib/Linux/armv5tejl/libPocoXML.so.6-rwxr-xr-x 1 guenter guenter  353312 2009-03-03 18:54 lib/Linux/armv5tejl/libPocoZip.so.6
  13. 13. POCO and Applied Informatics > Applied Informatics provides project infrastructure and leads the open source project. > Professional, commercial support and training. > Additional C++ libraries and tools.
  14. 14. Device Management Remoting OSP Universal Plug and Play Binary SOAP Standard Services Devices & Services Code Generator Bundle Creator SOAP, GENA HTTPMU, SSDP Fast Infoset Zeroconf UPnP Core POCO C++ LibrariesApplication (Foundation, XML, Crypto, Net, NetSSL, Data, Util, Zip) C++ and C Standard Libraries POSIX, WIN32, other (RT)OS API Commercial Open Source Third party/customer-specific
  15. 15. Roadmap08.2012 11.2012 06.2013release 1.4.4 release 1.6 release 2.0production release production release c++11 alignmentbugfixes, minor new features based on 1.5 dev branch 09.2012 01.2013 release 1.5 release 1.4.5 development release bugfixes new data library major new features
  16. 16. Getting Started
  17. 17. http://pocoproject.org/download > Source packages for Windows have CR-LF line endings and are in Zip format. > Source packages for other platforms have LF line endings and are in .tar.gz format.
  18. 18. External Dependencies > Basic Edition (only Foundation, XML, Util, Net) has no external dependencies. > Complete Edition needs third-party libraries: > OpenSSL (for Crypto and NetSSL) > ODBC (for Data/ODBC) > MySQL Client (for Data/MySQL)
  19. 19. External Dependencies: OpenSSL > needed by Crypto and NetSSL libraries > integrated in Mac OS X and most Linux distributions > alternatively, build from source (http://openssl.org) > Windows > use installer from Shining Light Productions http://www.slproweb.com/products/Win32OpenSSL.html > or build from source
  20. 20. External Dependencies: ODBC > needed by Data/ODBC > part of the Windows SDK > Mac OS X: includes iodbc > Linux/other Unix platforms: get unixodbc or iodbc.
  21. 21. External Dependencies: MySQL > needed by Data/MySQL > get from http://dev.mysql.com/downloads/ > or use Linux package sudo apt-get install libmysqlclient-dev
  22. 22. Building on Windows > Source code distribution includes Visual Studio solutions and project files for: > Visual Studio .NET 2003 > Visual Studio 2005 > Visual Studio 2008 (32 and 64-bit, Windows CE) > Visual Studio 2010/2012 (32 and 64-bit) > Build Script buildwin.cmd for command-line batch builds
  23. 23. Building on Windows: Configurations Build Results debug release static_md PocoFoundationmdd.lib PocoFoundationmd.lib static_mt PocoFoundationmtd.lib PocoFoundationmt.lib shared PocoFoundationd.dll PocoFoundation.dll
  24. 24. Building on Windows: Configurations Runtime Dependencies debug release msvcpXXd.dll msvcpXX.dll static_md msvcrXXd.dll msvcrXX.dll static_mt – – msvcpXXd.dll msvcpXX.dll shared msvcrXXd.dll msvcrXX.dll
  25. 25. Building on Windows: Build Script > buildwin.cmd builds all libraries, testsuites and (optionally) samples > arguments specify Visual Studio version, build configuration and platform > External Dependencies (OpenSSL, etc.): > either add search paths to INCLUDE and LIB environment vars > or edit buildwin.cmd and add search paths
  26. 26. Building on Windows: Build Script Examples > build everything (Visual Studio 2008) buildwin 90 build all both Win32 samples > build 64-bit static libs, no samples (Visual Studio 2008) buildwin 90 build static_mt both x64 nosamples Important: run from Visual Studio 2008 x64 Cross Tools Command Prompt > show all options – launch buildwin with no arguments
  27. 27. Building on Windows: Build Output > Dynamic Link Libraries will be placed in: %POCO_BASE%bin (32-bit) %POCO_BASE%bin64 (64-bit) %POCO_BASE%bin%PLATFORM_NAME% (Windows CE) > Static and import libraries will be placed in: %POCO_BASE%lib (32-bit) %POCO_BASE%lib64 (64-bit) %POCO_BASE%lib%PLATFORM_NAME% (Windows CE) > Binaries go into: bin binstatic_md (statically linked, multithreaded DLL, new in 1.4) binstatic_mt (statically linked, multithreaded, new in 1.4)
  28. 28. Building on Unix/Linux > Unix/Linux platforms use a build system based on GNU Make > can be used on Linux, Mac OS X, FreeBSD, QNX, Solaris, HP-UX, etc. (also Cygwin) > supports cross-builds for Embedded Linux > supports automatic computation of dependencies > can be used for custom projects > requires GNU Make 3.80 or newer > configure script to simplify setup
  29. 29. Building on Unix/Linux > $ ./configure $ make -s -j4
  30. 30. Building on Unix/Linux: Customizing > Dont build samples and testsuites: ./configure --no-samples --no-tests > Dont build a specific library (Data/MySQL): ./configure --omit=Data/MySQL > Use a specific build configuration (cross build): ./configure --config=iPhone > Typical Embedded Linux build: ./configure --config=DigiEL --poquito --static --no-samples --no-tests > Show all options: ./configure --help
  31. 31. Building on Unix/Linux: Build Output> Shared and static libraries will be placed in: ${POCO_BASE}/lib/${OSNAME}/${OSARCH} > Examples: ${POCO_BASE}/Linux/i686 ${POCO_BASE}/Linux/armv5tejl ${POCO_BASE}/Darwin/x86_64> Binaries go into: bin/${OSNAME}/${OSARCH} bin/${OSNAME}/${OSARCH}/static (statically linked, new in 1.4)> Code for different architectures can be built within same source tree
  32. 32. Building on Unix/Linux: Environment> Set environment variable POCO_BASE: export POCO_BASE=/ws/poco-1.4 cd $POCO_BASE/XML make -s -j4> Use a specific build configuration: export POCO_CONFIG=DigiEL> Clean rebuild: make clean make -s -j4
  33. 33. Example
  34. 34. // hello.cpp#include "Poco/Thread.h"#include "Poco/Runnable.h"#include <iostream>class HelloThread: public Poco::Runnable{ void run() { for (int i = 0; i < 10; i++) { std::cout << "Hello, world!" << std::endl; } }};int main(int argc, char** argv){ Poco::Thread thread; HelloThread hello; thread.start(hello); thread.join(); return 0;}
  35. 35. # Makefileinclude $(POCO_BASE)/build/rules/globalobjects = hellotarget = hellotarget_libs = PocoFoundationinclude $(POCO_BASE)/build/rules/exec
  36. 36. XML
  37. 37. XML Programming Interfaces > POCO supports two standard interfaces for working with (reading and writing) XML data: > The Simple API for XML, Version 2 > The Document Object Model > Theres also Poco::Util::XMLConfiguration for the lazy ones ;-)
  38. 38. The Simple API for XML (SAX) > SAX was originally a Java-only API for reading XML data. > The API has been developed by a group of volunteers, not by an "official" standardization group. > The current version of the API is 2.0.2 (since April 2004) > POCO supports a C++ variant of the original Java API. > For more information: http://www.saxproject.org
  39. 39. Event-driven Parsing > SAX is an event-driven interface. > The XML document is not loaded into memory as a whole for parsing. > Instead, the parser scans the XML document, and for every XML construct (element, text, processing instruction, etc.) it finds, calls a certain member function of a handler object. > SAX basically defines the interfaces of these handler objects, as well as the interface you use to start and configure the parser.
  40. 40. startDocument() startElement()<?xml version="1.0"?> startElement()<root> <elem1> some text characters() </elem1> <elem2 attr1="val2" endElement() attr2="val3"/></root> startElement() endElement() endElement() endDocument()
  41. 41. SAX Interfaces > Attributes (access attributes values by index or name) > ContentHandler (startElement(), endElement(), characters(), ...) > DeclHandler (partly supported for reporting entity declarations) > DTDHandler (notationDecl(), unparsedEntityDecl()) > LexicalHandler (startDTD(), endDTD(), startCDATA(), endCDATA(), comment())
  42. 42. #include "Poco/SAX/ContentHandler.h"class MyHandler: public Poco::XML::ContentHandler{public: MyHandler(); void setDocumentLocator(const Locator* loc); void startDocument(); void endDocument(); void startElement( const XMLString& namespaceURI, const XMLString& localName, const XMLString& qname, const Attributes& attributes); void endElement( const XMLString& uri, const XMLString& localName, const XMLString& qname);
  43. 43. void characters(const XMLChar ch[], int start, int length); void ignorableWhitespace(const XMLChar ch[], int start, int len); void processingInstruction( const XMLString& target, const XMLString& data); void startPrefixMapping( const XMLString& prefix, const XMLString& uri); void endPrefixMapping(const XMLString& prefix); void skippedEntity(const XMLString& name);};
  44. 44. SAX Parser Configuration > XMLReader defines the interface of the parser. > Methods for registering handlers (setContentHandler(), etc.) > Methods for parser configuration: > setFeature(), getFeature() e.g. for enabling/disabling namespaces support > setProperty(), getProperty() e.g. for registering LexicalHandler, DeclHandler
  45. 45. class MyHandler: public ContentHandler{ ...};MyHandler handler;SAXParser parser;parser.setFeature(XMLReader::FEATURE_NAMESPACES, true);parser.setFeature(XMLReader::FEATURE_NAMESPACE_PREFIXES, true);parser.setContentHandler(&handler);try{ parser.parse(“test.xml”);}catch (Poco::Exception& e){ std::cerr << e.displayText() << std::endl;}
  46. 46. The Document Object Model > The Document Object Model is an API specified by the World Wide Web Consortium (W3C) > DOM uses a tree representation of the XML document > The entire document has to be loaded into memory > You can modify the XML document directly
  47. 47. <xml version="1.0"><root> <elem1> some text </elem1> <elem2 attr1="val2" attr2="val3"/></root> Document Element Attr Element Element Attr Text
  48. 48. EventTarget NodeDocument Element CharacterData ProcessingInstruction Text Comment CDATASection
  49. 49. Navigating the DOM > Node has > parentNode() > firstChild(), lastChild() > nextSibling(), previousSibling() > NodeIterator for document-order traversal: nextNode(), previousNode() > TreeWalker for arbitraty navigation: parentNode(), firstChild(), lastChild(), etc. > NodeIterator and TreeWalker support node filtering
  50. 50. Memory Management in the DOM > DOM Nodes are reference counted. > If you create a new node and add it to a document, the document increments its reference count. So use an AutoPtr. > You only get ownership of non-tree objects implementing the NamedNodeMap and NodeList interface. You have to release them (or use an AutoPtr). > The document keeps ownership of nodes you remove from the tree. These nodes end up in the documents AutoReleasePool.
  51. 51. #include "Poco/DOM/DOMParser.h"#include "Poco/DOM/Document.h"#include "Poco/DOM/NodeIterator.h"#include "Poco/DOM/NodeFilter.h"#include "Poco/DOM/AutoPtr.h"#include "Poco/SAX/InputSource.h"[...]std::ifstream in(“test.xml”);Poco::XML::InputSource src(in);Poco::XML::DOMParser parser;Poco::AutoPtr<Poco::XML::Document> pDoc = parser.parse(&src);Poco::XML::NodeIterator it(pDoc, Poco::XML::NodeFilter::SHOW_ELEMENTS);Poco::XML::Node* pNode = it.nextNode();while (pNode){ std::cout<<pNode->nodeName()<<":"<< pNode->nodeValue()<<std::endl; pNode = it.nextNode();}
  52. 52. Creating XML Documents > You can create an XML document by: > building a DOM document from scratch, or > by using the XMLWriter class, > or by generating the XML yourself. > XMLWriter supports a SAX interface for generating XML data.
  53. 53. #include "Poco/DOM/Document.h"#include "Poco/DOM/Element.h"#include "Poco/DOM/Text.h"#include "Poco/DOM/AutoPtr.h" //typedef to Poco::AutoPtr#include "Poco/DOM/DOMWriter.h"#include "Poco/XML/XMLWriter.h"using namespace Poco::XML;...AutoPtr<Document> pDoc = new Document;AutoPtr<Element> pRoot = pDoc->createElement("root");pDoc->appendChild(pRoot);AutoPtr<Element> pChild1 = pDoc->createElement("child1");AutoPtr<Text> pText1 = pDoc->createTextNode("text1");pChild1->appendChild(pText1);pRoot->appendChild(pChild1);AutoPtr<Element> pChild2 = pDoc->createElement("child2");AutoPtr<Text> pText2 = pDoc->createTextNode("text2");pChild2->appendChild(pText2);pRoot->appendChild(pChild2);DOMWriter writer;writer.setNewLine("n");writer.setOptions(XMLWriter::PRETTY_PRINT);writer.writeNode(std::cout, pDoc);
  54. 54. #include "Poco/XML/XMLWriter.h"#include "Poco/SAX/AttributesImpl.h"...std::ofstream str(“test.xml”)XMLWriter writer(str, XMLWriter::WRITE_XML_DECLARATION |XMLWriter::PRETTY_PRINT);writer.setNewLine("n");writer.startDocument();AttributesImpl attrs;attrs.addAttribute("", "", "a1", "", "v1");attrs.addAttribute("", "", "a2", "", "v2");writer.startElement("urn:mynamespace", "root", "", attrs);writer.startElement("", "", "sub");writer.endElement("", "", "sub");writer.endElement("urn:mynamespace", "root", "");writer.endDocument();
  55. 55. DOM and XPath > The DOM parser offers minimal XPath support for finding elements and attributes in DOM trees. > Node* getNodeByPath(const XMLString& path) const searches a node (element or attribute) based on a simplified XPath expression: > elem1/elem2/elem3 <root> <elem1> <elem2 attr1="value1"> > /elem1/elem2[1] <elem3> </elem3> > </elem2> /elem1/elem2[@attr1] <elem2 attr1="value2"> </elem2> > //elem1/elem2[@attr1=value2] </elem1> </root>
  56. 56. Network and Internet
  57. 57. SocketStreamSocket ServerSocket DatagramSocket RawSocket ICMPSocket SecureServerSocket MulticastSocketDialogSocket SecureStreamSocket WebSocket
  58. 58. The Socket Class > Poco::Net::Socket is the root class of the sockets inheritance tree. > It supports methods that can be used with some or all kinds of sockets, like: > select() and poll() > setting and getting various socket options (timeouts, buffer sizes, reuse address flag, etc.) > getting the sockets local address and the peers address
  59. 59. The StreamSocket Class > Poco::Net::StreamSocket is used for creating a TCP connection to a server. > Use sendBytes() and receiveBytes() to send and receive data, or use the Poco::Net::SocketStream class, which provides an I/O streams interface to a StreamSocket.
  60. 60. #include "Poco/Net/SocketAddress.h"#include "Poco/Net/StreamSocket.h"#include "Poco/Net/SocketStream.h"#include "Poco/StreamCopier.h"#include <iostream>int main(int argc, char** argv){ Poco::Net::SocketAddress sa("www.appinf.com", 80); Poco::Net::StreamSocket socket(sa) Poco::Net::SocketStream str(socket); str << "GET / HTTP/1.1rn" "Host: www.appinf.comrn" "rn"; str.flush(); Poco::StreamCopier::copyStream(str, std::cout); return 0;}
  61. 61. The ServerSocket Class > Poco::Net::ServerSocket is used to create a TCP server socket. > It is pretty low level. > For an actual server, consider using the TCPServer or the Reactor framework.
  62. 62. #include "Poco/Net/ServerSocket.h"#include "Poco/Net/StreamSocket.h"#include "Poco/Net/SocketStream.h"#include "Poco/Net/SocketAddress.h"int main(int argc, char** argv){ Poco::Net::ServerSocket srv(8080); // does bind + listen for (;;) { Poco::Net::StreamSocket ss = srv.acceptConnection(); Poco::Net::SocketStream str(ss); str << "HTTP/1.0 200 OKrn" "Content-Type: text/htmlrn" "rn" "<html><head><title>My 1st Web Server</title></head>" "<body><h1>Hello, world!</h1></body></html>" << std::flush; } return 0;}
  63. 63. The TCPServer Framework > Poco::Net::TCPServer implements a multithreaded TCP server. > The server uses a ServerSocket to accept incoming connections. You must put the ServerSocket into listening mode before passing it to the TCPServer. > The server maintains a queue for incoming connections. > A variable number of worker threads fetches connections from the queue to process them. The number of worker threads is adjusted automatically, depending on the number of connections waiting in the queue.
  64. 64. The TCPServer Framework (contd) > The number of connections in the queue can be limited to prevent the server from being flooded with requests. Incoming connections that no longer fit into the queue are closed immediately. > TCPServer creates its own thread that accepts connections and places them in the queue. > TCPServer uses TCPServerConnection objects to handle a connection. You must create your own subclass of TCPServerConnection, as well as a factory for it. The factory object is passed to the constructor of TCPServer.
  65. 65. The TCPServer Framework (contd) > Your subclass of TCPServerConnection must override the run() method. In the run() method, you handle the connection. > When run() returns, the TCPServerConnection object will be deleted, and the connection closed. > A new TCPServerConnection will be created for every accepted connection.
  66. 66. The HTTPServer Framework > POCO contains a ready-to-use HTTP Server framework > multithreaded > HTTP 1.0/1.1 > authentication support > cookie support > HTTPS by using the NetSSL library
  67. 67. HTTPServer > configurable multi-threading > maximum number of threads > uses thread pool > queue size for pending connections > similar to TCPServer > expects a HTTPRequestHandlerFactory which creates HTTPRequestHandler based on the URI
  68. 68. HTTPRequestHandlerFactory > manages all known HTTPRequestHandlers > sole purpose is to decide which request handler will answer a request > can be used to check cookies, authentication info but this is mostly done by the request handlers
  69. 69. Poco::UInt16 port = 9999;HTTPServerParams::Ptr pParams = new HTTPServerParams;pParams->setMaxQueued(100);pParams->setMaxThreads(16);ServerSocket svs(port);HTTPServer srv(new MyRequestHandlerFactory, svs, pParams);// start the HTTPServersrv.start();waitForTerminationRequest();// Stop the HTTPServersrv.stop();
  70. 70. #include "Poco/Net/HTTPRequestHandlerFactory.h"#include "Poco/Net/HTTPServerRequest.h"#include "RootHandler.h"#include "DataHandler.h"class MyRequestHandlerFactory: public Poco::Net::HTTPRequestHandlerFactory{public: MyRequestHandlerFactory() { } Poco::Net::HTTPRequestHandler* createRequestHandler( const Poco::Net::HTTPServerRequest& request) { if (request.getURI() == "/") return new RootHandler; else return new DataHandler; }};
  71. 71. HTTPServerRequest > created by the server > passed as parameter to the HTTPRequestHandler/-Factory > contains URI > cookies > authentification information > HTML form data
  72. 72. HTTPServerResponse > created by the server but initialized by the request handler > sets: > cookies > content type of the answer response.setContentType("text/html"); > either (a) the length of the content or (b) chunked transfer encoding response.setContentLength(1024); response.setChunkedTransferEncoding(true);
  73. 73. HTTPServerResponse (cont) > set response type response.setStatus[AndReason]( HTTPResponse::HTTP_OK); // default response.setStatus[AndReason]( HTTPResponse::HTTP_UNAUTHORIZED) > after response is fully configured, send the header std::ostream& out = response.send(); > if required, write data content to the returned stream > send() must be invoked exactly once!
  74. 74. class RootHandler: public Poco::Net::HTTPRequestHandler{public: void handleRequest(Poco::Net::HTTPServerRequest& request, Poco::Net::HTTPServerResponse& response){ Application& app = Application::instance(); app.logger().information("Request from " + request.clientAddress().toString()); response.setChunkedTransferEncoding(true); response.setContentType("text/html"); std::ostream& ostr = response.send(); ostr << "<html><head>" "<title>HTTP Server powered by POCO C++ Libraries</title>" "</head>"; ostr << "<body>"; ... ostr << "</body></html>";};
  75. 75. Handling Cookies > Support for handling cookies is provided by the Poco::Net::HTTPCookie class, as well as by the Poco::Net::HTTPRequest and Poco::Net::HTTPResponse classes. // set cookie in response Poco::Net::HTTPCookie cookie(“name”, “Peter”); cookie.setPath(“/”); cookie.setMaxAge(3600); // 1 hour response.addCookie(cookie); // extract cookie from request Poco::Net::NameValueCollection cookies; request.getCookies(cookies); Poco::Net::NameValueCollection::ConstIterator it = cookies.find(“name”); std::string userName; if (it != cookies.end()) userName = it->second;
  76. 76. Handling Credentialsvoid handleRequest(Poco::Net::HTTPServerRequest& request, Poco::Net::HTTPServerResponse& response){ if (!request.hasCredentials()) { response.requireAuthentication("My Realm"); response.setContentLength(0); response.send(); return; } else { Poco::Net::HTTPBasicCredentials cred(request); const std::string& user = cred.getUsername(); const std::string& pwd = cred.getPassword(); [...] }}
  77. 77. HTMLForm> helper class to handle HTML form data Poco::Net::HTMLForm form(request); form[“entry1”] == “somedata”;> to handle file uploads (POST with attachments) you must combine it with a Poco::Net::PartHandler MyPartHandler myHandler; Poco::Net::HTMLForm form(request, request.stream(), myHandler);
  78. 78. #include “Poco/Net/PartHandler.h”#include “Poco/Net/MessageHeader.h”class MyPartHandler: public Poco::Net::PartHandler{public: void handlePart(const Poco::Net::MessageHeader& header, std::istream& stream){ _disp = header["Content-Disposition"]; _type = header["Content-Type"]; // read from stream and do something with it}private: std::string _disp; std::string _type;};
  79. 79. HTTP Client > Poco::Net::HTTPClientSession > allows you set GET/POST > authentication information > proxy support > Poco::Net::HTTPStreamFactory and Poco::StreamCopier if you only want to download something
  80. 80. using namespace Poco::Net;HTTPClientSession s("www.somehost.com");//s.setProxy("localhost", srv.port());HTTPRequest request(HTTPRequest::HTTP_GET, "/large");HTMLForm form;form.add(“entry1”, “value1”);form.prepareSubmit(request);s.sendRequest(request);HTTPResponse response;std::istream& rs = s.receiveResponse(response);StreamCopier::copyStream(rs, std::cout);
  81. 81. PageCompiler > Allows to write HTML (or other) files with embedded C++ code. (similar to PHP, JSP, ASP, etc.) > Compiles pages into header and implementation file containing a Poco::Net::HTTPRequestHandler subclass. > Makes it a lot easier to implement web servers.
  82. 82. <%@ page class="TimeHandler" %><%@ impl include="Poco/DateTime.h" include="Poco/DateTimeFormatter.h"%><% Poco::DateTime now; std::string dt(Poco::DateTimeFormatter::format(now, "%W, %e %b %y %H:%M:%S %Z"));%><html><head><title>HTTPTimeServer powered by POCO C++ Libraries and PageCompiler</title><meta http-equiv="refresh" content="1"></head><body><p style="text-align: center; font-size: 48px;"><%= dt %></p></body></html>
  83. 83. URIStreamOpener > Poco::URIStreamOpener is used to create and open input streams for resources identified by URIs. > #include "Poco/URIStreamOpener.h" > For every URI scheme used, a subclass of Poco::URIStreamFactory must be registered. > POCO provides stream factories for files, HTTP, HTTPS and FTP resources.
  84. 84. #include "Poco/URIStreamOpener.h"#include "Poco/Net/HTTPStreamFactory.h"#include "Poco/Net/FTPStreamFactory.h"#include <memory>int main(int argc, char** argv){ Poco::Net::HTTPStreamFactory::registerFactory(); Poco::Net::FTPStreamFactory::registerFactory(); Poco::URIStreamOpener& opener = Poco::URIStreamOpener::defaultOpener(); std::unique_ptr<std::istream> istr1( opener.open("http://www.appinf.com/index.html") ); std::unique_ptr<std::istream> istr2( opener.open("ftp://ftp.appinf.com/pub/poco/poco-1.4.3p1.tar.gz") ); std::unique_ptr<std::istream> istr3( opener.open("file:///usr/include/stdio.h") ); return 0;}
  85. 85. SQL Database Access
  86. 86. Poco::Data Features > Transactions > all builtin C++ data types (and more) supported: bool, short, int, long, Poco::Int64, std::string, Poco::Data::BLOB > container support: vector, map, multimap, set, multiset, list > complex type support: map classes to database tables > supports Oracle, DB2, SQLServer and PostgreSQL (using ODBC), SQLite and MySQL > elegant, easy to use interface
  87. 87. #include "Poco/Data/Common.h"#include "Poco/Data/SQLite/Connector.h"#include <iostream>using namespace Poco::Data;void init(){ SQLite::Connector::registerConnector();}void shutdown(){ SQLite::Connector::unregisterConnector();}
  88. 88. int main(int argc, char* argv[]){ init(); Session ses( SessionFactory::instance().create( SQLite::Connector::KEY, "dummy.db" ) ); int count = 0; ses << "SELECT COUNT(*) FROM PERSON", into(count), now; std::cout << "People in DB " << count; shutdown(); return 0;}
  89. 89. Statement stmt(ses << "SELECT COUNT(*) FROM PERSON",into(count));stmt.execute();std::string str;Statement insert(ses << "INSERT INTO Strings VALUES(?)", use(str));insert.execute(); // inserts the empty stringstr = "Hi";insert.execute(); // inserts "Hi"std::set<std::string> setStr; // [...] init with 100s of stringsStatement bulk(ses << "INSERT INTO Strings VALUES(?)", use(setStr));bulk.execute();
  90. 90. Keywords > into where should we write data to > use where should we read data from > lowerLimit, upperLimit, limit how many rows should we fetch at least/at most > range defines a range (lowerLimit, upperLimit) > now execute the query immediately
  91. 91. Session Pooling > Creating a Session is a potentially expensive operation. (involving network activity, user authentication/authorization, etc.) > A SessionPool stores Session objects for eventual later reuse. > Unused sessions are closed automatically.
  92. 92. Complex Type Mapping > You can create mappings from your own types to database tables. > You do this by specializing the Poco::Data::TypeHandler template for your type.
  93. 93. RecordSet > A generic way to access data in an SQL table (e.g., you dont know the exact schema) > Find out about the columns in a table (name, type, size, etc.) > Get the data from columns as DynamicAny
  94. 94. Session session("SQLite", "sample.db");Statement select(session);select << "SELECT * FROM Person";select.execute();RecordSet rs(select);std::size_t cols = rs.columnCount();for (std::size_t col = 0; col < cols; ++col){ std::cout << rs.columnName(col) << std::endl;}bool more = rs.moveFirst();while (more){ for (std::size_t col = 0; col < cols; ++col) { std::cout << rs[col].convert<std::string>() << " "; } std::cout << std::endl; more = rs.moveNext();}
  95. 95. Q&A
  96. 96. POCO DevConSiliconValley Friday, August 31, 2–6pm Plug and Play Tech Center, Sunnyvale, CARegister and more info at pocodevconsv.eventbrite.com
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.