po co samples

37
The C++ Portable Components Getting Started With The Samples Version 1.2

Upload: samlet-wu

Post on 16-Apr-2017

369 views

Category:

Business


0 download

TRANSCRIPT

The C++ Portable Components

Getting Started With The SamplesVersion 1.2

Purpose of This Document

This document gives an overview of the sample applications delivered with the AppliedInformatics C++ Portable Components. The C++ Portable Components are a collection ofclass libraries and frameworks that greatly simplifies the development of network-centric andplatform-independent applications in C++.

The document is targeted at developers and development/technical managers wanting to getan overview of the functionality and features offered by the Applied Informatics C++ PortableComponents. Familiarity with the C++ programming language is assumed.

Validity of This Document

This document covers release 1.1 and later releases of the Applied Informatics C++ PortableComponents.

Copyright, Trademarks, Disclaimer

Copyright © 2006, Applied Informatics. All rights reserved.

All trademarks or registered marks in this document belong to their respective owners.

Information in this document is subject to change without notice and does not represent acommitment on the part of Applied Informatics. This document is provided "as is" withoutwarranty of any kind, either expressed or implied, including, but not limited to, the particularpurpose. Applied Informatics reserves the right to make improvements and/or changes to thisdocument or the products described herein at any time.

Table of Contents1 Introduction............................................................................................................................................. 4

2 Overview of The Samples .................................................................................................................. 52.1 Foundation Samples 52.1.1 ActiveMethod Sample 62.1.2 Activity Sample 72.1.3 Base64Decode and Base64Encode Samples 82.1.4 BinaryReaderWriter Sample 92.1.5 DateTime Sample 102.1.6 Deflate and Inflate Samples 112.1.7 Dir Sample 122.1.8 Grep Sample 132.1.9 HMACmd5 Sample 142.1.10 Logger Sample 152.1.11 MD5 Sample 162.1.12 NotificationQueue Sample 172.1.13 StringTokenizer Sample 182.1.14 Timer Sample 192.1.15 URI Sample 202.1.16 UUIDGen Sample 212.2 XML Samples 222.2.1 DOMParser Sample 232.2.2 DOMWriter Sample 242.2.3 PrettyPrint Sample 252.2.4 SAXParser Sample 262.3 Util Samples 272.3.1 SampleApp Sample 282.3.2 SampleServer Sample 292.4 Net Samples 302.4.1 Dict Sample 312.4.2 Download Sample 322.4.3 EchoServer Sample 332.4.4 HTTPGet Sample 342.4.5 HTTPTimeServer Sample 352.4.6 Mail Sample 362.4.7 TimeServer Sample 37

C++ Portable ComponentsGetting Started With The Samples 4/37

1 IntroductionThis document is intended to demonstrate the most typical usages of thedifferent C++ Portable Components classes. This is achieved by presentingthe samples deployed with the installation of the C++ PortableComponents.

The samples are divided into four main libraries:

• The Foundation library, which provides numerous classes that shieldthe programmer from the underlying operating system applicationprogramming interface (API);

• The XML library, which provides classes and frameworks for readingand writing XML data;

• The Util library, which makes classes available for working withconfiguration files and command line arguments, as well as aframework for building command line tools and server applications;

• The Net library, which holds high level tools to establish connectionsto the outside world. HTTP and TCP servers, Web servers, Webapplications are some of the important concepts of the package.

• The NetSSL library, which adds SSL (Secure Sockets Layer) and TLS(Transport Layer Security) support to the Net library.

The typical subjects treated are:

• Foundation: multi-threading, async. calls, date/time, cryptography,streams, file system, logging and timers.

• XML: DOM and SAX reading and writing utilities.

• Util: Applications, servers, configuration files

• Net: Web servers, TCP servers, HTTP clients and servers.

C++ Portable ComponentsGetting Started With The Samples 5/37

2 Overview of The Samples

2.1 Foundation SamplesThe foundation samples cover most of the important concepts of the library.It offers cross-platform compatibility, making a wise usage of the standardtemplate library. Here is a list of the samples, together with the relatedsubjects:

Sample name Subjects treated

ActiveMethod Async. calls, multi-threading

Activity Async. calls, multi-threading

Base64Encode Cryptography

Base64Decode Cryptography

BinaryReaderWriter Streams

DateTime Date and time utility

Deflate Compression, decompression

Dir File systems

Grep Regular expressions, patterns

HMACmd5 Cryptography

Inflate Compression, decompression

Logger Logging utility

MD5 Cryptography

NotificationQueue Notification systems, threading, thread pools

