File: 00100-GuidedTour.html

package info (click to toggle)
poco-doc 1.3.6-1
  • links: PTS
  • area: main
  • in suites: buster, jessie, jessie-kfreebsd, squeeze, stretch, wheezy
  • size: 10,076 kB
  • ctags: 9,611
  • sloc: makefile: 31
file content (322 lines) | stat: -rw-r--r-- 21,037 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>A Guided Tour of the POCO C++ Libraries</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<meta name="author" content="Applied Informatics Software Engineering GmbH and Contributors"/>
<meta name="publisher" content="Applied Informatics Software Engineering GmbH and Contributors"/>
<meta name="copyright" content="Copyright (c) 2009, Applied Informatics Software Engineering GmbH and Contributors"/>
<meta name="language" content="en"/>
<meta name="date" content="2009-11-24"/>
<meta name="generator" content="PocoDoc"/>
<link rel="stylesheet" href="css/styles.css" type="text/css"/>
</head>
<body bgcolor="#ffffff" leftmargin="0" topmargin="0">
<div class="header">
<h1 class="category">Introduction</h1>
<h1 class="title">A Guided Tour of the POCO C++ Libraries</h1>
</div>
<div class="body">
<h2>Contents</h2>
<div class="toc"><ul>
<li class="level1"><a href="#0">Introduction</a></li>
<li class="level1"><a href="#1">The Foundation Library</a></li>
<li class="level1"><a href="#2">The XML Library</a></li>
<li class="level1"><a href="#3">The Util Library</a></li>
<li class="level1"><a href="#4">The Net Library</a></li>
<li class="level1"><a href="#5">Putting It All Together</a></li>
</ul></div>
<div class="description">
<p></p><h2><a name="0">Introduction</a></h2><p>
</p>
<p>The POCO C++ Libraries are a collection of open source C++ class libraries that simplify and accelerate the development of network-centric, portable applications in C++. The libraries integrate perfectly with the C++ Standard Library and fill many of the functional gaps left open by it. Their modular and efficient design and implementation makes the POCO C++ Libraries extremely well suited for embedded development, an area where the C++ programming language is becoming increasingly popular, due to its suitability for both low-level (device I/O, interrupt handlers, etc.) and high-level object-oriented development. Of course, POCO is also ready for enterprise-level challenges. </p>
<p></p> <img src="images/poco.png" width="320" height="255" alt="POCO Libraries" border="0"> <p> </p>
<p>POCO consists of four core libraries, and a number of add-on libraries. The core libraries are Foundation, XML, Util and Net. Two of the add-on libraries are NetSSL, providing SSL support for the network classes in the Net library, and Data, a library for uniformly accessing different SQL databases.  POCO aims to be for network-centric, cross-platform C++ software development what Apple's Cocoa is for Mac development, or Ruby on Rails is for Web development &mdash; a powerful, yet easy and fun to use platform to build your applications upon. POCO is built strictly using standard ANSI/ISO C++, including the standard library. The contributors attempt to find a good balance between using advanced C++ features and keeping the classes comprehensible and the code clean, consistent and easy to maintain. </p>
<p></p>
<p></p><h2><a name="1">The Foundation Library</a></h2><p>
</p>
<p>The Foundation library makes up the heart of POCO. It contains the underlying platform abstraction layer, as well as frequently used utility classes and functions. The Foundation library contains types for fixed-size integers, functions for converting integers between byte orders, an <a href="Poco.Any.html" title="class Poco::Any">Poco::Any</a> class (based on <tt>boost::Any</tt>), utilities for error handling and debugging, including various exception classes and support for assertions. Also available are a number of classes for memory management, including reference counting based smart pointers, as well as classes for buffer management and memory pools. For string handling, POCO contains a number of functions that among other things, trim strings, perform case insensitive comparisons and case conversions. Basic support for Unicode text is also available in the form of classes that convert text between different character encodings, including UTF-8 and UTF-16. Support for formatting and parsing numbers is there, including a typesafe variant of sprintf. Regular expressions based on the well-known PCRE library (<a href="http://www.pcre.org" target="_blank">http://www.pcre.org</a>) are provided as well.  </p>
<p>POCO gives you classes for handling dates and times in various variants.  For accessing the file system, POCO has <a href="Poco.File.html" title="class Poco::File">Poco::File</a> and <a href="Poco.Path.html" title="class Poco::Path">Poco::Path</a> classes, as well as a <a href="Poco.DirectoryIterator.html" title="class Poco::DirectoryIterator">Poco::DirectoryIterator</a> class. In many applications, some parts of the application need to tell other parts that something has happened. In POCO, <a href="Poco.NotificationCenter.html" title="class Poco::NotificationCenter">Poco::NotificationCenter</a>, <a href="Poco.NotificationQueue.html" title="class Poco::NotificationQueue">Poco::NotificationQueue</a> and events (similar to C# events) make this easy. The following example shows how POCO events can be used. In this example, class <tt>Source</tt> has a public event named <tt>theEvent</tt>, having an argument of type int. Subscribers can subscribe by calling <tt>operator +=</tt> and unsubscribe by calling <tt>operator -=</tt>, passing a pointer to an object and a pointer to a member function. The event can be fired by calling <tt>operator ()</tt>, as its done in <tt>Source::fireEvent()</tt>. </p>
<p></p>
<pre>#include &quot;Poco/BasicEvent.h&quot;
#include &quot;Poco/Delegate.h&quot;
#include &lt;iostream&gt;

using Poco::BasicEvent;
using Poco::Delegate;

class Source
{
public:
    BasicEvent&lt;int&gt; theEvent;

    void fireEvent(int n)
    {
        theEvent(this, n);
    }
};

class Target
{
public:
    void onEvent(const void* pSender, int&amp; arg)
    {
        std::cout &lt;&lt; &quot;onEvent: &quot; &lt;&lt; arg &lt;&lt; std::endl;
    }
};

int main(int argc, char** argv)
{
    Source source;
    Target target;

    source.theEvent += Delegate&lt;Target, int&gt;(
        &amp;target, &amp;Target::onEvent);

    source.fireEvent(42);

    source.theEvent -= Delegate&lt;Target, int&gt;(
        &amp;target, &amp;Target::onEvent);

    return 0;
}
</pre>
<p> </p>
<p></p>
<p>The stream classes available in POCO have already been mentioned. These are augmented by <a href="Poco.BinaryReader.html" title="class Poco::BinaryReader">Poco::BinaryReader</a> and <a href="Poco.BinaryWriter.html" title="class Poco::BinaryWriter">Poco::BinaryWriter</a> for writing binary data to streams, automatically and transparently handling byte order issues.  </p>
<p>In complex multithreaded applications, the only way to find problems or bugs is by writing extensive logging information. POCO provides a powerful and extensible logging framework that supports filtering, routing to different channels, and formatting of log messages. Log messages can be written to the console, a file, the Windows Event Log, the Unix syslog daemon, or to the network. If the channels provided by POCO are not sufficient, it is easy to extend the logging framework with new classes.  </p>
<p>For loading (and unloading) shared libraries at runtime, POCO has a low-level <a href="Poco.SharedLibrary.html" title="class Poco::SharedLibrary">Poco::SharedLibrary</a> class. Based on it is the <a href="Poco.ClassLoader.html" title="class Poco::ClassLoader">Poco::ClassLoader</a> class template and supporting framework, allowing dynamic loading and unloading of C++ classes at runtime, similar to what's available to Java and .NET developers. The class loader framework also makes it a breeze to implement plug-in support for applications in a platform-independent way.  </p>
<p>Finally, POCO Foundation contains multithreading abstractions at different levels. Starting with a <a href="Poco.Thread.html" title="class Poco::Thread">Poco::Thread</a> class and the usual synchronization primitives (<a href="Poco.Mutex.html" title="class Poco::Mutex">Poco::Mutex</a>, <a href="Poco.ScopedLock.html" title="class Poco::ScopedLock">Poco::ScopedLock</a>, <a href="Poco.Event.html" title="class Poco::Event">Poco::Event</a>,  <a href="Poco.Semaphore.html" title="class Poco::Semaphore">Poco::Semaphore</a>, <a href="Poco.RWLock.html" title="class Poco::RWLock">Poco::RWLock</a>), a <a href="Poco.ThreadPool.html" title="class Poco::ThreadPool">Poco::ThreadPool</a> class and support for  thread-local storage, also high level abstractions like active objects are  available. Simply speaking, an active object is an object that has methods executing in their own thread. This makes asynchronous member function calls possible &mdash; call a member function, while the function executes, do a bunch of other things, and, eventually, obtain the function's return value. The following example shows how this is done in POCO. The <tt>ActiveAdder</tt> class in defines an active method <tt>add()</tt>, implemented by the <tt>addImpl()</tt> member function. Invoking the active method in <tt>main()</tt> yields an <a href="Poco.ActiveResult.html" title="class Poco::ActiveResult">Poco::ActiveResult</a> (also known as a future), that eventually receives the function's return value. </p>
<p></p>
<pre>#include &quot;Poco/ActiveMethod.h&quot;
#include &quot;Poco/ActiveResult.h&quot;
#include &lt;utility&gt;

using Poco::ActiveMethod;
using Poco::ActiveResult;

class ActiveAdder
{
public:
    ActiveObject(): activeAdd(this, &amp;ActiveAdder::add)
    {
    }

    ActiveMethod&lt;int, std::pair&lt;int, int&gt;, ActiveAdder&gt; add;

private:
    int addImpl(const std::pair&lt;int, int&gt;&amp; args)
    {
        return args.first + args.second;
    }
};

int main(int argc, char** argv)
{
    ActiveAdder adder;

    ActiveResult&lt;int&gt; sum = adder.add(std::make_pair(1, 2));
    // do other things
    sum.wait();
    std::cout &lt;&lt; sum.data() &lt;&lt; std::endl;

    return 0;
}
</pre>
<p> </p>
<p></p>
<p></p><h2><a name="2">The XML Library</a></h2><p>
</p>
<p>The POCO XML library provides support for reading, processing and writing XML. Following one's of POCO's guiding principles &mdash; don't try to reinvent things that already work &mdash; POCO's XML library supports the industry-standard SAX (version 2) and DOM interfaces, familiar to many developers with XML experience. SAX, the Simple API for XML (<a href="http://www.saxproject.org" target="_blank">http://www.saxproject.org</a>), defines an event-based interface for reading XML. A SAX-based XML parser reads through the XML document and notifies the application whenever it encounters an element, character data, or other XML artifact. A SAX parser does not need to load the complete XML document into memory, so it can be used to parse huge XML files efficiently. In contrast, DOM (Document Object Model, <a href="http://www.w3.org/DOM/" target="_blank">http://www.w3.org/DOM/</a>) gives the application  complete access to an XML document, using a tree-style object hierarchy. For this to work, the DOM parser provided by POCO has to load the entire document into memory. To reduce the memory footprint of the DOM document, the POCO DOM implementation uses string pooling, storing frequently occuring strings such as element and attribute names only once. The XML library is based on the Expat open source XML parser library (<a href="http://www.libexpat.org" target="_blank">http://www.libexpat.org</a>).  Built on top of Expat are the SAX interfaces, and built on top of the SAX interfaces is the DOM implementation. For strings, the XML library uses <tt>std::string</tt>, with characters encoded in UTF-8. This makes interfacing the XML library to other parts of the application easy. Support for XPath and XSLT will be available in a future release. </p>
<p></p>
<p></p><h2><a name="3">The Util Library</a></h2><p>
</p>
<p>The Util library has a somewhat misleading name, as it basically contains a framework for creating command-line and server applications. Included is support for handling command line arguments (validation, binding to configuration properties, etc.) and managing configuration information. Different configuration file formats are supported &mdash; Windows-style INI files, Java-style property files, XML files and the Windows registry.  </p>
<p>For server applications, the framework provides transparent support for Windows services and Unix daemons. Every server application can be registered and run as a Windows service, with no extra code required. Of course, all server applications can still be executed from the command line, which makes testing and debugging easier. </p>
<p></p>
<p></p><h2><a name="4">The Net Library</a></h2><p>
</p>
<p>POCO's Net library makes it easy to write network-based applications. No matter whether your application simply needs to send data over a plain TCP socket, or whether your application needs a full-fledged built-in HTTP server, you will find something useful in the Net library.  </p>
<p>At the lowest level, the Net library contains socket classes, supporting TCP stream and server sockets, UDP sockets, multicast sockets, ICMP and raw sockets. If your application needs secure sockets, these are available in the NetSSL library, implemented using OpenSSL (<a href="http://www.openssl.org" target="_blank">http://www.openssl.org</a>).  Based on the socket classes are two frameworks for building TCP servers &mdash; one for multithreaded servers (one thread per connection, taken from a thread pool), one for servers based on the Acceptor-Reactor pattern. The multithreaded <a href="Poco.Net.TCPServer.html" title="class Poco::Net::TCPServer">Poco::Net::TCPServer</a> class and its supporting framework are also the foundation for POCO's HTTP server implementation (<a href="Poco.Net.HTTPServer.html" title="class Poco::Net::HTTPServer">Poco::Net::HTTPServer</a>).  On the client side, the Net library provides classes for talking to HTTP servers,  for sending and receiving files using the FTP protocol, for sending mail messages (including attachments) using SMTP and for receiving mail from a POP3 server. </p>
<p></p>
<p></p><h2><a name="5">Putting It All Together</a></h2><p>
</p>
<p>The following example shows the implementation of a simple HTTP server using the POCO libraries. The server returns a HTML document showing the current date and time. The application framework is used to build a server application that can run as a Windows service, or Unix daemon process. Of course, the same executable can also directly be started from the shell. For use with the HTTP server framework, a <tt>TimeRequestHandler</tt> class is defined that servers incoming requests by returning a HTML document containing the current date and time. Also, for each incoming request, a message is logged using the logging framework. Together with the <tt>TimeRequestHandler</tt> class, a corresponding factory class, <tt>TimeRequestHandlerFactory</tt> is needed; an instance of the factory is passed to the HTTP server object. The <tt>HTTPTimeServer</tt> application class defines a command line argument help by overriding the <tt>defineOptions()</tt> member function of <a href="Poco.Util.ServerApplication.html" title="class Poco::Util::ServerApplication">Poco::Util::ServerApplication</a>. It also reads in the default application configuration file (in <tt>initialize()</tt>) and obtains the value of some configuration properties in <tt>main()</tt>, before starting the HTTP server. </p>
<p></p>
<pre>#include &quot;Poco/Net/HTTPServer.h&quot;
#include &quot;Poco/Net/HTTPRequestHandler.h&quot;
#include &quot;Poco/Net/HTTPRequestHandlerFactory.h&quot;
#include &quot;Poco/Net/HTTPServerParams.h&quot;
#include &quot;Poco/Net/HTTPServerRequest.h&quot;
#include &quot;Poco/Net/HTTPServerResponse.h&quot;
#include &quot;Poco/Net/HTTPServerParams.h&quot;
#include &quot;Poco/Net/ServerSocket.h&quot;
#include &quot;Poco/Timestamp.h&quot;
#include &quot;Poco/DateTimeFormatter.h&quot;
#include &quot;Poco/DateTimeFormat.h&quot;
#include &quot;Poco/Exception.h&quot;
#include &quot;Poco/ThreadPool.h&quot;
#include &quot;Poco/Util/ServerApplication.h&quot;
#include &quot;Poco/Util/Option.h&quot;
#include &quot;Poco/Util/OptionSet.h&quot;
#include &quot;Poco/Util/HelpFormatter.h&quot;
#include &lt;iostream&gt;

using Poco::Net::ServerSocket;
using Poco::Net::HTTPRequestHandler;
using Poco::Net::HTTPRequestHandlerFactory;
using Poco::Net::HTTPServer;
using Poco::Net::HTTPServerRequest;
using Poco::Net::HTTPServerResponse;
using Poco::Net::HTTPServerParams;
using Poco::Timestamp;
using Poco::DateTimeFormatter;
using Poco::DateTimeFormat;
using Poco::ThreadPool;
using Poco::Util::ServerApplication;
using Poco::Util::Application;
using Poco::Util::Option;
using Poco::Util::OptionSet;
using Poco::Util::OptionCallback
using Poco::Util::HelpFormatter;

class TimeRequestHandler: public HTTPRequestHandler
{
public:
    TimeRequestHandler(const std::string&amp; format): _format(format)
    {
    }

    void handleRequest(HTTPServerRequest&amp; request,
                       HTTPServerResponse&amp; response)
    {
        Application&amp; app = Application::instance();
        app.logger().information(&quot;Request from &quot;
            + request.clientAddress().toString());

        Timestamp now;
        std::string dt(DateTimeFormatter::format(now, _format));

        response.setChunkedTransferEncoding(true);
        response.setContentType(&quot;text/html&quot;);

        std::ostream&amp; ostr = response.send();
        ostr &lt;&lt; &quot;&lt;html&gt;&lt;head&gt;&lt;title&gt;HTTPTimeServer powered by &quot;
                &quot;POCO C++ Libraries&lt;/title&gt;&quot;;
        ostr &lt;&lt; &quot;&lt;meta http-equiv=\&quot;refresh\&quot; content=\&quot;1\&quot;&gt;&lt;/head&gt;&quot;;
        ostr &lt;&lt; &quot;&lt;body&gt;&lt;p style=\&quot;text-align: center; &quot;
                &quot;font-size: 48px;\&quot;&gt;&quot;;
        ostr &lt;&lt; dt;
        ostr &lt;&lt; &quot;&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;&quot;;
    }

private:
    std::string _format;
};

class TimeRequestHandlerFactory: public HTTPRequestHandlerFactory
{
public:
    TimeRequestHandlerFactory(const std::string&amp; format):
        _format(format)
    {
    }

    HTTPRequestHandler* createRequestHandler(
        const HTTPServerRequest&amp; request)
    {
        if (request.getURI() == &quot;/&quot;)
            return new TimeRequestHandler(_format);
        else
            return 0;
    }

private:
    std::string _format;
};

class HTTPTimeServer: public Poco::Util::ServerApplication
{
public:
    HTTPTimeServer(): _helpRequested(false)
    {
    }

    ~HTTPTimeServer()
    {
    }

protected:
    void initialize(Application&amp; self)
    {
        loadConfiguration();
        ServerApplication::initialize(self);
    }

    void uninitialize()
    {
        ServerApplication::uninitialize();
    }

    void defineOptions(OptionSet&amp; options)
    {
        ServerApplication::defineOptions(options);

        options.addOption(
        Option(&quot;help&quot;, &quot;h&quot;, &quot;display argument help information&quot;)
            .required(false)
            .repeatable(false)
            .callback(OptionCallback&lt;HTTPTimeServer&gt;(
                this, &amp;HTTPTimeServer::handleHelp)));
    }

    void handleHelp(const std::string&amp; name, 
                    const std::string&amp; value)
    {
        HelpFormatter helpFormatter(options());
        helpFormatter.setCommand(commandName());
        helpFormatter.setUsage(&quot;OPTIONS&quot;);
        helpFormatter.setHeader(
            &quot;A web server that serves the current date and time.&quot;);
        helpFormatter.format(std::cout);
        stopOptionsProcessing();
        _helpRequested = true;
    }

    int main(const std::vector&lt;std::string&gt;&amp; args)
    {
        if (!_helpRequested)
        {
            unsigned short port = (unsigned short)
                config().getInt(&quot;HTTPTimeServer.port&quot;, 9980);
            std::string format(
                config().getString(&quot;HTTPTimeServer.format&quot;, 
                                   DateTimeFormat::SORTABLE_FORMAT));

            ServerSocket svs(port);
            HTTPServer srv(new TimeRequestHandlerFactory(format), 
                svs, new HTTPServerParams);
            srv.start();
            waitForTerminationRequest();
            srv.stop();
        }
        return Application::EXIT_OK;
    }

private:
    bool _helpRequested;
};

int main(int argc, char** argv)
{
    HTTPTimeServer app;
    return app.run(argc, argv);
}
</pre>
<p> </p>
<p></p>
</div>
<p class="footer">POCO C++ Libraries 1.3.6-all<br />
Copyright &copy; 2009, <a href="http://pocoproject.org/" target="_blank">Applied Informatics Software Engineering GmbH and Contributors</a></p>
</body>
</html>