poco c++ libraries intro and overview

97
POCO C++ Libraries Intro & Overview Günter Obiltschnig Founder, POCO C++ Libraries Project Applied Informatics Software Engineering GmbH [email protected]

Upload: guenter-obiltschnig

Post on 07-Dec-2014

1.546 views

Category:

Technology


9 download

DESCRIPTION

 

TRANSCRIPT

Page 1: POCO C++ Libraries Intro and Overview

POCO C++ Libraries Intro & Overview

Günter ObiltschnigFounder, POCO C++ Libraries ProjectApplied Informatics Software Engineering [email protected]

Page 2: POCO C++ Libraries Intro and Overview

"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++)

Page 3: POCO C++ Libraries Intro and Overview
Page 4: POCO C++ Libraries Intro and Overview

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.

Page 5: POCO C++ Libraries Intro and Overview

POSIX, WIN32, other (RT)OS API

Foundation

XML

C++ and C Standard Libraries

Appl

icat

ion

Crypto

Util

NetSSL

Data

SQLi

te

OD

BC

MyS

QL

Zip

Net

Tools & Utilities

Page 6: POCO C++ Libraries Intro and Overview

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++

Page 7: POCO C++ Libraries Intro and Overview

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

Page 8: POCO C++ Libraries Intro and Overview

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

Page 9: POCO C++ Libraries Intro and Overview

History & Milestones

08.2004project started

05.2006> 1000 downloads/month

03.2005!rst contributor

11.2006!rst major commercial user (> 100 devs)03.2006

release 1.1applied informatics founded

02.2005!rst release on sourceforge

01.2006release 1.0

06.2006boost license, new website

Page 10: POCO C++ Libraries Intro and Overview

History & Milestones

01.2011> 5000 downloads/month

05.2012joined wg21> 5500 downloads/month

01.2007> 2000 downloads/month

05.2007relese 1.3

12.2010release 1.4

08.2012work on 1.5/1.6

12.2008bjarne mentions poco in interview

Page 11: POCO C++ Libraries Intro and Overview

Windows XP/Vista/7/Server

OS X

Linux

Server/Desktop Mobile/Embedded

WindowsEmbedded/Compact (CE)

iOS

Embedded Linux

Page 12: POCO C++ Libraries Intro and Overview

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 theweb server from the Net library has a staticallylinked 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).

Page 13: POCO C++ Libraries Intro and Overview

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

Page 14: POCO C++ Libraries Intro and Overview

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.

Page 15: POCO C++ Libraries Intro and Overview

POSIX, WIN32, other (RT)OS API

POCO C++ Libraries(Foundation, XML, Crypto, Net, NetSSL, Data, Util, Zip)

Remoting

Code Generator

C++ and C Standard Libraries

Appl

icat

ion

Binary SOAP

OSP Universal Plug and Play

Bundle Creator

Standard Services

Commercial Open Source Third party/customer-specific

Fast Infoset ZeroconfUPnP Core

HTTPMU, SSDP

SOAP, GENA

Devices & Services

Device Management

Page 16: POCO C++ Libraries Intro and Overview

Roadmap

08.2012release 1.4.4production releasebug!xes, minor new features

11.2012release 1.6production releasebased on 1.5 dev branch

06.2013release 2.0c++11 alignment

09.2012release 1.5development releasenew data librarymajor new features

01.2013release 1.4.5bug!xes

Page 17: POCO C++ Libraries Intro and Overview

Getting Started

Page 18: POCO C++ Libraries Intro and Overview

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.

Page 19: POCO C++ Libraries Intro and Overview

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)

Page 20: POCO C++ Libraries Intro and Overview

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 Productionshttp://www.slproweb.com/products/Win32OpenSSL.html

> or build from source

Page 21: POCO C++ Libraries Intro and Overview

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.

Page 22: POCO C++ Libraries Intro and Overview

External Dependencies: MySQL

> needed by Data/MySQL

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

> or use Linux packagesudo apt-get install libmysqlclient-dev

Page 23: POCO C++ Libraries Intro and Overview

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

Page 24: POCO C++ Libraries Intro and Overview

Building on Windows: Configurations

debug release

static_md PocoFoundationmdd.lib PocoFoundationmd.lib

static_mt PocoFoundationmtd.lib PocoFoundationmt.lib

shared PocoFoundationd.dll PocoFoundation.dll

Build Results

Page 25: POCO C++ Libraries Intro and Overview

Building on Windows: Configurations

debug release

static_md msvcpXXd.dllmsvcrXXd.dll

msvcpXX.dllmsvcrXX.dll

static_mt – –

shared msvcpXXd.dllmsvcrXXd.dll

msvcpXX.dllmsvcrXX.dll

