SlideShare a Scribd company logo
1 of 97
Download to read offline
POCO C++ Libraries
Intro & Overview
Günter Obiltschnig
Founder, POCO C++ Libraries Project
Applied Informatics Software Engineering GmbH
guenter@pocoproject.org
"Without a good library, most
interesting 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++)
The POCO C++ Libraries are...
 >   a collection of C++ class libraries, similar in concept to the Java
     Class Library, the .NET Framework or Apple's 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.
Zip           NetSSL           Tools & Utilities


              Util          Net              Data




                                                              MySQL
                                              SQLite

                                                       ODBC
              XML           Crypto


              Foundation
Application




              C++ and C Standard Libraries


POSIX, WIN32, other (RT)OS API
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++
Objectives and Mission (cont'd)

 >   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
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
History & Milestones
                                                      06.2006
                                                      boost license, new website
08.2004                                          05.2006
project 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
History & Milestones                                         05.2012
                                                               joined wg21
                                                               > 5500 downloads/month

01.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
Windows                Windows
XP/Vista/7/Server   Embedded/Compact (CE)

      OS X                   iOS


     Linux             Embedded Linux




 Server/Desktop        Mobile/Embedded
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).
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
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.
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++ Libraries
Application




              (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
Roadmap
08.2012                        11.2012                   06.2013
release 1.4.4                  release 1.6               release 2.0
production release             production release        c++11 alignment
bugfixes, 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
Getting Started
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.
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)
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
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.
External Dependencies: MySQL
 >   needed by Data/MySQL

 >   get from http://dev.mysql.com/downloads/

 >   or use Linux package
     sudo apt-get install libmysqlclient-dev
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
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
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
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
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
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)
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
Building on Unix/Linux
 >   $ ./configure
     $ make -s -j4
Building on Unix/Linux: Customizing
 >   Don't build samples and testsuites:
     ./configure --no-samples --no-tests

 >   Don't 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
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
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
Example
// 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;
}
# Makefile

include $(POCO_BASE)/build/rules/global

objects = hello

target            = hello
target_libs       = PocoFoundation

include $(POCO_BASE)/build/rules/exec
XML
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

 >   There's also Poco::Util::XMLConfiguration
     for the lazy ones ;-)
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
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.
startDocument()

                                     startElement()

<?xml version="1.0"?>                   startElement()
<root>
        <elem1>
            some text                       characters()
        </elem1>
        <elem2 attr1="val2"             endElement()
                attr2="val3"/>
</root>
                                        startElement()

                                        endElement()

                                      endElement()

                                 endDocument()
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())
#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);
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);
};
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
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;
}
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
<xml version="1.0">
<root>
        <elem1>
            some text
        </elem1>
        <elem2 attr1="val2"
                attr2="val3"/>
</root>


                  Document

                  Element

                                           Attr
        Element                  Element
                                           Attr
          Text
EventTarget


                       Node


Document   Element            CharacterData     ProcessingInstruction



                 Text                         Comment


             CDATASection
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
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 document's AutoReleasePool.
#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();
}
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.
#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);
#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();
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>
Network and Internet
Socket




StreamSocket     ServerSocket       DatagramSocket    RawSocket   ICMPSocket




               SecureServerSocket   MulticastSocket




DialogSocket   SecureStreamSocket

 WebSocket
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 socket's local address and the peer's address
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.
#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;
}
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.
#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;
}
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.
The TCPServer Framework (cont'd)
 >   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.
The TCPServer Framework (cont'd)
 >   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.
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
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
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
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 HTTPServer
srv.start();

waitForTerminationRequest();

// Stop the HTTPServer
srv.stop();
#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;
     }
};
HTTPServerRequest
 >   created by the server

 >   passed as parameter to the HTTPRequestHandler/-Factory

     >   contains URI

     >   cookies

     >   authentification information

     >   HTML form data
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);
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!
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>";
};
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;
Handling Credentials
void 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();
         [...]
    }
}
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);
#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;
};
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
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);
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.
<%@ 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>
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.
#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;
}
SQL Database Access
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
#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();
}
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;
}
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 string

str = "Hi";
insert.execute(); // inserts "Hi"