StringTokenizer Tokenizing

Timer Timer, threading and stopwatches

URI Web links, addresses

UUIDGen Unique identification codes generation

C++ Portable ComponentsGetting Started With The Samples 6/37

2.1.1 ActiveMethod Sample

An active object is an object which have methods that execute in their ownthread, what is called active methods. It is intended to simplify the multi-threading programming complexity.

Example Name: ActiveMethod

Goal: Showing how to use active methods in a context.

Description: The ActiveMethodExample class holds an activemethod (ActiveMethod class) which takes a structureas argument. In this case, the structure contains twointegers, but could be more complex. The structure iscreated and the active method is called. Internally, athread is created and will execute the methodActiveMethodImp(), which calculates the sum of thetwo integers of the structure. The ActiveResult objectconnected to the method will wait until the call of themethod is finished (when the thread has executed themethod, which depends of cpu availability). TheData() value of the result depends of the templatetype given(in this case, an integer). The value isprinted to the screen in the example.

Used FoundationClasses:

ActiveMethod, ActiveResult.

Particularities: These classes are useful for asynchronous methodinvocations.

C++ Portable ComponentsGetting Started With The Samples 7/37

2.1.2 Activity Sample

The Activity class is an object set up to have long running methods thatperform background tasks and active methods, a bit like how threads aregenerally used. This example creates a user-class which contains an Activitymember, with simple start and stop methods to begin or stop the executionof the threaded method, in an asynchronous way.

Example Name: Activity

Goals: Showing how to use the Activity class in anasynchronous context.

Description: The ActivityExample class is instantiated, delegatingits runActivity() method (the method to executeasynchronously) to the Activity context. When theactivity member will be started (thread started), therunActivity() method will be called and will executeits content when the thread that holds the method isexecuted (on the cpu).Afterwards, the activity thread is started and stopped(start() and stop() methods). The runActivity()method writes the status on the screen.

Used FoundationClasses:

Activity, Thread.

Particularities: An active object uses threads to decouple methodexecution from method invocation, or to performtasks autonomously, without intervention of a caller.

C++ Portable ComponentsGetting Started With The Samples 8/37

2.1.3 Base64Decode and Base64Encode Samples

The Base64 technique is used to code streams in respect to the 64 ASCIIcharacters. Some usage of the Base64 encoding/decoding are MIME, UTF-7,IRCu and some URL applications.

Example Name: Base64Decode

Goals: Demonstrate how to decode a Base64 coded stream.

Description: The Base64decode example takes an input stream(file) as argument, gives the stream to the instance ofthe Base64Decoder class and writes the decodedstream into an output stream.

Used FoundationClasses:

Base64Decoder, StreamCopier.

Particularities: Base64 is a coding method using 64 characters (allAscii) often used in emails distribution.

Example Name: Base64Encode

Goals: Demonstrate how to encode a Base64 coded stream.

Description: The Base64encode example takes an input stream(file) as argument, gives the stream to the instance ofthe Base64Encoder class and writes the new encodedstream into an output stream.

Used FoundationClasses:

Base64Encoder, StreamCopier.

Particularities:

C++ Portable ComponentsGetting Started With The Samples 9/37

2.1.4 BinaryReaderWriter Sample

Binary streams typically contain bytes that are intended to be interpreted assomething other than characters. Compiled computer programs are typicalexamples, as the data and CPU instructions they contain can be any binaryvalue. Binary files can also be image files, sound files, compressed versions ofother files (of either type), etc.

Example Name: BinaryReaderWriter

Goals: Showing how to use the Binary reader and writer ofthe Foundation.

Description: The example demonstrates how to use the writer andthe reader. The “<<” and “>>” operators areoverloaded to suite strings, integers, floats, chars andbooleans.

Used FoundationClasses:

BinaryWriter, BinaryReader.

Particularities: The important thing in binary coding is that one hasto know how to decode the stream, e.g. in whichorder comes what type.

C++ Portable ComponentsGetting Started With The Samples 10/37

2.1.5 DateTime Sample

Date and time is in general difficult to determinate with precision in theexact format that is wanted. How many days have June? How to calculatethe number of seconds of the next year, without knowing if it is a leap yearor not? How to format efficiently the results? The DateTime class of theFoundation is a great tool in that direction. The date is precisely calculatedand returned in the desired format, e.g. months as number (1-12) or asstrings (“September” or even its abbreviation “Sept”). The format of thedesired time is given through a format string, e.g.: “%Hh-%mmin-%ssec”would return “24h-32min-12sec”, or through predefined formats.