Runtime Dependencies

Page 26: POCO C++ Libraries Intro and Overview

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

Page 27: POCO C++ Libraries Intro and Overview

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 nosamplesImportant: run from Visual Studio 2008 x64 Cross Tools Command Prompt

> show all options – launch buildwin with no arguments

Page 28: POCO C++ Libraries Intro and Overview

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:binbin\static_md (statically linked, multithreaded DLL, new in 1.4)bin\static_mt (statically linked, multithreaded, new in 1.4)

Page 29: POCO C++ Libraries Intro and Overview

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

Page 30: POCO C++ Libraries Intro and Overview

Building on Unix/Linux

> $ ./configure$ make -s -j4

Page 31: POCO C++ Libraries Intro and Overview

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

Page 32: POCO C++ Libraries Intro and Overview

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

Page 33: POCO C++ Libraries Intro and Overview

Building on Unix/Linux: Environment

> Set environment variable POCO_BASE:export POCO_BASE=/ws/poco-1.4cd $POCO_BASE/XMLmake -s -j4

> Use a specific build configuration:export POCO_CONFIG=DigiEL

> Clean rebuild:make cleanmake -s -j4

Page 34: POCO C++ Libraries Intro and Overview

Example

Page 35: POCO C++ Libraries Intro and Overview

// 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;}

Page 36: POCO C++ Libraries Intro and Overview

# Makefile

include $(POCO_BASE)/build/rules/global

objects = hello

target = hellotarget_libs = PocoFoundation

include $(POCO_BASE)/build/rules/exec

Page 37: POCO C++ Libraries Intro and Overview

XML

Page 38: POCO C++ Libraries Intro and Overview

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::XMLConfigurationfor the lazy ones ;-)

Page 39: POCO C++ Libraries Intro and Overview

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

Page 40: POCO C++ Libraries Intro and Overview

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.

Page 41: POCO C++ Libraries Intro and Overview

<?xml version="1.0"?><root>

<elem1> some text </elem1> <elem2 attr1="val2" attr2="val3"/>

</root>

startDocument()

startElement()

startElement()

characters()

endElement()

startElement()

endElement()

endElement()

endDocument()

Page 42: POCO C++ Libraries Intro and Overview

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())

Page 43: POCO C++ Libraries Intro and Overview

#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);

Page 44: POCO C++ Libraries Intro and Overview

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);};

Page 45: POCO C++ Libraries Intro and Overview

> 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

SAX Parser Configuration

Page 46: POCO C++ Libraries Intro and Overview

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;}

Page 47: POCO C++ Libraries Intro and Overview

> 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

The Document Object Model

Page 48: POCO C++ Libraries Intro and Overview

<xml version="1.0"><root>

<elem1> some text </elem1> <elem2 attr1="val2" attr2="val3"/>

</root>

Document

Element

Text

Element ElementAttr

Attr

Page 49: POCO C++ Libraries Intro and Overview

EventTarget

Node

Document Element ProcessingInstructionCharacterData

Text

CDATASection

Comment

Page 50: POCO C++ Libraries Intro and Overview

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

Page 51: POCO C++ Libraries Intro and Overview

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.

Page 52: POCO C++ Libraries Intro and Overview

#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();}

Page 53: POCO C++ Libraries Intro and Overview

> 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.

Creating XML Documents

Page 54: POCO C++ Libraries Intro and Overview

#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);

Page 55: POCO C++ Libraries Intro and Overview

#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();

Page 56: POCO C++ Libraries Intro and Overview

> The DOM parser offers minimal XPath support for finding elements and attributes in DOM trees.

> Node* getNodeByPath(const XMLString& path) constsearches a node (element or attribute) based on a simplified XPath expression:

> elem1/elem2/elem3

> /elem1/elem2[1]

> /elem1/elem2[@attr1]

> //elem1/elem2[@attr1='value2']

DOM and XPath

<root> <elem1> <elem2 attr1="value1"> <elem3> </elem3> </elem2> <elem2 attr1="value2"> </elem2> </elem1></root>

Page 57: POCO C++ Libraries Intro and Overview

Network and Internet

Page 58: POCO C++ Libraries Intro and Overview

Socket

StreamSocket ServerSocket DatagramSocket RawSocket

DialogSocket

MulticastSocket

ICMPSocket

SecureServerSocket

SecureStreamSocket

WebSocket

Page 59: POCO C++ Libraries Intro and Overview

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

Page 60: POCO C++ Libraries Intro and Overview

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.

Page 61: POCO C++ Libraries Intro and Overview

#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.1\r\n" "Host: www.appinf.com\r\n" "\r\n";str.flush();

Poco::StreamCopier::copyStream(str, std::cout);