std::set<std::string> setStr; // [...] init with 100s of strings
Statement bulk(ses << "INSERT INTO Strings VALUES(?)", use(setStr));
bulk.execute();
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
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.
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.
RecordSet
 >   A generic way to access data in an SQL table
     (e.g., you don't know the exact schema)

 >   Find out about the columns in a table
     (name, type, size, etc.)

 >   Get the data from columns as DynamicAny
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();
}
Q&A
POCO
    DevConSiliconValley
              Friday, August 31, 2–6pm

       Plug and Play Tech Center, Sunnyvale, CA

Register and more info at pocodevconsv.eventbrite.com

More Related Content

What's hot

Vb.net session 01
Vb.net session 01Vb.net session 01
Vb.net session 01
Niit Care
 
버전관리를 들어본적 없는 사람들을 위한 DVCS - Git
버전관리를 들어본적 없는 사람들을 위한 DVCS - Git버전관리를 들어본적 없는 사람들을 위한 DVCS - Git
버전관리를 들어본적 없는 사람들을 위한 DVCS - Git
민태 김
 
Presentation web based application|Web designing training center in coimbator...
Presentation web based application|Web designing training center in coimbator...Presentation web based application|Web designing training center in coimbator...
Presentation web based application|Web designing training center in coimbator...
Vignesh026
 
Nakov - .NET Framework Overview - English
Nakov - .NET Framework Overview - EnglishNakov - .NET Framework Overview - English
Nakov - .NET Framework Overview - English
Svetlin Nakov
 
Microsoft Offical Course 20410C_01
Microsoft Offical Course 20410C_01Microsoft Offical Course 20410C_01
Microsoft Offical Course 20410C_01
gameaxt
 

What's hot (20)

Observer pattern with Stl, boost and qt
Observer pattern with Stl, boost and qtObserver pattern with Stl, boost and qt
Observer pattern with Stl, boost and qt
 
Từ Gà Đến Pro Git và GitHub trong 60 phút
Từ Gà Đến Pro Git và GitHub trong 60 phútTừ Gà Đến Pro Git và GitHub trong 60 phút
Từ Gà Đến Pro Git và GitHub trong 60 phút
 
formal verification
formal verificationformal verification
formal verification
 
Using openCV 3.2.0 with CodeBlocks
Using openCV 3.2.0 with CodeBlocksUsing openCV 3.2.0 with CodeBlocks
Using openCV 3.2.0 with CodeBlocks
 
Django Celery
Django Celery Django Celery
Django Celery
 
Fundamental software engineering activities
Fundamental software engineering activitiesFundamental software engineering activities
Fundamental software engineering activities
 
Vb.net session 01
Vb.net session 01Vb.net session 01
Vb.net session 01
 
Advanced task management with Celery
Advanced task management with CeleryAdvanced task management with Celery
Advanced task management with Celery
 
Diving Through The Layers: Investigating runc, containerd, and the Docker eng...
Diving Through The Layers: Investigating runc, containerd, and the Docker eng...Diving Through The Layers: Investigating runc, containerd, and the Docker eng...
Diving Through The Layers: Investigating runc, containerd, and the Docker eng...
 
버전관리를 들어본적 없는 사람들을 위한 DVCS - Git
버전관리를 들어본적 없는 사람들을 위한 DVCS - Git버전관리를 들어본적 없는 사람들을 위한 DVCS - Git
버전관리를 들어본적 없는 사람들을 위한 DVCS - Git
 
SemVer, the whole story
SemVer, the whole storySemVer, the whole story
SemVer, the whole story
 
Introduction of EC-CUBE 4.0
Introduction of EC-CUBE 4.0Introduction of EC-CUBE 4.0
Introduction of EC-CUBE 4.0
 
Cronjob
CronjobCronjob
Cronjob
 
Devops
DevopsDevops
Devops
 
client-server.pptx
client-server.pptxclient-server.pptx
client-server.pptx
 
Presentation web based application|Web designing training center in coimbator...
Presentation web based application|Web designing training center in coimbator...Presentation web based application|Web designing training center in coimbator...
Presentation web based application|Web designing training center in coimbator...
 