Example Name: DateTime

Goal: Demonstrate the ease of use of the DateTime class.

Description: It is possible to get the weekday name from the dayof week number, the month name from the monthnumber, the exact number of seconds and so on.This example shows some of these possibilities.

Used FoundationClasses:

DateTime, DateTimeFormat.

Particularities:

C++ Portable ComponentsGetting Started With The Samples 11/37

2.1.6 Deflate and Inflate Samples

Deflation and inflation are used in data compression. In the Foundation, thezlib cross-platform data compression library is used to proceed. DEFLATE isthe compression algorithm.

Example Name: Deflate

Goals: Demonstrate how to deflate bytes that are writteninto a stream.

Description: If the files are valid, the stream of the output file isgiven as argument to the DeflatingOutputStreamclass of the Foundation, telling where to write theprocessed data. The StreamCopier copies the inputstream into the deflater instance, which takes thisstream, compresses the data using zlib's deflatealgorithm, and writes it down into the outputstream. See the Inflate example for the reverse actionusing InflatingInputStream.

Used FoundationClasses:

DeflatingOutputStream, StreamCopier.

Particularities: Input and output files required.

Example Name: Inflate

Goals: Demonstrate how to inflate (decom-pression) bytesthat are written into a stream (which wascompressed with zlib).

Description: Similar to the Deflate example but using theInflatingInputStream class instead anddecompressing a compressed file.

Used FoundationClasses:

InflatingInputStream, StreamCopier.

Particularities: Input and output files required.

C++ Portable ComponentsGetting Started With The Samples 12/37

2.1.7 Dir Sample

In a cross-platform context, directories and files navigation must bewrapped to give to the user a single navigation interface. This is donethrough the DirectoryIterator, File and Path classes of the Foundation.Getting the current directory, changing directory, getting properties of filesand directories are some of the numerous functionalities offered by theclasses.

Example Name: Dir

Goals: Demonstrate how to use the DirectoryIterator andthe Path classes of the Foundation.

Description: The example starts by finding the current directorywhich is given to the DirectoryIterator instance.The DirectoryIterator class is used to enumerate thefiles in a directory. In a loop, all files of theenumeration are questioned about their accesses,dates and types (functionalities of the File class). APath object is created from the path string of each ofthe files. Data is printed on the screen.

Used FoundationClasses:

DirectoryIterator, Path, File.

Particularities:

C++ Portable ComponentsGetting Started With The Samples 13/37

2.1.8 Grep Sample

Grep is a well known application for Unix users. It uses regular expressionsto match with a given stream. A regular expression is a string that describesor matches a set of strings, according to certain syntax rules. It is forexample used for words research in a text.

Example Name: Grep

Goals: Demonstrate the usage of the Regular-Expressionclass, as an implementation of the well-known Grepapplication for Unix users (finds a pattern in astring).

Description: The example takes a string pattern as argument. Thisstring will be used to match similar patterns in thestrings that will be written on the screen by the user.Two options are supported in this example: -i (caseinsensitive matching) and -x (totally ignorewhitespace). A RegularExpression object is createdwith the given pattern and options. The user is thenrequested to enter strings on the screen. If theexample finds the regular expression (a match to thegiven pattern) in the string, it will rewrite the stringon the screen.

Used FoundationClasses:

RegularExpression.

Particularities: A regular expression is a string that describes ormatches a set of strings, according to certain syntaxrules.

C++ Portable ComponentsGetting Started With The Samples 14/37

2.1.9 HMACmd5 Sample

A keyed-hash message authentication code, or HMAC, is a type of messageauthentication code (MAC) calculated using a cryptographic hash functionin combination with a secret key. As with any MAC, it may be used tosimultaneously verify both the data integrity and the authenticity of amessage. Any iterative cryptographic hash function, such as MD5 or SHA-1,may be used in the calculation of an HMAC. In this sample, the MD5Engineis used.

Example Name: HMACmd5

Goals: Demonstrate the usage of the HMACEngine class(cryptography).

Description: The example takes a password (key) and a file pathas argument. The HMACEngine takes the passwordas construction's argument. Then, aDigestOutputStream is created to allow theStreamCopier to copy the content of the input file tothe HMACEngine for processing. Internally, thecontent of the file is broken into blocks, each blockbeing compressed and combined with the password.The HMACEngine.Digest () method returns thehexadecimal authentication code.

Used FoundationClasses:

HMACEngine, MD5Engine, DigestEngine,StreamCopier, DigestOutputStream,