return 0;}

Page 62: POCO C++ Libraries Intro and Overview

> 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.

The ServerSocket Class

Page 63: POCO C++ Libraries Intro and Overview

#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 OK\r\n" "Content-Type: text/html\r\n" "\r\n" "<html><head><title>My 1st Web Server</title></head>" "<body><h1>Hello, world!</h1></body></html>" << std::flush;

}return 0;

}

Page 64: POCO C++ Libraries Intro and Overview

> 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

Page 65: POCO C++ Libraries Intro and Overview

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.

Page 66: POCO C++ Libraries Intro and Overview

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.

Page 67: POCO C++ Libraries Intro and Overview

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

Page 68: POCO C++ Libraries Intro and Overview

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

Page 69: POCO C++ Libraries Intro and Overview

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

Page 70: POCO C++ Libraries Intro and Overview

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();

Page 71: POCO C++ Libraries Intro and Overview

#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;

} };

Page 72: POCO C++ Libraries Intro and Overview

> created by the server

> passed as parameter to the HTTPRequestHandler/-Factory

> contains URI

> cookies

> authentification information

> HTML form data

HTTPServerRequest

Page 73: POCO C++ Libraries Intro and Overview

HTTPServerResponse

> created by the server but initialized by the request handler

> sets:

> cookies

> content type of the answerresponse.setContentType("text/html");

> either (a) the length of the content or (b) chunked transfer encodingresponse.setContentLength(1024);response.setChunkedTransferEncoding(true);

Page 74: POCO C++ Libraries Intro and Overview

HTTPServerResponse (cont)

> set response typeresponse.setStatus[AndReason]( HTTPResponse::HTTP_OK); // defaultresponse.setStatus[AndReason]( HTTPResponse::HTTP_UNAUTHORIZED)

> after response is fully configured, send the headerstd::ostream& out = response.send();

> if required, write data content to the returned stream

> send() must be invoked exactly once!

Page 75: POCO C++ Libraries Intro and Overview

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>";

};

Page 76: POCO C++ Libraries Intro and Overview

> 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.

Handling Cookies

// set cookie in responsePoco::Net::HTTPCookie cookie(“name”, “Peter”); cookie.setPath(“/”); cookie.setMaxAge(3600); // 1 hour response.addCookie(cookie);

// extract cookie from requestPoco::Net::NameValueCollection cookies; request.getCookies(cookies); Poco::Net::NameValueCollection::ConstIterator it = cookies.find(“name”); std::string userName;if (it != cookies.end())

userName = it->second;

Page 77: POCO C++ Libraries Intro and Overview

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(); [...]

}}

Page 78: POCO C++ Libraries Intro and Overview

HTMLForm

> helper class to handle HTML form data

> 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);

Poco::Net::HTMLForm form(request); form[“entry1”] == “somedata”;

Page 79: POCO C++ Libraries Intro and Overview

#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;

};

Page 80: POCO C++ Libraries Intro and Overview

> 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

HTTP Client

Page 81: POCO C++ Libraries Intro and Overview

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);

Page 82: POCO C++ Libraries Intro and Overview

> 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.

PageCompiler

Page 83: POCO C++ Libraries Intro and Overview

<%@ 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>

Page 84: POCO C++ Libraries Intro and Overview

> 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.

URIStreamOpener

Page 85: POCO C++ Libraries Intro and Overview

#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;}

Page 86: POCO C++ Libraries Intro and Overview

SQL Database Access

Page 87: POCO C++ Libraries Intro and Overview

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

Page 88: POCO C++ Libraries Intro and Overview

#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();}

Page 89: POCO C++ Libraries Intro and Overview

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;}

Page 90: POCO C++ Libraries Intro and Overview

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 stringsStatement bulk(ses << "INSERT INTO Strings VALUES(?)", use(setStr));bulk.execute();

Page 91: POCO C++ Libraries Intro and Overview

> intowhere should we write data to

> usewhere should we read data from

> lowerLimit, upperLimit, limithow many rows should we fetch at least/at most

> rangedefines a range (lowerLimit, upperLimit)

> nowexecute the query immediately

Keywords

Page 92: POCO C++ Libraries Intro and Overview

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.

Page 93: POCO C++ Libraries Intro and Overview

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.

Page 94: POCO C++ Libraries Intro and Overview

> 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

RecordSet

Page 95: POCO C++ Libraries Intro and Overview

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();}

Page 96: POCO C++ Libraries Intro and Overview

Q & A

Page 97: POCO C++ Libraries Intro and Overview

Friday, August 31, 2–6pm

Plug and Play Tech Center, Sunnyvale, CA

Register and more info at pocodevconsv.eventbrite.com

POCODevConSiliconValley