Network and System Administration chapter 2
Network and System Administration chapter 2Network and System Administration chapter 2
Network and System Administration chapter 2
 
Git commands
Git commandsGit commands
Git commands
 
Nakov - .NET Framework Overview - English
Nakov - .NET Framework Overview - EnglishNakov - .NET Framework Overview - English
Nakov - .NET Framework Overview - English
 
Microsoft Offical Course 20410C_01
Microsoft Offical Course 20410C_01Microsoft Offical Course 20410C_01
Microsoft Offical Course 20410C_01
 

Viewers also liked

ApacheCon NA11 - Apache Celix, Universal OSGi?
ApacheCon NA11 - Apache Celix, Universal OSGi?ApacheCon NA11 - Apache Celix, Universal OSGi?
ApacheCon NA11 - Apache Celix, Universal OSGi?
abroekhuis
 
Native OSGi, Modular Software Development in a Native World - Alexander Broek...
Native OSGi, Modular Software Development in a Native World - Alexander Broek...Native OSGi, Modular Software Development in a Native World - Alexander Broek...
Native OSGi, Modular Software Development in a Native World - Alexander Broek...
mfrancis
 
Hsu Presentation
Hsu PresentationHsu Presentation
Hsu Presentation
sealt
 
My SQL Idiosyncrasies That Bite OTN
My SQL Idiosyncrasies That Bite OTNMy SQL Idiosyncrasies That Bite OTN
My SQL Idiosyncrasies That Bite OTN
Ronald Bradford
 
What are bleached knots
What are bleached knotsWhat are bleached knots
What are bleached knots
Max Lee
 
Compass Fi Treasury Pp July2008
Compass Fi Treasury Pp July2008Compass Fi Treasury Pp July2008
Compass Fi Treasury Pp July2008
ntrung
 
I care for you, because i love you
I care for you, because i love youI care for you, because i love you
I care for you, because i love you
Renny
 
蘭花草歌
蘭花草歌蘭花草歌
蘭花草歌
Ryan Wong
 

Viewers also liked (20)

Programming IoT Gateways in JavaScript with macchina.io
Programming IoT Gateways in JavaScript with macchina.ioProgramming IoT Gateways in JavaScript with macchina.io
Programming IoT Gateways in JavaScript with macchina.io
 
Browser-based Secure Remote Access for the Internet of Things
Browser-based Secure Remote Access for the Internet of ThingsBrowser-based Secure Remote Access for the Internet of Things
Browser-based Secure Remote Access for the Internet of Things
 
ApacheCon NA11 - Apache Celix, Universal OSGi?
ApacheCon NA11 - Apache Celix, Universal OSGi?ApacheCon NA11 - Apache Celix, Universal OSGi?
ApacheCon NA11 - Apache Celix, Universal OSGi?
 
Programming IoT Gateways with macchina.io
Programming IoT Gateways with macchina.ioProgramming IoT Gateways with macchina.io
Programming IoT Gateways with macchina.io
 
Native OSGi, Modular Software Development in a Native World - Alexander Broek...
Native OSGi, Modular Software Development in a Native World - Alexander Broek...Native OSGi, Modular Software Development in a Native World - Alexander Broek...
Native OSGi, Modular Software Development in a Native World - Alexander Broek...
 
Unit 1 the universe
Unit 1 the universeUnit 1 the universe
Unit 1 the universe
 
Hsu Presentation
Hsu PresentationHsu Presentation
Hsu Presentation
 
Types and Styles of music videos
Types and Styles of music videosTypes and Styles of music videos
Types and Styles of music videos
 
My SQL Idiosyncrasies That Bite OTN
My SQL Idiosyncrasies That Bite OTNMy SQL Idiosyncrasies That Bite OTN
My SQL Idiosyncrasies That Bite OTN
 
What are bleached knots
What are bleached knotsWhat are bleached knots
What are bleached knots
 
Wxig points update
Wxig points updateWxig points update
Wxig points update
 
Compass Fi Treasury Pp July2008
Compass Fi Treasury Pp July2008Compass Fi Treasury Pp July2008
Compass Fi Treasury Pp July2008
 