Particularities: • Internally, an iterative hash function breaksup a message into blocks of a fixed size anditerates over them with a compressionfunction.

• MD5 (Message-Digest algorithm 5) is awidely-used cryptographic hash functionwith a 128-bit hash value and is used in thisexample.

C++ Portable ComponentsGetting Started With The Samples 15/37

2.1.10 Logger Sample

Logging is an important component of complex systems. The Logger class ofthe Foundation offers a very efficient way to log messages of differentpriorities to channel streams like files and console. At initialization of theLogger, the minimum message priority is set and will filter further logs withlower priority: e.g. if initialized with CRITICAL, INFORMATION logs willnot be proceeded, while if initialized with TRACE or DEBUG priority, theLogger will log every messages. The handled priorities are (in order): fatal,critical, error, warning, notice, information, debug and trace.

Example Name: Logger

Goals: Demonstrate the usage of the logger class.

Description: The example shows how to log into a file and intothe console, both stream types being implementedthrough channels. It starts by creating the twochannels, using PatternFormatter objects to set thecontent of the logged line. For example, the format"%Y-%m-%d %H:%M:%S" tells the channel to writethe following structure:"Year-Month-Day Hour:Minutes:Seconds". After thecreation of the channels, the two loggers are createdand used to send errors, information and warningsto the channels. During the creation of the loggers,the message priority to follow is set toPRIO_WARNING for the f i l e andPRIO_INFORMATION for the console.

Used FoundationClasses:

Logger, ConsoleChannel, FileChannel,FormattingChannel, PatternFormater, Message.

C++ Portable ComponentsGetting Started With The Samples 16/37

2.1.11 MD5 Sample

In cryptography, MD5 (Message-Digest algorithm 5) is a widely-usedcryptographic hash function with a 128-bit hash value. As an Internetstandard (RFC 1321), MD5 has been employed in a wide variety of securityapplications and is also commonly used to check the integrity of files. TheMD5Engine of the Foundation offers an implementation of it.

Example Name: Md5

Goals: Demonstrate the usage of the MD5 engine digestalgorithm for cryptography.

Description: The MD5 does not use a hash function like forHMAC. A DigestOutputStream object (computes adigest of all the data passing through it, using aDigestEngine) is created with a MD5Engine. Thecontent of the file (argument) is then copied to thestream and processed by the MD5Engine to createthe message digest, which is then printed on thescreen.

Used FoundationClasses:

DigestOutputStream, MD5Engine, StreamCopier,DigestEngine

Particularities:

C++ Portable ComponentsGetting Started With The Samples 17/37

2.1.12 NotificationQueue Sample

NotificationQueue objects maintain notifications (instances of theNotification class of the Foundation) in a First In First Out (FIFO) order. Itprovides a way to implement asynchronous notifications, especially usefulfor sending notifications from one thread to another, for example from abackground thread to the main (user interface) thread.

Example Name: NotificationQueue

Goals: Showing how to use a NotificationQueue, sendingnotifications to working threads.

Description: A NotificationQueue is created and three threads areg e t t i n g a t t a c h e d t o i t ( t h r o u g h_queue.waitDequeueNotification()). These threethreads will process the notifications received (likeobservers), printing the notification data on thescreen (their work). After worker threads are startedby the ThreadPool, notifications are created andadded to the NotificationQueue, to be handled bythe working threads.

Used FoundationClasses:

Runnable, Thread, FastMutex, Notification,NotificationQueue, ThreadPool, Random.

Particularities: A ScopedLock is a class that simplifies threadsynchronization with a mutex. The Mutex is used bythe notifications receivers to protected thenotification data.

C++ Portable ComponentsGetting Started With The Samples 18/37

2.1.13 StringTokenizer Sample

The StringTokenizer class of the Foundation is the best tool to divide astring into tokens (vector of strings). Any kind of separator (or separatorcombinations) can be used, like any ASCII characters.

Example Name: StringTokenizer

Goals: Showing how to use the StringTokenizer class todivide a string into tokens.

Description: A string containing separators is declared: "white;black; magenta, blue, green; yellow". AStringTokenizer object is instantiated with the stringand the separators (“;,”) as arguments. Eachautomatically created token is then accessed throughiterators and printed on the screen.

Used FoundationClasses:

StringTokenizer.

Particularities: Given separators are “;” and “,” but could bedifferent, e.g.: “,” or “;” or “;,” or “ “ or “e”... . Eachcharacter given in the separator string will be used asa an individual separator.The option StringTokenizer::TOK_TRIM is used totrim the tokens from any blank spaces.

C++ Portable ComponentsGetting Started With The Samples 19/37

2.1.14 Timer Sample

The Foundation contains a cross-platform Timer class, which usage isdescribed in this sample.

Example Name: Timer

Goals: Showing how to use a timer, how to handle itscallbacks and how to use the Stopwatch class.

Description: The example uses a TimerExample class to write onthe screen the elapsed time between each ticks of thetimer. During its instantiation, the TimerExampleclass starts a Stopwatch which counts the number ofmilliseconds since its start. A timer (Timer class) isthen started and configured to tick each 500 ms. Itscallback is set to use the OnTimer method of theTimerExample, which will print on the screen theelapsed time until the start of the Stopwatch.

Used FoundationClasses:

Timer, Stopwatch, Thread.

Particularities: A Thread::sleep (5000) will let the timer do its workwithout interruption.

C++ Portable ComponentsGetting Started With The Samples 20/37

2.1.15 URI Sample

A Uniform Resource Identifier (URI) is an Internet protocol elementconsisting of a short string of characters that conform to a certain syntax.The string comprises a name or address that can be used to refer to aresource. It is a fundamental component of the World Wide Web. TheFoundation has its own implementation of the URI class.

Example Name: URI

Goals: Demonstrate how to use the URI class and elementsfrom a web address.

Description: The example is given a web address:" http://www.inf.com:81/sample?example- query#somewhere "which is set to a new URI object. Every part of thelink can be individually requested.E . g . : Uri .getScheme() returns "http",uri.getAuthority() returns www.inf.com:81,uri.getPath() returns /sample.

Used FoundationClasses:

URI

C++ Portable ComponentsGetting Started With The Samples 21/37

2.1.16 UUIDGen Sample

A Universally Unique Identifier is an identifier standard used in softwareconstruction. The intent of UUIDs is to enable distributed systems touniquely identify information without significant central coordination.Thus, anyone can create a UUID and use it to identify something withreasonable confidence that the identifier will never be unintentionally usedby anyone for anything else.

Example Name: UUIDGen

Goals: Demonstrate how to generate a unique identifierwith the UUIDGen class.

Description: The example creates a UUID identifier using theUUIDGenerator class.

Used FoundationClasses:

UUID, UUIDGenerator.

Particularities: A UUID is an identifier that is unique across bothspace and time, with respect to the space of allUUIDs.UUID = Universally Unique Identifier.

C++ Portable ComponentsGetting Started With The Samples 22/37

2.2 XML Samples

Build on top of the Foundation library, the XML package solves all commonproblems related to the reading and writing activities of XML documentsand streams. The samples of this library are grouped in the two main XMLmodels used: the Document Object Model (DOM) and the Simple API forXML (SAX).

Sample name Subjects treated

DOMParser Document Object Model - reading

DOMWriter Document Object Model - writing

PrettyPrint XML pretty printing

SAXParser Simple API for XML - reading

C++ Portable ComponentsGetting Started With The Samples 23/37

2.2.1 DOMParser Sample

The DOMParser class of the XML package parses XML streams followingthe DOM model. A non-conform document will throw specific exceptions.It build an XML tree with all elements which is then accessed through nodes.

Example Name: DOMParser

Goals: Showing how to parse a DOM document and to usethe available methods of the DOMParser.

Description: The sample is given the string:“<html><head></head><bodyonclick="ChangeColor()">Click on thisdocument!</body></html>”. The string is parsed bythe DOMParser and the process returns a XMLdocument. The NodeIterator class is used to iteratethrough all nodes of the document. The nodesreturned by the iterator depend on the NodeFiltergiven, in that case NodeFilter::SHOW_ALL whichshows all nodes. See the WhatToShow enumerationof the NodeFilter class for more choices.Then, the nodeValue and nodeName attributes areprinted out to the screen.

Used XML Classes: DOMParser, AutoPtr, InputSource, NodeIterator,NodeFilter, Node.

Particularities:

C++ Portable ComponentsGetting Started With The Samples 24/37

2.2.2 DOMWriter Sample

Document Object Model (DOM) is a description of how a HTML or XMLdocument is represented in an object-oriented fashion. DOM provides anapplication programming interface to access and modify the content,structure and style of the document. The DOMWriter of the XML packageoffers easy-and-intuitive-to-use methods to build a DOM tree.

Example Name: DOMWriter

Goals: Demonstrate how to use the DOMWriter class andto create well-formed XML documents using itsmethods.