Know Your Supplier - Rubber & Tyre Machinery World May 2016 Special
Know Your Supplier - Rubber & Tyre Machinery World May 2016 SpecialKnow Your Supplier - Rubber & Tyre Machinery World May 2016 Special
Know Your Supplier - Rubber & Tyre Machinery World May 2016 Special
 
Portfolio
PortfolioPortfolio
Portfolio
 
P1 L2
P1 L2P1 L2
P1 L2
 
I care for you, because i love you
I care for you, because i love youI care for you, because i love you
I care for you, because i love you
 
蘭花草歌
蘭花草歌蘭花草歌
蘭花草歌
 
1.vitamines and coenzymes 31.03.2071
1.vitamines and coenzymes 31.03.20711.vitamines and coenzymes 31.03.2071
1.vitamines and coenzymes 31.03.2071
 
Pd t 27
Pd t 27Pd t 27
Pd t 27
 
Memuary Tetrad 1
Memuary Tetrad 1Memuary Tetrad 1
Memuary Tetrad 1
 

Similar to POCO C++ Libraries Intro and Overview

WS-* Specifications Update 2007
WS-* Specifications Update 2007WS-* Specifications Update 2007
WS-* Specifications Update 2007
Jorgen Thelin
 
OCCIware Project at EclipseCon France 2016, by Marc Dutoo, Open Wide
OCCIware Project at EclipseCon France 2016, by Marc Dutoo, Open WideOCCIware Project at EclipseCon France 2016, by Marc Dutoo, Open Wide
OCCIware Project at EclipseCon France 2016, by Marc Dutoo, Open Wide
OCCIware
 

Similar to POCO C++ Libraries Intro and Overview (20)

O futuro do .NET : O que eu preciso saber
O futuro do .NET : O que eu preciso saberO futuro do .NET : O que eu preciso saber
O futuro do .NET : O que eu preciso saber
 
Cont0519
Cont0519Cont0519
Cont0519
 
Future of .NET - .NET on Non Windows Platforms
Future of .NET - .NET on Non Windows PlatformsFuture of .NET - .NET on Non Windows Platforms
Future of .NET - .NET on Non Windows Platforms
 
Open Source In The World Of Java
Open Source In The World Of JavaOpen Source In The World Of Java
Open Source In The World Of Java
 
.Net: Introduction, trends and future
.Net: Introduction, trends and future.Net: Introduction, trends and future
.Net: Introduction, trends and future
 
Developers’ mDay u Banjoj Luci - Janko Isidorović, Mainflux – Unified IoT Pl...
Developers’ mDay u Banjoj Luci - Janko Isidorović, Mainflux –  Unified IoT Pl...Developers’ mDay u Banjoj Luci - Janko Isidorović, Mainflux –  Unified IoT Pl...
Developers’ mDay u Banjoj Luci - Janko Isidorović, Mainflux – Unified IoT Pl...
 
.Net introduction by Quontra Solutions
.Net introduction by Quontra Solutions.Net introduction by Quontra Solutions
.Net introduction by Quontra Solutions
 
"Wie passen Serverless & Autonomous zusammen?"
"Wie passen Serverless & Autonomous zusammen?""Wie passen Serverless & Autonomous zusammen?"
"Wie passen Serverless & Autonomous zusammen?"
 
Introduction to .net
Introduction to .netIntroduction to .net
Introduction to .net
 
The NRB Group mainframe day 2021 - New Programming Languages on Z - Frank Van...
The NRB Group mainframe day 2021 - New Programming Languages on Z - Frank Van...The NRB Group mainframe day 2021 - New Programming Languages on Z - Frank Van...
The NRB Group mainframe day 2021 - New Programming Languages on Z - Frank Van...
 
WS-* Specifications Update 2007
WS-* Specifications Update 2007WS-* Specifications Update 2007
WS-* Specifications Update 2007
 
EclipseCon 2016 - OCCIware : one Cloud API to rule them all
EclipseCon 2016 - OCCIware : one Cloud API to rule them allEclipseCon 2016 - OCCIware : one Cloud API to rule them all
EclipseCon 2016 - OCCIware : one Cloud API to rule them all
 