Description: A Document is created and hosts all the objects. Aroot element <root> is created and will hold allsub-elements. A new element <child1> is createdand appended to the <root> element. The text1 isadded to this sub-element <child1>text1</child1>.The process is repeated to add a child2 and a text2to the root element. Now that the document iscompleted, a DOMWriter object is used to writethe stream to an output stream, in this case theconsole. Please note that without thePRETTYPRINT option, there will be no tabs addedand the result will be a single string.

Used XML Classes: AutoPtr, Document, Element, Text, DOMWriter,XMLWriter.

Particularities: Auto pointers (AutoPtr) are used to simplify thehandling of the many pointers. The destruction ofthe pointer is automatically done at the destructionof the AutoPtr object (end of method).

C++ Portable ComponentsGetting Started With The Samples 25/37

2.2.3 PrettyPrint Sample

Pretty printing a XML stream is used to show in an object-oriented way thestream to the user. PrettyPrint is an option of the XMLWriter of the XMLpackage.

Example Name: PrettyPrint

Goals: Showing the result of the pretty print function.

Description: A SAX parser is created and will parse the text thatwill be given in the console. An XMLWriter iscreated, with the pretty print option, and will beused to print the XML data in the console afterformatting. The XML string to give can be, forexample, “< h t m l > < h e a d > < / h e a d > < b o d yoncl ick="ChangeColor()">Click on thisdocument!</body></html>”. This single string willbe reformatted to reach the standard XML view,sub-elements being tabbed within their parents.

Used XML Classes: SAXParser, XMLWritter, WhitespaceFilter,InputSource.

Particularities: The WhitespaceFilter, an implementation of theSAX2 XMLFilter interface, is an XMLReader thatcan be associated with a "parent" reader, in this casethe SAXParser.

C++ Portable ComponentsGetting Started With The Samples 26/37

2.2.4 SAXParser Sample

SAX is a serial access parser API for XML. Sax provides a mechanism forreading data from an XML document. It is a popular alternative to theDocument Object Model (DOM). The SAXParser handles XML informationas a single stream of data. This data stream is unidirectional, such thatpreviously accessed data cannot be re-read without reparsing. Most users ofXML believe that the SAX paradigm results in systematically faster XMLprocessing than DOM. This is attributed to the fact that a SAX stream has aminuscule memory footprint compared to that of a fully constructed DOMtree.

Example Name: SAXParser

Goals: Showing how to build a typical SAX documenthandler.

Description: The class MyHandler is created and set to theSAXParser object as its handler. Some features andproperties are set to the parser: refer tohttp://xml.org/sax/features andhttp://xml.org/sax/properties.

Used XML Classes: ContentHandler, LexicalHandler, Locator,SAXParser, XMLReader

Particularities: The class MyHandler is derived fromContentHandler and LexicalHandler, base classes tohandle SAX parsing. They have abstract methodthat must be implemented by the MyHandler class.The most important method is probably theStartElement() method, because this is where thenode treatment will be held. This method is calledby the parser each time it starts to parse an elementof the tree. You can create the logic in this method,deciding if you need the content of the currentnode.A Locator object is also used to located the currentposition in the stream (row and column numbers).The where() method prints this location on thescreen. There are many oder methods of thehandling class that must me implemented withlogic.

C++ Portable ComponentsGetting Started With The Samples 27/37

2.3 Util Samples

The C++ Portable Components Utilities library makes available classes forworking with configuration files and command line arguments, as well as aframework for building command line tools and server applications. Thetwo following samples demonstrate how to create a simple application and asimple server. A server application is typically expected to run as a daemonprocess on a Unix platform, or as a service on a Windows platform. Theapplication framework classes in the Util library implement the necessaryglue code to achieve this transparently, allowing the same executable to runeither from the command line, or as a daemon or service.

Sample name Subjects treated

SampleApp Applications, configuration files

SampleServer Applications, servers, configuration files.

C++ Portable ComponentsGetting Started With The Samples 28/37

2.3.1 SampleApp Sample

The Application class of the Util package is a runnable application ready forconfiguration files and command line options. The SampleApp applicationis derived from the Application class to personalize the definition ofcommand line options (/help, /define, /config-file) and their treatment.Subclasses must override the following methods: initialize(), uninitialize(),reinitialize(), defineOptions(), handleOptions() and main().

Example Name: SampleApp

Goals: Demonstrates some of the features of theUtil::Application class, such as configuration filehandling and command line arguments processing.