OCCIware Project at EclipseCon France 2016, by Marc Dutoo, Open Wide
OCCIware Project at EclipseCon France 2016, by Marc Dutoo, Open WideOCCIware Project at EclipseCon France 2016, by Marc Dutoo, Open Wide
OCCIware Project at EclipseCon France 2016, by Marc Dutoo, Open Wide
 
Building Hopsworks, a cloud-native managed feature store for machine learning
Building Hopsworks, a cloud-native managed feature store for machine learning Building Hopsworks, a cloud-native managed feature store for machine learning
Building Hopsworks, a cloud-native managed feature store for machine learning
 
LinuxONE cavemen mmit 20160505 v1.0
LinuxONE cavemen mmit 20160505 v1.0LinuxONE cavemen mmit 20160505 v1.0
LinuxONE cavemen mmit 20160505 v1.0
 
Docker Seattle Meetup, May 2017
Docker Seattle Meetup, May 2017Docker Seattle Meetup, May 2017
Docker Seattle Meetup, May 2017
 
Flexible delivery options
Flexible delivery options Flexible delivery options
Flexible delivery options
 
.Net Core
.Net Core.Net Core
.Net Core
 
stackconf 2022: It’s Time to Debloat the Cloud with Unikraft
stackconf 2022: It’s Time to Debloat the Cloud with Unikraftstackconf 2022: It’s Time to Debloat the Cloud with Unikraft
stackconf 2022: It’s Time to Debloat the Cloud with Unikraft
 
OpenIO A3techlive in London - March 2016
OpenIO A3techlive in London - March 2016OpenIO A3techlive in London - March 2016
OpenIO A3techlive in London - March 2016
 

Recently uploaded

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
TrustArc
 

Recently uploaded (20)

Quantum Leap in Next-Generation Computing
Quantum Leap in Next-Generation ComputingQuantum Leap in Next-Generation Computing
Quantum Leap in Next-Generation Computing
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Decarbonising Commercial Real Estate: The Role of Operational Performance
Decarbonising Commercial Real Estate: The Role of Operational PerformanceDecarbonising Commercial Real Estate: The Role of Operational Performance
Decarbonising Commercial Real Estate: The Role of Operational Performance
 
Introduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDMIntroduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDM
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
How to Check CNIC Information Online with Pakdata cf
How to Check CNIC Information Online with Pakdata cfHow to Check CNIC Information Online with Pakdata cf
How to Check CNIC Information Online with Pakdata cf
 
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
 
JohnPollard-hybrid-app-RailsConf2024.pptx
JohnPollard-hybrid-app-RailsConf2024.pptxJohnPollard-hybrid-app-RailsConf2024.pptx
JohnPollard-hybrid-app-RailsConf2024.pptx
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
 
ChatGPT and Beyond - Elevating DevOps Productivity
ChatGPT and Beyond - Elevating DevOps ProductivityChatGPT and Beyond - Elevating DevOps Productivity
ChatGPT and Beyond - Elevating DevOps Productivity
 
AI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by AnitarajAI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by Anitaraj
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 