Description: The SampleApp is created and initialized.General:SampleApp has two important override methods:DefineOption and HandleOption. In theDefineOption method, the options help, define andconfiguration file are defined while in theHandleOption method, the treatment for each of theoptions is declared.The methods:For instance, the help option (when set) will rise acall to the displayHelp() method, which in this casedisplays the functionalities of the application. TheDefineProperty() method will add properties to theapplication environment, like global variables. Thiscan also be done when adding variables to theconfiguration file. Configuration files are parsed andvariables and their values are stored in theapplication memory for future usage by the user.The main() method of the class is called wheneverything has been initialized and when theapplication is ready to do its work or to quit. Hereyou can put the logic that will make the application“permanent”.

Used Util Classes: Application, HelpFormatter, Option, OptionSet,AbstractConfiguration, AutoPtr.

Particularities:

C++ Portable ComponentsGetting Started With The Samples 29/37

2.3.2 SampleServer Sample

The SampleServer sample is an interesting example of server applicationsand task scheduling.

Example Name: SampleServer

Goals: Demonstrate how to build and use a serverapplication based on the ServerApplication class.

Description: Very similar to the application example, theSampleServer derives from the ServerApplicationclass. The server application class allows theapplication to run as a service or as daemon. Itoverrides the same option, define and handlingmethods as the SampleApp sample, but has thedifference that we find the command“waitForTerminationRequest()” in the mainmethod. This method call will standby the mainthread until termination request, allowing the otherthreads of the server to execute. It could host somelisteners like web servers for example.In this example, a TaskScheduler object is createdand a SampleTask is added to its list. These twoclasses come from the Foundation package. TheSample task is executed and logs messages each tenseconds on the screen. When the terminationrequest occurs, the TaskManager object will stop allof its tasks in a thread-safe way.

Used Util Classes: Application, ServerApplication, Option, OptionSet,HelpFormatter.From Foundation: Task, TaskManager andDateTimerFormatter.

C++ Portable ComponentsGetting Started With The Samples 30/37

2.4 Net Samples

The Net package is composed of a wide range of classes related to networkprogramming. TCP/IP, sockets, HTTP, FTP, SMTP, POP and Mime areonly some of the most important concepts implemented in this library. Anincreasingly important tool is the web service application. Such afunctionality is brought by the library with SOAP-related classes.

Sample name Subjects treated

Dict Socket streams.

Download URIStreamOpener and stream factories.

EchoServer Reactor/Acceptor patterns.

HTTPGet HTTP clients, requests, responses.

HTTPTimeServer HTTP servers, request handling, webpages.

TimeServer TCPServer, port listeners.

Mail SMTPClientSession – sending emails.

C++ Portable ComponentsGetting Started With The Samples 31/37

2.4.1 Dict Sample

The sample searches the definition of a word on the dict.org website. Thiswebsite has a tcp access with the port 2628 that is used by the SocketStreamclass as a bidirectional stream (send commands and receive answers). Theexample shows how a complex task can be reduced to only a few lines ofcode.

Example Name: Dict

Goals: Showing how to use the SocketStream class to makea request on the web.

Description: The example takes a word as argument. Its definitionwill then be searched on the web at the dict.org:2628address. The StreamSocket class provides aninterface to a TCP stream socket, while theSocketStream class is a bidirectional stream forreading and writing to a socket. Now that the streamsocket is created between the machine and thedict.org machine, we send commands to the streamand then flush the stream to make sure that thereceiver receives the command. If everything wentwell, the dict.org website replied to our request andput in the socket stream the answer, the definition ofthe given word.

Used Net Classes: SocketAddress, StreamSocket, SocketStream,StreamCopier (Foundation).

Particularities: An Internet connection must be established to runthis example.

C++ Portable ComponentsGetting Started With The Samples 32/37

2.4.2 Download Sample

The URIStreamOpener class allows to download files from a URI.

Example Name: Download

Goals: Demonstrate the usage of the URIStreamOpenerclass to download files from FTP or HTTP sources.

Description: The example starts by registering the two streamfactories, FTP and HTTP. The given URI for the fileto download can be of both types. AURIStreamOpener object is created and is set toopen the link, downloading the file and storing itinto a stream for output.

Used Net Classes: URIStreamOpener, HTTPStreamFactory,FTPStreamFactory, StreamCopier, Path.

Particularities:

C++ Portable ComponentsGetting Started With The Samples 33/37

2.4.3 EchoServer Sample

The EchoServer creates a server which handles socket events. When acharacter is written in the socket, e.g. a telnet user connected to the server,the socket event handler catches the event and writes the same character tothe socket. The user then sees its characters written two times.

Example Name: EchoServer

Goals: To show how to use the SocketReactor andSocketAcceptor classes to listen to socket events.

Description: A Server class is created (see Util section). ASocketReactor is declared and will send events toobservers when socket events occur. TheSocketAcceptor links the reactor to theEchoServiceHandler, the handler class for socketevents. This class registers itself to the socket eventsand when an event occurs, it writes the received dataagain into the socket, making it appear two times forthe user.

Used Net Classes: SocketReactor, SocketAcceptor, ServerSocket,StreamSocket, SocketNotification,From Util:ServerApplication, Application, Option, OptionSet,HelpFormatterFrom Foundation:Observer, Thread

Particularities: To test the EchoServer you can use any telnet client(telnet localhost 9977).

C++ Portable ComponentsGetting Started With The Samples 34/37

2.4.4 HTTPGet Sample

This example makes usage of HTTPClientSession, HTTPRequest andHTTPResponse classes of the Net package. It literally builds up an HTTPclient. In this sample, the goal of this client is to get the source of a web page,given by the URI.

Example Name: HTTPGet

Goals: Demonstrate how to build an HTTPClient.

Description: After building the URI from the URI string given asargument , the example crea tes anHTTPClientSession with the host and port values.The HTTPRequest “HTTP_Get” is created and sentby the session object. The session object will thenstore the HTTPResponse object, if any, and its datawill be displayed.

Used Net Classes: HTTPClientSession, HTTPResponse, HTTPRequest.From Foundation: URI, Path, StreamCopier

Particularities: An Internet connection must be established to runthis example.

C++ Portable ComponentsGetting Started With The Samples 35/37

2.4.5 HTTPTimeServer Sample

An Internet server is created, hosting a time server application. Once started,the address localhost:9980 will lead to a web page displaying the currenttime, updated each second.

Example Name: HTTPTimeServer

Goals: Showing how to create a web server using theHTTPServer class.

Description: Everything starts with a ServerApplication (pleaserefer to the Util section for more details). Its mainmethod creates and starts an HTTPServer object. Ittakes a RequestHandlerFactory as argument, whichcreates a new RequestHandler object for eachrequest received. In this case, because the HTMLcode of the RequestHandler asks for a refresh eachsecond, a new request will occur each second if abrowser is opened on that page. The displayinformation and handling is done in theRequestHandler class, in the handleRequest method.Here we prepare the date and time to show and setthe viewing characteristics of the web page throughHTML code.

Used Net Classes: ServerSocket, HTTPRequestHandler,HTTPRequestHandlerFactory, HTTPServer,HTTPServerRequest, HTTPServerResponse,HTTPServerParams.From Foundation: Timestamp, DateTimeFormatter,DateTimeFormat.From Util: ServerApplication, Application, Option,OptionSet, HelpFormatter.

Particularities:

C++ Portable ComponentsGetting Started With The Samples 36/37

2.4.6 Mail Sample

The Net package of the C++ Portable Components includes an emailpackage which sends and receives emails with (or without) attachments. It isready for new portable mail applications.

Example Name: Mail

Goals: Demonstrate how to send emails.

Description: The sample start by asking the mailserver, the senderand receiver details. Then, it creates a MailMessageobject to which it adds the sender details and thecontent of the email. An SMTPClientSession objectis created with the mailserver details, logs it andsends the email. It also attaches an image to the mail.

Used Net Classes: SMTPClientSession, MailMessage, MailRecipient,StringPartSource.

Particularities:

C++ Portable ComponentsGetting Started With The Samples 37/37

2.4.7 TimeServer Sample

The last example showed a server application hosting a HTTP web serverwith a web application displaying the current time. The current example isquite similar, but hosts a TCP server instead. The opening of a connection tothis TCP server will return the current time.

Example Name: TimeServer

Goals: Demonstrate how to use the TCPServer application.

Description: The example works the same way as theHTTPTimeServer sample. Instead of having anH T T P R e q u e s t H a n d l e r , t h e r e i s aTCPServerConnection class, which have a run()method to process the reception of socket event. TheT C P S e r v e r c l a s s a l s o u s e aTCPServerConnectionFactory which creates aTCPServerConnection (handling) object for eachrequest. The biggest difference is that we use directlysocket streams to communicate between themachines.

Used Net Classes: ServerSocket, TCPServer, TCPServerConnection,TCPServerConnectionFactory, TCPServerParams,StreamSocket.From Foundation: Timestamp, DateTimeFormatter,DateTimeFormat.From Util: ServerApplication, Application, Option,OptionSet, HelpFormatter.

Particularities: To test the TimeServer you can use any telnet client(telnet localhost 9911).