POCO C++ Libraries Intro and Overview

  • 1. POCO C++ Libraries Intro & Overview Günter Obiltschnig Founder, POCO C++ Libraries Project Applied Informatics Software Engineering GmbH guenter@pocoproject.org
  • 2. "Without a good library, most interesting 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.
  • 4. The POCO C++ Libraries are... > a collection of C++ class libraries, similar in concept to the Java Class Library, the .NET Framework or Apple's 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.
  • 5. Zip NetSSL Tools & Utilities Util Net Data MySQL SQLite ODBC XML Crypto Foundation Application C++ and C Standard Libraries POSIX, WIN32, other (RT)OS API
  • 6. 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++
  • 7. Objectives and Mission (cont'd) > 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
  • 8. 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
  • 9. History & Milestones 06.2006 boost license, new website 08.2004 05.2006 project 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
  • 10. History & Milestones 05.2012 joined wg21 > 5500 downloads/month 01.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
  • 11. Windows Windows XP/Vista/7/Server Embedded/Compact (CE) OS X iOS Linux Embedded Linux Server/Desktop Mobile/Embedded
  • 12. 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).
  • 13. 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
  • 14. 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.
  • 15. 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++ Libraries Application (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
  • 16. Roadmap 08.2012 11.2012 06.2013 release 1.4.4 release 1.6 release 2.0 production release production release c++11 alignment bugfixes, 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
  • 18. 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.
  • 19. 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)
  • 20. 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
  • 21. 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.
  • 22. External Dependencies: MySQL > needed by Data/MySQL > get from http://dev.mysql.com/downloads/ > or use Linux package sudo apt-get install libmysqlclient-dev
  • 23. 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
  • 24. 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
  • 25. 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
  • 26. 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
  • 27. 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
  • 28. 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)
  • 29. 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
  • 30. Building on Unix/Linux > $ ./configure $ make -s -j4
  • 31. Building on Unix/Linux: Customizing > Don't build samples and testsuites: ./configure --no-samples --no-tests > Don't 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
  • 32. 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
  • 33. 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
  • 35. // 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; }
  • 36. # Makefile include $(POCO_BASE)/build/rules/global objects = hello target = hello target_libs = PocoFoundation include $(POCO_BASE)/build/rules/exec
  • 37. XML
  • 38. 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 > There's also Poco::Util::XMLConfiguration for the lazy ones ;-)
  • 39. 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
  • 40. 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.
  • 41. startDocument() startElement() <?xml version="1.0"?> startElement() <root> <elem1> some text characters() </elem1> <elem2 attr1="val2" endElement() attr2="val3"/> </root> startElement() endElement() endElement() endDocument()
  • 42. 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())
  • 43. #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);
  • 44. 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); };
  • 45. 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
  • 46. 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; }
  • 47. 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
  • 48. <xml version="1.0"> <root> <elem1> some text </elem1> <elem2 attr1="val2" attr2="val3"/> </root> Document Element Attr Element Element Attr Text
  • 49. EventTarget Node Document Element CharacterData ProcessingInstruction Text Comment CDATASection
  • 50. 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
  • 51. 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 document's AutoReleasePool.
  • 52. #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(); }
  • 53. 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.
  • 54. #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);
  • 55. #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();
  • 56. 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>
  • 58. Socket StreamSocket ServerSocket DatagramSocket RawSocket ICMPSocket SecureServerSocket MulticastSocket DialogSocket SecureStreamSocket WebSocket
  • 59. 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 socket's local address and the peer's address
  • 60. 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.
  • 61. #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; }
  • 62. 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.
  • 63. #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; }
  • 64. 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.
  • 65. The TCPServer Framework (cont'd) > 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.
  • 66. The TCPServer Framework (cont'd) > 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.
  • 67. 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
  • 68. 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
  • 69. 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
  • 70. 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 HTTPServer srv.start(); waitForTerminationRequest(); // Stop the HTTPServer srv.stop();
  • 71. #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; } };
  • 72. HTTPServerRequest > created by the server > passed as parameter to the HTTPRequestHandler/-Factory > contains URI > cookies > authentification information > HTML form data
  • 73. 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);
  • 74. 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!
  • 75. 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>"; };
  • 76. 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;
  • 77. Handling Credentials void 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(); [...] } }
  • 78. 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);
  • 79. #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; };
  • 80. 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
  • 81. 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);
  • 82. 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.
  • 83. <%@ 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>
  • 84. 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.
  • 85. #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; }
  • 87. 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
  • 88. #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(); }
  • 89. 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; }
  • 90. 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 string str = "Hi"; insert.execute(); // inserts "Hi" std::set<std::string> setStr; // [...] init with 100s of strings Statement bulk(ses << "INSERT INTO Strings VALUES(?)", use(setStr)); bulk.execute();
  • 91. 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
  • 92. 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.
  • 93. 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.
  • 94. RecordSet > A generic way to access data in an SQL table (e.g., you don't know the exact schema) > Find out about the columns in a table (name, type, size, etc.) > Get the data from columns as DynamicAny
  • 95. 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(); }
  • 96. Q&A
  • 97. POCO DevConSiliconValley Friday, August 31, 2–6pm Plug and Play Tech Center, Sunnyvale, CA Register and more info at pocodevconsv.eventbrite.com