initial import

This commit is contained in:
Guenter Obiltschnig 2006-07-11 16:33:40 +00:00
commit f476bd6b32
1463 changed files with 242402 additions and 0 deletions

370
CHANGELOG Normal file
View File

@ -0,0 +1,370 @@
This is the changelog file for the C++ Portable Components.
Release 1.1.2 (2006-07-07)
==========================
- Changed license to Boost license
Release 1.1.1 (2006-04-03)
==========================
- NetSSL_OpenSSL now supports separate certificate verification
settings for client and server.
- fixed SF #1460309 (enumerating network interfaces failed on 64bit Linux)
- TCPServer no longer crashes if accept() fails
Release 1.1.0 (2006-03-23)
==========================
- events no longer require awkward += new syntax
- source code and documentation cleanups
- basic support for new compilers and platforms
Release 1.1b2 (2006-03-04)
==========================
- made NetSSL threadsafe (added locking callbacks for OpenSSL)
- improved OpenSSL initialization (random generator seeding)
- various changes to improve compatibility with various platforms
Release 1.1b1 (2006-03-03)
==========================
- New Events package in Foundation. The package supports C#-style event handling
- New Cache package in Foundation: a templates-based caching framework
- added Any class to Foundation
- added DBLite library
- fixed a memory leak with layered configurations in the application
- made POCO_DLL the default (unless POCO_STATIC is #defined)
It is no longer necessary to specify POCO_DLL in projects that use Poco
(SourceForge Patch #1408231 and Feature Request #1407575).
- added Buffer template class to Foundation
- added the UnicodeConverter utility class. This is mainly used for Windows Unicode support and probably of little use for anything else.
- added Path::resolve()
- added Windows Unicode support. This calls the Unicode variant of the Windows API functions.
For this to work, all strings must be UTF-8 encoded and POCO_WIN32_UTF8 must be defined in all compilation units.
- added StreamCopier::copyToString()
- added URIStreamOpener::unregisterStreamFactory() and new variants of URIStreamOpener::open() that also work with filesystem paths.
This fixes SourceForge Bug #1409064 and Feature Request #1409062.
- added NodeIterator::currentNodeNP() to XML library
- added some sanity checks to UTF8Encoding::convert()
- added NetSSL - SSL support for Net library, based on OpenSSL
- console output of processes launched with Process::launch() is now visible
Release 1.0.0 (2006-01-19)
==========================
- removed unnecessary console output from ProcessTest
- documentation fixes
Release 1.0b2 (2006-01-16)
==========================
- added ProcessHandle class
- Process::launch() now returns a ProcessHandle instead of a process ID.
This fixes a potential problem on Windows with Process::wait() when
the process terminates before wait() is called.
- added SplitterChannel::close()
- added Logger::destroy()
- added POP3ClientSession::deleteMessage()
- added test for Process::launch()
- documentation fixes
Release 1.0b1 (2006-01-09)
==========================
- improved recognition of Windows paths in Path::parseGuess()
- added setCurrentLineNumber()/getCurrentLineNumber() to CountingStreamBuf
- improvememts to StreamTokenizer and Token; fixed documentation
- added a workaround for some strange istream behaviour with VS 2005 and FTPClientSessionTest
- improved exception/error reporting in cppunit
- added POP3ClientSession
- added Process::launch() and Process::wait()
- added Mail sample
- added MailStream and SMTPClientSession classes
- renamed some methods in DialogSocket to make them more general
- NullPartHandler has moved out of HTMLForm.cpp into a separate file
- Base64Encoder now always writes \r\n line ends
- MessageHeader::quote has an optional addition arg controlling the treatment of whitespace
- bugfix: MultipartReader had a problem with empty lines (\r\n sequences) in a part
- added MailMessage and MailRecipient classes
- added text encoding support for Windows-1252 codepage
Release 1.0a1 (2006-01-03) [internal]
=====================================
- mediaType is used consistently to refer to a MIME media type (some occurences of contentType and mimeType have been replaced)
- moved MediaType::quote() to MessageHeader and made it public
- added MultipartWriter::stream()
- Renamed AttachmentSource to PartSource and AttachmentHandler to PartHandler
- SIGPIPE is always blocked in main thread on Unix systems
- added EchoServer sample
- fixed a bug in SocketImpl::setBlocking() - did exactly the opposite (value to ioctl was wrong)
- fixed a memory leak in NotificationQueue sample
- added comparison operators to Socket so that Sockets can be used as keys in maps
- added Socket::setBlocking()
- added StreamSocket::connectNB() (non-blocking connect)
- added Observer::accepts()
- added SocketReactor, SocketConnector and SocketAcceptor classes to support event-based socket programming
- NamespacePrefixesStrategy now uses expat's XML_SetReturnNSTriplet().
The previously used separate namespace handling code has been removed.
This improves performance if NamespacePrefixesStrategy is used (both the n
amespaces and namespace-prefixes SAX2 features are used)
- upgraded expat to 2.0 pre-release (2005-12-27) snapshot
- added TeeInputStream and TeeOutputStream classes
- added download sample for URIStreamOpener
- renamed registerOpener() to registerFactory() in HTTPStreamFactory and FTPStreamFactory
- added LineEndingConverter streams
- added FTPClientSession
- code and documentation clean-up
- added DialogSocket class
- reorganized HTTP test suites
- added FTPClientSession and FTPStreamFactory
- added DialogSocket class
Release 0.96.1 (2005-12-28)
===========================
- fixed a memory leak caused by a bug in Microsoft's stream implementation (see the comment in Foundation/StreamUtil.h for an explanation)
- added samples for Net library
- added uptime() and startTime() to Util::Application
- added DateTimeFormatter::format() for Timespan
- added ErrorHandler class and better exception handling for threads
- added poco_debugger() and poco_debugger_msg() macros
- added project and solution files for Visual Studio 2005 (due to some bugs/leaks in Microsofts standard library - see
http://lab.msdn.microsoft.com/productfeedback/viewfeedback.aspx?feedbackid=e08bd793-3fef-40ff-adda-ed313e0eafcc
we do not recommend using this for production purposes)
- fixed two problems with out-of-range string iterator in Path (the testsuite triggered an assertion in VC++ 8.0)
- fixed mac line endings in a few files
- added a workaround to the class loader that fixes strange behavior with VC++ 8.0. There seems to be a problem with typeid() not returning a valid typeinfo under certain circumstances.
- added buffer allocator argument to buffered stream buffer templates
- added buffer pools to HTTP to reduce memory fragmentation and to improve performance
- added Net to Windows build.cmd script
- added swap() to various classes that already support assignment
- added a null pointer check in DOMWriter::writeNode()
- fixed documentation in BinaryWriter.h and BinaryReader.h
- added explicit support for network byte order to BinaryReader and BinaryWriter
- added basic support for FreeBSD (needs more testing)
- BinaryReader: renamed readRawData() to readRaw() to be consistent with BinaryWriter::writeRaw()
- added support for uppercase output to HexBinaryEncoder.
- added MediaType class
- added QuotedPrintableEncoder and QuotedPrintableDecoder classes
- renamed ObjectFactory to Instantiator. This should prevent the confusion caused by DynamicFactory and ObjectFactory. Sorry for the inconvenience if you are already using this.
- AttachmentSource::filename() now returns const string&
- added StringAttachmentSource
- replaced old-style C casts with C++ casts in NetworkInterface.cpp
- MutexImpl (WIN32): replaced InitializeCriticalSection with InitializeCriticalSectionAndSpinCount, which should increase performance on multiprocessor or multicore systems when many locks are used.
- fixed a problem with STLport 5.0 when compiling StreamTokenizer
- HTTPStreamOpener now also works with no-path URIs (like http://www.appinf.com)
- fixed wrong delete usage (plain delete instead of delete [] was used in a few cases)
- fixed a handle leak in WinTestRunner
Release 0.95.4 (2005-11-07)
===========================
- fixed #1348006 and #1348005
Release 0.95.3 (2005-10-28) [internal]
======================================
- updated build scripts (patch #1339015)
- added support for AMD64 platforms (patch #1339015)
- MultipartWriter creates its own boundary if an empty string is passed in as boundary
- made MultipartWriter::createBoundary() public
- fixed wrong documentation for DateTimeFormat::HTTP_FORMAT
- added support for HTTP Basic authentication
- added support for HTTP Cookies
- added support for HTML forms
Release 0.95.2 (2005-10-22) [internal]
======================================
- fixed a potential problems with streams when close in destructor fails (added try..catch block around close in destructors)
- added HTTPServer & friends
- added hasIdleThreads() method to NotificationQueue
- added TCPServer and friend
- added support for HTTP proxies to HTTPClientSession and HTTPStreamOpener
- fixed documentation bugs (Mutex.h, ClassLoader.h)
Relesae 0.95.1 (2005-10-15) [internal]
======================================
- Tasks can now throw custom notifications (contributed by Alex Fabijanic)
- renamed URIFileStreamFactory to FileStreamFactory
- added a few methods to URI (setPathEtc(), getPathEtc(), getPathAndQuery())
- added new exception classes
- fixed some documentation
- added basic checks when reading a MessageHeader from a stream
- added HTTP classes (testsuite still incomplete)
- added MessageHeader, NameValueCollection, MultipartReader and MultipartWriter classes
- added Timespan::useconds()
- added ClassLoader::isLibraryLoaded()
- Socket classes use Timespan::useconds() to fill struct timeval
- added DatagramSocket, MulticastSocket and NetworkInterface classes
- added socket classes and related basic stuff
- added additonal constructor/assign to Timespan- added BasicBufferedBidirectionalStreamBuf
- fixed a potential MT issue in Base64Decoder
- code beautifying in [Un]BufferedStreamBuf
- more improvements to ClassLoader
- code cleanup and naming convention fixes (changed all *Imp classes to *Impl for consistency)
Release 0.94.1 (2005-09-30) [internal]
======================================
- added MetaSingleton (based on a contribution by Alex Fabijanic)
- added ClassLoader::create()
- added ClassLoader::instance()
- code clean-ups in FileChannel and related classes
- added SimpleFileChannel
- RotateAtTimeStrategy:
::getNextRollover() rewritten (buggy)
- DateTime
microseconds assert corrected
asserts in computeGregorian() (except for year - see comment in computeGregorian())
milliseconds calculation modified in computeGregorian()
microseconds assigned in computeGregorian()
normalize() and checkLimit() private functions to correct cases of overflow for milli/microseconds
- LocalDateTime: added timestamp() method
- FileChannel:
added "times" property (used to determine whether to use UTC or local time with RotateAtTimeStrategy)
::setProperty() modified (whenever "times" property is set, methods setRotation and setArchive are
reinvoked to reflect the change)
- FileChannel: added support for archived file compression and archived file purging
- FileChannel tests modified
- FileChannel: put LogFile, RotateStrategy and ArchiveStrategy into their own files
- Message: added thread id field
- PatternFormatter: added %I specifier for thread id
- ThreadPool: PooledThread can be assigned a name
- TaskManager: task name is reflected in thread name
- fixed LocalDateTime::operator - (const Timespan&) [#0000004]
- upon startup all loggers' channels are set to a console channel
- improved search for application configuration files (see loadConfiguration()).
- added Glob class (fixes #1249700)
- upgraded to zlib 1.2.3 (fixes #1261712)
- added Logger::dump()
- fixed a wrong condition in Logger::log(const Message&)
- Path::find() now also works with relative paths in addition to plain file names
- added Path(const Path&, const Path&) constructor
- added SharedPtr template
- added Path::tryParse()
- SAXParser::parse()/EntityResolverImpl now works for both URIs and local filesystem paths (fixes #1254812)
Release 0.93.1 (2005-08-01)
===========================
This release contains various new features, improvements and bugfixes:
- bugfix: UUIDGenerator throws an exception if no connected ethernet adapter can
be found (and thus no MAC address can be obtained)
- added UUIDGenerator::createOne() method
- added error handling to UUID sample application
- added relational (==, !=, <, <=, >, >=) and arithmetic operators (+, -, +=, -=) to DateTime
- added LocalDateTime class
- added support for LocalDateTime to DateTimeParser and DateTimeFormatter
- added enqueueUrgentNotification() to NotificationQueue
- added support for timezone specifiers (%z, %Z) to PatternFormatter
- added [] operator and count() to StringTokenizer
- added elapsed() and isElapsed() to Timestamp
- added tzd() to Timezone
- added WinRegistryKey and WinService classes (Windows only)
- added index operator and count() to StringTokenizer
- added day/time-based log rotation (thanks to Alex Fabijanic), minor improvements to DateTimeParser
- support for Mac OS X 10.4/gcc 4.0.0
- added NamedMutex and NamedEvent
- added Process::kill()
- added NoPermissionException
- added Task and TaskManager classes
- added ServerApplication class
- bugfix: EventLogChannel - _logFile was not properly initialized in one constructor
- bugfix: File::createDirectories did not work for hierarchies deeper than three
- added Util::FilesystemConfiguration
- documented logging policy: log() must open channel if it hasn't been opened yet
- FileChannel::log() opens channel if necessary
- the application reference passed to initialize() and reinitialize() is no longer const
- improved application logging initialization
- fixed a problem with configuration view and property placeholders
- fixed Util build configuration for Visual Studio
- improved application samples
- fixed documentation for Semaphore class
Release 0.92.1 (2005-05-09)
===========================
This release introduces the Util library that provides support for
configuration file parsing (different file formats), command line
argument processing, logging configuration and a framework for
command line/server applications.
There have also been various changes to the Foundation library:
- a new RefCountedObject class that acts as a base class for
various classes that use reference counting
- some missing members have been added to the AutoPtr template
- various improvements and bugfixes to the Logging framework, as well as
new LoggingFactory and LoggingRegistry classses, and a NullChannel class
- the SignalHandler class (Unix platforms only)
- ObjectFactory and DynamicFactory template classes
- the Path::find method for searching a file in a list of directories
- various new Exception classes
Release 0.91.4 (2005-04-11)
===========================
This is mainly a maintenance release that adds support for QNX Neutrino
and OpenVMS. There are also minor bugfixes and improvements.
The Unix build system has been modified to work on QNX Neutrino.
The OpenVMS build system has been fixed and works now.
Some missing #include's have been added for QNX Neutrino.
Foundation/String.h: icompare now supports comparison with const char*;
the classic C version of isspace() has been used in a few places instead of the
C++ <locale> version, this has been fixed.
Foundation/Exception.h: IllegalStateException added.
Release 0.91.3 (2005-03-19)
===========================
This is a maintenance release that adds support for Solaris/Sun Forte C++.
No new features have been added.
An implementation of FPEnvironment for Solaris has been included.
All stream classes have been modified to work around an initialization
problem that surfaced with Sun's C++ compiler when using STLport.
Source-code compatibility with the previous release is not affected. Various
minor changes, mostly adding missing #include's for Solaris.
Release 0.91.2 (2005-02-27)
===========================
Minor improvements to the Unix build system. No actual changes in the
libraries.
Release 0.91.1 (2005-02-21)
===========================
This is the first public release of the C++ Portable Components.
The release does not contain all features planned for the later 1.0 release
(the NET library is missing, for example), but is already quite usable.
Please refer to the README file for more information and instructions for
building the libraries.
--
$Id: //poco/1.1.0/dist/CHANGELOG#3 $

30
CppUnit/CppUnit_vs71.sln Normal file
View File

@ -0,0 +1,30 @@
Microsoft Visual Studio Solution File, Format Version 8.00
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "CppUnit", "CppUnit_VS71.vcproj", "{138BB448-808A-4FE5-A66D-78D1F8770F59}"
ProjectSection(ProjectDependencies) = postProject
EndProjectSection
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "WinTestRunner", "WinTestRunner\WinTestRunner_VS71.vcproj", "{BA620CC4-0E7D-4B9D-88E2-6DBE5C51FCBD}"
ProjectSection(ProjectDependencies) = postProject
{138BB448-808A-4FE5-A66D-78D1F8770F59} = {138BB448-808A-4FE5-A66D-78D1F8770F59}
EndProjectSection
EndProject
Global
GlobalSection(SolutionConfiguration) = preSolution
debug_shared = debug_shared
release_shared = release_shared
EndGlobalSection
GlobalSection(ProjectConfiguration) = postSolution
{138BB448-808A-4FE5-A66D-78D1F8770F59}.debug_shared.ActiveCfg = debug_shared|Win32
{138BB448-808A-4FE5-A66D-78D1F8770F59}.debug_shared.Build.0 = debug_shared|Win32
{138BB448-808A-4FE5-A66D-78D1F8770F59}.release_shared.ActiveCfg = release_shared|Win32
{138BB448-808A-4FE5-A66D-78D1F8770F59}.release_shared.Build.0 = release_shared|Win32
{BA620CC4-0E7D-4B9D-88E2-6DBE5C51FCBD}.debug_shared.ActiveCfg = debug_shared|Win32
{BA620CC4-0E7D-4B9D-88E2-6DBE5C51FCBD}.debug_shared.Build.0 = debug_shared|Win32
{BA620CC4-0E7D-4B9D-88E2-6DBE5C51FCBD}.release_shared.ActiveCfg = release_shared|Win32
{BA620CC4-0E7D-4B9D-88E2-6DBE5C51FCBD}.release_shared.Build.0 = release_shared|Win32
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
EndGlobalSection
GlobalSection(ExtensibilityAddIns) = postSolution
EndGlobalSection
EndGlobal

259
CppUnit/CppUnit_vs71.vcproj Normal file
View File

@ -0,0 +1,259 @@
<?xml version="1.0" encoding="Windows-1252"?>
<VisualStudioProject
ProjectType="Visual C++"
Version="7.10"
Name="CppUnit"
ProjectGUID="{138BB448-808A-4FE5-A66D-78D1F8770F59}"
SccProjectName="CppUnit"
SccLocalPath="."
Keyword="MFCProj">
<Platforms>
<Platform
Name="Win32"/>
</Platforms>
<Configurations>
<Configuration
Name="debug_shared|Win32"
OutputDirectory=".\obj\debug_shared"
IntermediateDirectory=".\obj\debug_shared"
ConfigurationType="2"
UseOfMFC="2"
ATLMinimizesCRunTimeLibraryUsage="FALSE"
CharacterSet="2">
<Tool
Name="VCCLCompilerTool"
Optimization="0"
InlineFunctionExpansion="0"
EnableIntrinsicFunctions="FALSE"
AdditionalIncludeDirectories="include"
PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;POCO_DLL;CppUnit_EXPORTS"
StringPooling="TRUE"
BasicRuntimeChecks="3"
RuntimeLibrary="3"
BufferSecurityCheck="TRUE"
TreatWChar_tAsBuiltInType="TRUE"
ForceConformanceInForLoopScope="TRUE"
RuntimeTypeInfo="TRUE"
PrecompiledHeaderFile=""
AssemblerListingLocation=""
ObjectFile="$(IntDir)/"
ProgramDataBaseFileName="$(IntDir)/vc70.pdb"
WarningLevel="3"
SuppressStartupBanner="TRUE"
Detect64BitPortabilityProblems="TRUE"
DebugInformationFormat="4"
CompileAs="0"
ShowIncludes="FALSE"/>
<Tool
Name="VCCustomBuildTool"/>
<Tool
Name="VCLinkerTool"
ShowProgress="0"
OutputFile="..\bin\CppUnitd.dll"
LinkIncremental="2"
SuppressStartupBanner="TRUE"
AdditionalLibraryDirectories=""
GenerateDebugInformation="TRUE"
ProgramDatabaseFile="..\bin\CppUnitd.pdb"
ImportLibrary="..\lib\CppUnitd.lib"
TargetMachine="1"/>
<Tool
Name="VCMIDLTool"
PreprocessorDefinitions="_DEBUG"
MkTypLibCompatible="TRUE"
SuppressStartupBanner="TRUE"
TargetEnvironment="1"
TypeLibraryName=".\lib/CppUnit.tlb"
HeaderFileName=""/>
<Tool
Name="VCPostBuildEventTool"/>
<Tool
Name="VCPreBuildEventTool"/>
<Tool
Name="VCPreLinkEventTool"/>
<Tool
Name="VCResourceCompilerTool"
PreprocessorDefinitions="_DEBUG"
Culture="3079"/>
<Tool
Name="VCWebServiceProxyGeneratorTool"/>
<Tool
Name="VCXMLDataGeneratorTool"/>
<Tool
Name="VCWebDeploymentTool"/>
<Tool
Name="VCManagedWrapperGeneratorTool"/>
<Tool
Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
</Configuration>
<Configuration
Name="release_shared|Win32"
OutputDirectory=".\obj\release_shared"
IntermediateDirectory=".\obj\release_shared"
ConfigurationType="2"
UseOfMFC="0"
ATLMinimizesCRunTimeLibraryUsage="FALSE"
CharacterSet="2">
<Tool
Name="VCCLCompilerTool"
Optimization="4"
InlineFunctionExpansion="1"
EnableIntrinsicFunctions="TRUE"
FavorSizeOrSpeed="1"
OmitFramePointers="TRUE"
AdditionalIncludeDirectories="include"
PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_AFXDLL;POCO_DLL;CppUnit_EXPORTS"
StringPooling="TRUE"
RuntimeLibrary="2"
BufferSecurityCheck="FALSE"
TreatWChar_tAsBuiltInType="TRUE"
ForceConformanceInForLoopScope="TRUE"
RuntimeTypeInfo="TRUE"
PrecompiledHeaderFile=""
AssemblerListingLocation=""
ObjectFile="$(IntDir)/"
ProgramDataBaseFileName="$(IntDir)/vc70.pdb"
WarningLevel="3"
SuppressStartupBanner="TRUE"
Detect64BitPortabilityProblems="TRUE"
CompileAs="0"/>
<Tool
Name="VCCustomBuildTool"/>
<Tool
Name="VCLinkerTool"
OutputFile="..\bin\CppUnit.dll"
LinkIncremental="1"
SuppressStartupBanner="TRUE"
AdditionalLibraryDirectories=""
ProgramDatabaseFile=""
ImportLibrary="..\lib\CppUnit.lib"
TargetMachine="1"/>
<Tool
Name="VCMIDLTool"
PreprocessorDefinitions="NDEBUG"
MkTypLibCompatible="TRUE"
SuppressStartupBanner="TRUE"
TargetEnvironment="1"
TypeLibraryName=".\lib/CppUnit.tlb"
HeaderFileName=""/>
<Tool
Name="VCPostBuildEventTool"/>
<Tool
Name="VCPreBuildEventTool"/>
<Tool
Name="VCPreLinkEventTool"/>
<Tool
Name="VCResourceCompilerTool"
PreprocessorDefinitions="NDEBUG"
Culture="3079"/>
<Tool
Name="VCWebServiceProxyGeneratorTool"/>
<Tool
Name="VCXMLDataGeneratorTool"/>
<Tool
Name="VCWebDeploymentTool"/>
<Tool
Name="VCManagedWrapperGeneratorTool"/>
<Tool
Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
</Configuration>
</Configurations>
<References>
</References>
<Files>
<Filter
Name="Source Files"
Filter="cpp;c;cxx;rc;def;r;odl;idl;hpj;bat">
<File
RelativePath=".\src\CppUnitException.cpp">
<FileConfiguration
Name="debug_shared|Win32">
<Tool
Name="VCCLCompilerTool"
ObjectFile="$(IntDir)/$(InputName)1.obj"/>
</FileConfiguration>
<FileConfiguration
Name="release_shared|Win32">
<Tool
Name="VCCLCompilerTool"
ObjectFile="$(IntDir)/$(InputName)1.obj"/>
</FileConfiguration>
</File>
<File
RelativePath="src\TestCase.cpp">
</File>
<File
RelativePath="src\TestDecorator.cpp">
</File>
<File
RelativePath="src\TestFailure.cpp">
</File>
<File
RelativePath="src\TestResult.cpp">
</File>
<File
RelativePath=".\src\TestRunner.cpp">
</File>
<File
RelativePath="src\TestSuite.cpp">
</File>
<File
RelativePath="src\TextTestResult.cpp">
</File>
</Filter>
<Filter
Name="Include Files"
Filter="*.h">
<File
RelativePath=".\include\CppUnit\CppUnit.h">
</File>
<File
RelativePath=".\include\CppUnit\CppUnitException.h">
</File>
<File
RelativePath=".\include\CppUnit\estring.h">
</File>
<File
RelativePath=".\include\CppUnit\Guards.h">
</File>
<File
RelativePath=".\include\CppUnit\Orthodox.h">
</File>
<File
RelativePath=".\include\CppUnit\RepeatedTest.h">
</File>
<File
RelativePath=".\include\CppUnit\Test.h">
</File>
<File
RelativePath=".\include\CppUnit\TestCaller.h">
</File>
<File
RelativePath=".\include\CppUnit\TestCase.h">
</File>
<File
RelativePath=".\include\CppUnit\TestDecorator.h">
</File>
<File
RelativePath=".\include\CppUnit\TestFailure.h">
</File>
<File
RelativePath=".\include\CppUnit\TestResult.h">
</File>
<File
RelativePath=".\include\CppUnit\TestRunner.h">
</File>
<File
RelativePath=".\include\CppUnit\TestSetup.h">
</File>
<File
RelativePath=".\include\CppUnit\TestSuite.h">
</File>
<File
RelativePath=".\include\CppUnit\TextTestResult.h">
</File>
</Filter>
</Files>
<Globals>
</Globals>
</VisualStudioProject>

28
CppUnit/CppUnit_vs80.sln Normal file
View File

@ -0,0 +1,28 @@
Microsoft Visual Studio Solution File, Format Version 9.00
# Visual Studio 2005
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "CppUnit", "CppUnit_vs80.vcproj", "{138BB448-808A-4FE5-A66D-78D1F8770F59}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "WinTestRunner", "WinTestRunner\WinTestRunner_vs80.vcproj", "{BA620CC4-0E7D-4B9D-88E2-6DBE5C51FCBD}"
ProjectSection(ProjectDependencies) = postProject
{138BB448-808A-4FE5-A66D-78D1F8770F59} = {138BB448-808A-4FE5-A66D-78D1F8770F59}
EndProjectSection
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
debug_shared|Win32 = debug_shared|Win32
release_shared|Win32 = release_shared|Win32
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{138BB448-808A-4FE5-A66D-78D1F8770F59}.debug_shared|Win32.ActiveCfg = debug_shared|Win32
{138BB448-808A-4FE5-A66D-78D1F8770F59}.debug_shared|Win32.Build.0 = debug_shared|Win32
{138BB448-808A-4FE5-A66D-78D1F8770F59}.release_shared|Win32.ActiveCfg = release_shared|Win32
{138BB448-808A-4FE5-A66D-78D1F8770F59}.release_shared|Win32.Build.0 = release_shared|Win32
{BA620CC4-0E7D-4B9D-88E2-6DBE5C51FCBD}.debug_shared|Win32.ActiveCfg = debug_shared|Win32
{BA620CC4-0E7D-4B9D-88E2-6DBE5C51FCBD}.debug_shared|Win32.Build.0 = debug_shared|Win32
{BA620CC4-0E7D-4B9D-88E2-6DBE5C51FCBD}.release_shared|Win32.ActiveCfg = release_shared|Win32
{BA620CC4-0E7D-4B9D-88E2-6DBE5C51FCBD}.release_shared|Win32.Build.0 = release_shared|Win32
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal

351
CppUnit/CppUnit_vs80.vcproj Normal file
View File

@ -0,0 +1,351 @@
<?xml version="1.0" encoding="Windows-1252"?>
<VisualStudioProject
ProjectType="Visual C++"
Version="8.00"
Name="CppUnit"
ProjectGUID="{138BB448-808A-4FE5-A66D-78D1F8770F59}"
Keyword="MFCProj"
>
<Platforms>
<Platform
Name="Win32"
/>
</Platforms>
<ToolFiles>
</ToolFiles>
<Configurations>
<Configuration
Name="debug_shared|Win32"
OutputDirectory=".\obj\debug_shared"
IntermediateDirectory=".\obj\debug_shared"
ConfigurationType="2"
InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
UseOfMFC="2"
ATLMinimizesCRunTimeLibraryUsage="false"
CharacterSet="2"
>
<Tool
Name="VCPreBuildEventTool"
/>
<Tool
Name="VCCustomBuildTool"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCWebServiceProxyGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
PreprocessorDefinitions="_DEBUG"
MkTypLibCompatible="true"
SuppressStartupBanner="true"
TargetEnvironment="1"
TypeLibraryName=".\lib/CppUnit.tlb"
HeaderFileName=""
/>
<Tool
Name="VCCLCompilerTool"
Optimization="0"
InlineFunctionExpansion="0"
EnableIntrinsicFunctions="false"
AdditionalIncludeDirectories="include"
PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;CppUnit_EXPORTS;_CRT_SECURE_NO_DEPRECATE"
StringPooling="true"
BasicRuntimeChecks="3"
RuntimeLibrary="3"
BufferSecurityCheck="true"
TreatWChar_tAsBuiltInType="true"
ForceConformanceInForLoopScope="true"
RuntimeTypeInfo="true"
PrecompiledHeaderFile=""
AssemblerListingLocation=""
ObjectFile="$(IntDir)/"
ProgramDataBaseFileName="$(IntDir)/vc80.pdb"
WarningLevel="3"
SuppressStartupBanner="true"
Detect64BitPortabilityProblems="true"
DebugInformationFormat="4"
CompileAs="0"
ShowIncludes="false"
/>
<Tool
Name="VCManagedResourceCompilerTool"
/>
<Tool
Name="VCResourceCompilerTool"
PreprocessorDefinitions="_DEBUG"
Culture="3079"
/>
<Tool
Name="VCPreLinkEventTool"
/>
<Tool
Name="VCLinkerTool"
ShowProgress="0"
OutputFile="..\bin\CppUnitd.dll"
LinkIncremental="2"
SuppressStartupBanner="true"
AdditionalLibraryDirectories=""
GenerateDebugInformation="true"
ProgramDatabaseFile="..\bin\CppUnitd.pdb"
ImportLibrary="..\lib\CppUnitd.lib"
TargetMachine="1"
/>
<Tool
Name="VCALinkTool"
/>
<Tool
Name="VCManifestTool"
/>
<Tool
Name="VCXDCMakeTool"
/>
<Tool
Name="VCBscMakeTool"
/>
<Tool
Name="VCFxCopTool"
/>
<Tool
Name="VCAppVerifierTool"
/>
<Tool
Name="VCWebDeploymentTool"
/>
<Tool
Name="VCPostBuildEventTool"
/>
</Configuration>
<Configuration
Name="release_shared|Win32"
OutputDirectory=".\obj\release_shared"
IntermediateDirectory=".\obj\release_shared"
ConfigurationType="2"
InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
UseOfMFC="0"
ATLMinimizesCRunTimeLibraryUsage="false"
CharacterSet="2"
>
<Tool
Name="VCPreBuildEventTool"
/>
<Tool
Name="VCCustomBuildTool"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCWebServiceProxyGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
PreprocessorDefinitions="NDEBUG"
MkTypLibCompatible="true"
SuppressStartupBanner="true"
TargetEnvironment="1"
TypeLibraryName=".\lib/CppUnit.tlb"
HeaderFileName=""
/>
<Tool
Name="VCCLCompilerTool"
Optimization="4"
InlineFunctionExpansion="1"
EnableIntrinsicFunctions="true"
FavorSizeOrSpeed="1"
OmitFramePointers="true"
AdditionalIncludeDirectories="include"
PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_AFXDLL;POCO_DLL;CppUnit_EXPORTS;_CRT_SECURE_NO_DEPRECATE"
StringPooling="true"
RuntimeLibrary="2"
BufferSecurityCheck="false"
TreatWChar_tAsBuiltInType="true"
ForceConformanceInForLoopScope="true"
RuntimeTypeInfo="true"
PrecompiledHeaderFile=""
AssemblerListingLocation=""
ObjectFile="$(IntDir)/"
ProgramDataBaseFileName="$(IntDir)/vc70.pdb"
WarningLevel="3"
SuppressStartupBanner="true"
Detect64BitPortabilityProblems="true"
CompileAs="0"
/>
<Tool
Name="VCManagedResourceCompilerTool"
/>
<Tool
Name="VCResourceCompilerTool"
PreprocessorDefinitions="NDEBUG"
Culture="3079"
/>
<Tool
Name="VCPreLinkEventTool"
/>
<Tool
Name="VCLinkerTool"
OutputFile="..\bin\CppUnit.dll"
LinkIncremental="1"
SuppressStartupBanner="true"
AdditionalLibraryDirectories=""
ProgramDatabaseFile=""
ImportLibrary="..\lib\CppUnit.lib"
TargetMachine="1"
/>
<Tool
Name="VCALinkTool"
/>
<Tool
Name="VCManifestTool"
/>
<Tool
Name="VCXDCMakeTool"
/>
<Tool
Name="VCBscMakeTool"
/>
<Tool
Name="VCFxCopTool"
/>
<Tool
Name="VCAppVerifierTool"
/>
<Tool
Name="VCWebDeploymentTool"
/>
<Tool
Name="VCPostBuildEventTool"
/>
</Configuration>
</Configurations>
<References>
</References>
<Files>
<Filter
Name="Source Files"
Filter="cpp;c;cxx;rc;def;r;odl;idl;hpj;bat"
>
<File
RelativePath=".\src\CppUnitException.cpp"
>
<FileConfiguration
Name="debug_shared|Win32"
>
<Tool
Name="VCCLCompilerTool"
ObjectFile="$(IntDir)/$(InputName)1.obj"
/>
</FileConfiguration>
<FileConfiguration
Name="release_shared|Win32"
>
<Tool
Name="VCCLCompilerTool"
ObjectFile="$(IntDir)/$(InputName)1.obj"
/>
</FileConfiguration>
</File>
<File
RelativePath="src\TestCase.cpp"
>
</File>
<File
RelativePath="src\TestDecorator.cpp"
>
</File>
<File
RelativePath="src\TestFailure.cpp"
>
</File>
<File
RelativePath="src\TestResult.cpp"
>
</File>
<File
RelativePath=".\src\TestRunner.cpp"
>
</File>
<File
RelativePath="src\TestSuite.cpp"
>
</File>
<File
RelativePath="src\TextTestResult.cpp"
>
</File>
</Filter>
<Filter
Name="Include Files"
Filter="*.h"
>
<File
RelativePath=".\include\CppUnit\CppUnit.h"
>
</File>
<File
RelativePath=".\include\CppUnit\CppUnitException.h"
>
</File>
<File
RelativePath=".\include\CppUnit\estring.h"
>
</File>
<File
RelativePath=".\include\CppUnit\Guards.h"
>
</File>
<File
RelativePath=".\include\CppUnit\Orthodox.h"
>
</File>
<File
RelativePath=".\include\CppUnit\RepeatedTest.h"
>
</File>
<File
RelativePath=".\include\CppUnit\Test.h"
>
</File>
<File
RelativePath=".\include\CppUnit\TestCaller.h"
>
</File>
<File
RelativePath=".\include\CppUnit\TestCase.h"
>
</File>
<File
RelativePath=".\include\CppUnit\TestDecorator.h"
>
</File>
<File
RelativePath=".\include\CppUnit\TestFailure.h"
>
</File>
<File
RelativePath=".\include\CppUnit\TestResult.h"
>
</File>
<File
RelativePath=".\include\CppUnit\TestRunner.h"
>
</File>
<File
RelativePath=".\include\CppUnit\TestSetup.h"
>
</File>
<File
RelativePath=".\include\CppUnit\TestSuite.h"
>
</File>
<File
RelativePath=".\include\CppUnit\TextTestResult.h"
>
</File>
</Filter>
</Files>
<Globals>
</Globals>
</VisualStudioProject>

18
CppUnit/Makefile Normal file
View File

@ -0,0 +1,18 @@
#
# Makefile
#
# $Id: //poco/1.1.0/CppUnit/Makefile#1 $
#
# Makefile for Poco CppUnit
#
include $(POCO_BASE)/build/rules/global
objects = CppUnitException TestDecorator TestResult TestSuite \
TestCase TestFailure TestRunner TextTestResult
target = CppUnit
target_version = 1
target_libs =
include $(POCO_BASE)/build/rules/lib

View File

@ -0,0 +1,223 @@
<?xml version="1.0" encoding="Windows-1252"?>
<VisualStudioProject
ProjectType="Visual C++"
Version="7.10"
Name="WinTestRunner"
ProjectGUID="{BA620CC4-0E7D-4B9D-88E2-6DBE5C51FCBD}"
SccProjectName="WinTestRunner"
SccLocalPath="."
Keyword="MFCProj">
<Platforms>
<Platform
Name="Win32"/>
</Platforms>
<Configurations>
<Configuration
Name="release_shared|Win32"
OutputDirectory=".\obj\release_shared"
IntermediateDirectory=".\obj\release_shared"
ConfigurationType="2"
UseOfMFC="2"
ATLMinimizesCRunTimeLibraryUsage="FALSE"
CharacterSet="2">
<Tool
Name="VCCLCompilerTool"
Optimization="4"
InlineFunctionExpansion="1"
EnableIntrinsicFunctions="TRUE"
FavorSizeOrSpeed="1"
OmitFramePointers="TRUE"
AdditionalIncludeDirectories="include;..\include"
PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;POCO_DLL;WinTestRunner_EXPORTS;WINVER=0x0500"
RuntimeLibrary="2"
BufferSecurityCheck="FALSE"
TreatWChar_tAsBuiltInType="TRUE"
ForceConformanceInForLoopScope="TRUE"
RuntimeTypeInfo="TRUE"
PrecompiledHeaderFile=""
AssemblerListingLocation=""
ObjectFile="$(IntDir)\"
ProgramDataBaseFileName="$(IntDir)/vc70.pdb"
WarningLevel="3"
SuppressStartupBanner="TRUE"
Detect64BitPortabilityProblems="TRUE"
CompileAs="0"/>
<Tool
Name="VCCustomBuildTool"/>
<Tool
Name="VCLinkerTool"
AdditionalDependencies="cppunit.lib winmm.lib"
OutputFile="..\..\bin\WinTestRunner.dll"
LinkIncremental="1"
SuppressStartupBanner="TRUE"
AdditionalLibraryDirectories="..\..\lib"
ProgramDatabaseFile=""
SubSystem="2"
ImportLibrary="..\..\lib\WinTestRunner.lib"
TargetMachine="1"/>
<Tool
Name="VCMIDLTool"
PreprocessorDefinitions="NDEBUG"
MkTypLibCompatible="TRUE"
SuppressStartupBanner="TRUE"
TargetEnvironment="1"
TypeLibraryName=".\lib\wintestrunner.tlb"
HeaderFileName=""/>
<Tool
Name="VCPostBuildEventTool"/>
<Tool
Name="VCPreBuildEventTool"/>
<Tool
Name="VCPreLinkEventTool"/>
<Tool
Name="VCResourceCompilerTool"
PreprocessorDefinitions="NDEBUG"
Culture="3079"/>
<Tool
Name="VCWebServiceProxyGeneratorTool"/>
<Tool
Name="VCXMLDataGeneratorTool"/>
<Tool
Name="VCWebDeploymentTool"/>
<Tool
Name="VCManagedWrapperGeneratorTool"/>
<Tool
Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
</Configuration>
<Configuration
Name="debug_shared|Win32"
OutputDirectory=".\obj\debug_shared"
IntermediateDirectory=".\obj\debug_shared"
ConfigurationType="2"
UseOfMFC="2"
ATLMinimizesCRunTimeLibraryUsage="FALSE"
CharacterSet="2">
<Tool
Name="VCCLCompilerTool"
Optimization="0"
InlineFunctionExpansion="0"
EnableIntrinsicFunctions="FALSE"
AdditionalIncludeDirectories="include;..\include"
PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;POCO_DLL;WinTestRunner_EXPORTS;WINVER=0x0500"
BasicRuntimeChecks="3"
RuntimeLibrary="3"
BufferSecurityCheck="TRUE"
TreatWChar_tAsBuiltInType="TRUE"
ForceConformanceInForLoopScope="TRUE"
RuntimeTypeInfo="TRUE"
PrecompiledHeaderFile=""
AssemblerListingLocation=""
ObjectFile="$(IntDir)\"
ProgramDataBaseFileName="$(IntDir)\vc70.pdb"
WarningLevel="3"
SuppressStartupBanner="TRUE"
Detect64BitPortabilityProblems="TRUE"
DebugInformationFormat="4"
CompileAs="0"
ShowIncludes="FALSE"/>
<Tool
Name="VCCustomBuildTool"/>
<Tool
Name="VCLinkerTool"
AdditionalDependencies="cppunitd.lib winmm.lib"
ShowProgress="0"
OutputFile="..\..\bin\WinTestRunnerd.dll"
LinkIncremental="2"
SuppressStartupBanner="TRUE"
AdditionalLibraryDirectories="..\..\lib"
GenerateDebugInformation="TRUE"
ProgramDatabaseFile="..\..\bin\WinTestRunnerd.pdb"
SubSystem="2"
ImportLibrary="..\..\lib\WinTestRunnerd.lib"
TargetMachine="1"/>
<Tool
Name="VCMIDLTool"
PreprocessorDefinitions="_DEBUG"
MkTypLibCompatible="TRUE"
SuppressStartupBanner="TRUE"
TargetEnvironment="1"
TypeLibraryName=".\lib\wintestrunner.tlb"
HeaderFileName=""/>
<Tool
Name="VCPostBuildEventTool"/>
<Tool
Name="VCPreBuildEventTool"/>
<Tool
Name="VCPreLinkEventTool"/>
<Tool
Name="VCResourceCompilerTool"
PreprocessorDefinitions="_DEBUG"
Culture="3079"/>
<Tool
Name="VCWebServiceProxyGeneratorTool"/>
<Tool
Name="VCXMLDataGeneratorTool"/>
<Tool
Name="VCWebDeploymentTool"/>
<Tool
Name="VCManagedWrapperGeneratorTool"/>
<Tool
Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
</Configuration>
</Configurations>
<References>
</References>
<Files>
<Filter
Name="Source Files"
Filter="cpp;c;cxx;rc;def;r;odl;idl;hpj;bat">
<File
RelativePath="src\ActiveTest.cpp">
</File>
<File
RelativePath=".\src\DLLMain.cpp">
</File>
<File
RelativePath="src\GUITestResult.cpp">
</File>
<File
RelativePath="src\ProgressBar.cpp">
</File>
<File
RelativePath="src\TestRunnerDlg.cpp">
</File>
<File
RelativePath=".\src\WinTestRunner.cpp">
</File>
</Filter>
<Filter
Name="Include Files"
Filter="*.h">
<File
RelativePath=".\src\ActiveTest.h">
</File>
<File
RelativePath=".\src\GUITestResult.h">
</File>
<File
RelativePath=".\src\ProgressBar.h">
</File>
<File
RelativePath=".\src\TestRunnerDlg.h">
</File>
<File
RelativePath=".\include\WinTestRunner\WinTestRunner.h">
</File>
</Filter>
<Filter
Name="Resource Files"
Filter="">
<File
RelativePath=".\res\Resource.h">
</File>
<File
RelativePath=".\res\WinTestRunner.rc">
</File>
</Filter>
</Files>
<Globals>
<Global
Name="RESOURCE_FILE"
Value="TestRunner.rc"/>
</Globals>
</VisualStudioProject>

View File

@ -0,0 +1,301 @@
<?xml version="1.0" encoding="Windows-1252"?>
<VisualStudioProject
ProjectType="Visual C++"
Version="8.00"
Name="WinTestRunner"
ProjectGUID="{BA620CC4-0E7D-4B9D-88E2-6DBE5C51FCBD}"
Keyword="MFCProj"
>
<Platforms>
<Platform
Name="Win32"
/>
</Platforms>
<ToolFiles>
</ToolFiles>
<Configurations>
<Configuration
Name="release_shared|Win32"
OutputDirectory=".\obj\release_shared"
IntermediateDirectory=".\obj\release_shared"
ConfigurationType="2"
InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
UseOfMFC="2"
ATLMinimizesCRunTimeLibraryUsage="false"
CharacterSet="2"
>
<Tool
Name="VCPreBuildEventTool"
/>
<Tool
Name="VCCustomBuildTool"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCWebServiceProxyGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
PreprocessorDefinitions="NDEBUG"
MkTypLibCompatible="true"
SuppressStartupBanner="true"
TargetEnvironment="1"
TypeLibraryName=".\lib\wintestrunner.tlb"
HeaderFileName=""
/>
<Tool
Name="VCCLCompilerTool"
Optimization="4"
InlineFunctionExpansion="1"
EnableIntrinsicFunctions="true"
FavorSizeOrSpeed="1"
OmitFramePointers="true"
AdditionalIncludeDirectories="include;..\include"
PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;WinTestRunner_EXPORTS;WINVER=0x0500;_CRT_SECURE_NO_DEPRECATE"
RuntimeLibrary="2"
BufferSecurityCheck="false"
TreatWChar_tAsBuiltInType="true"
ForceConformanceInForLoopScope="true"
RuntimeTypeInfo="true"
PrecompiledHeaderFile=""
AssemblerListingLocation=""
ObjectFile="$(IntDir)\"
ProgramDataBaseFileName="$(IntDir)/vc70.pdb"
WarningLevel="3"
SuppressStartupBanner="true"
Detect64BitPortabilityProblems="true"
CompileAs="0"
/>
<Tool
Name="VCManagedResourceCompilerTool"
/>
<Tool
Name="VCResourceCompilerTool"
PreprocessorDefinitions="NDEBUG"
Culture="3079"
/>
<Tool
Name="VCPreLinkEventTool"
/>
<Tool
Name="VCLinkerTool"
AdditionalDependencies="cppunit.lib winmm.lib"
OutputFile="..\..\bin\WinTestRunner.dll"
LinkIncremental="1"
SuppressStartupBanner="true"
AdditionalLibraryDirectories="..\..\lib"
ProgramDatabaseFile=""
SubSystem="2"
ImportLibrary="..\..\lib\WinTestRunner.lib"
TargetMachine="1"
/>
<Tool
Name="VCALinkTool"
/>
<Tool
Name="VCManifestTool"
/>
<Tool
Name="VCXDCMakeTool"
/>
<Tool
Name="VCBscMakeTool"
/>
<Tool
Name="VCFxCopTool"
/>
<Tool
Name="VCAppVerifierTool"
/>
<Tool
Name="VCWebDeploymentTool"
/>
<Tool
Name="VCPostBuildEventTool"
/>
</Configuration>
<Configuration
Name="debug_shared|Win32"
OutputDirectory=".\obj\debug_shared"
IntermediateDirectory=".\obj\debug_shared"
ConfigurationType="2"
InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
UseOfMFC="2"
ATLMinimizesCRunTimeLibraryUsage="false"
CharacterSet="2"
>
<Tool
Name="VCPreBuildEventTool"
/>
<Tool
Name="VCCustomBuildTool"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCWebServiceProxyGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
PreprocessorDefinitions="_DEBUG"
MkTypLibCompatible="true"
SuppressStartupBanner="true"
TargetEnvironment="1"
TypeLibraryName=".\lib\wintestrunner.tlb"
HeaderFileName=""
/>
<Tool
Name="VCCLCompilerTool"
Optimization="0"
InlineFunctionExpansion="0"
EnableIntrinsicFunctions="false"
AdditionalIncludeDirectories="include;..\include"
PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;WinTestRunner_EXPORTS;WINVER=0x0500;_CRT_SECURE_NO_DEPRECATE"
BasicRuntimeChecks="3"
RuntimeLibrary="3"
BufferSecurityCheck="true"
TreatWChar_tAsBuiltInType="true"
ForceConformanceInForLoopScope="true"
RuntimeTypeInfo="true"
PrecompiledHeaderFile=""
AssemblerListingLocation=""
ObjectFile="$(IntDir)\"
ProgramDataBaseFileName="$(IntDir)\vc70.pdb"
WarningLevel="3"
SuppressStartupBanner="true"
Detect64BitPortabilityProblems="true"
DebugInformationFormat="4"
CompileAs="0"
ShowIncludes="false"
/>
<Tool
Name="VCManagedResourceCompilerTool"
/>
<Tool
Name="VCResourceCompilerTool"
PreprocessorDefinitions="_DEBUG"
Culture="3079"
/>
<Tool
Name="VCPreLinkEventTool"
/>
<Tool
Name="VCLinkerTool"
AdditionalDependencies="cppunitd.lib winmm.lib"
ShowProgress="0"
OutputFile="..\..\bin\WinTestRunnerd.dll"
LinkIncremental="2"
SuppressStartupBanner="true"
AdditionalLibraryDirectories="..\..\lib"
GenerateDebugInformation="true"
ProgramDatabaseFile="..\..\bin\WinTestRunnerd.pdb"
SubSystem="2"
ImportLibrary="..\..\lib\WinTestRunnerd.lib"
TargetMachine="1"
/>
<Tool
Name="VCALinkTool"
/>
<Tool
Name="VCManifestTool"
/>
<Tool
Name="VCXDCMakeTool"
/>
<Tool
Name="VCBscMakeTool"
/>
<Tool
Name="VCFxCopTool"
/>
<Tool
Name="VCAppVerifierTool"
/>
<Tool
Name="VCWebDeploymentTool"
/>
<Tool
Name="VCPostBuildEventTool"
/>
</Configuration>
</Configurations>
<References>
</References>
<Files>
<Filter
Name="Source Files"
Filter="cpp;c;cxx;rc;def;r;odl;idl;hpj;bat"
>
<File
RelativePath="src\ActiveTest.cpp"
>
</File>
<File
RelativePath=".\src\DLLMain.cpp"
>
</File>
<File
RelativePath="src\GUITestResult.cpp"
>
</File>
<File
RelativePath="src\ProgressBar.cpp"
>
</File>
<File
RelativePath="src\TestRunnerDlg.cpp"
>
</File>
<File
RelativePath=".\src\WinTestRunner.cpp"
>
</File>
</Filter>
<Filter
Name="Include Files"
Filter="*.h"
>
<File
RelativePath=".\src\ActiveTest.h"
>
</File>
<File
RelativePath=".\src\GUITestResult.h"
>
</File>
<File
RelativePath=".\src\ProgressBar.h"
>
</File>
<File
RelativePath=".\src\TestRunnerDlg.h"
>
</File>
<File
RelativePath=".\include\WinTestRunner\WinTestRunner.h"
>
</File>
</Filter>
<Filter
Name="Resource Files"
>
<File
RelativePath=".\res\Resource.h"
>
</File>
<File
RelativePath=".\res\WinTestRunner.rc"
>
</File>
</Filter>
</Files>
<Globals>
<Global
Name="RESOURCE_FILE"
Value="TestRunner.rc"
/>
</Globals>
</VisualStudioProject>

View File

@ -0,0 +1,68 @@
//
// WinTestRunner.h
//
// $Id: //poco/1.1.0/CppUnit/WinTestRunner/include/WinTestRunner/WinTestRunner.h#1 $
//
// Application shell for CppUnit's TestRunner dialog.
//
#ifndef WinTestRunner_H_INCLUDED
#define WinTestRunner_H_INCLUDED
#if defined(WinTestRunner_EXPORTS)
#define WinTestRunner_API __declspec(dllexport)
#else
#define WinTestRunner_API __declspec(dllimport)
#endif
#ifndef CppUnit_CppUnit_INCLUDED
#include "CppUnit/CppUnit.h"
#endif
#ifndef STD_VECTOR_INCLUDED
#include <vector>
#define STD_VECTOR_INCLUDED
#endif
#include <afxwin.h>
CppUnit_BEGIN
class Test;
class WinTestRunner_API WinTestRunner
{
public:
WinTestRunner();
~WinTestRunner();
void run();
void addTest(Test* pTest);
private:
std::vector<Test*> _tests;
};
class WinTestRunner_API WinTestRunnerApp: public CWinApp
/// A simple application class that hosts the TestRunner dialog.
/// Create a subclass and override the TestMain() method.
{
public:
virtual BOOL InitInstance();
virtual void TestMain() = 0;
DECLARE_MESSAGE_MAP()
};
CppUnit_END
#endif // WinTestRunner_H_INCLUDED

View File

@ -0,0 +1,27 @@
//{{NO_DEPENDENCIES}}
// Microsoft Visual C++ generated include file.
// Used by TestRunner.rc
//
#define IDD_DIALOG_TESTRUNNER 129
#define IDC_LIST 1000
#define ID_RUN 1001
#define ID_STOP 1002
#define IDC_PROGRESS 1003
#define IDC_INDICATOR 1004
#define IDC_COMBO_TEST 1005
#define IDC_STATIC_RUNS 1007
#define IDC_STATIC_ERRORS 1008
#define IDC_STATIC_FAILURES 1009
#define IDC_EDIT_TIME 1010
#define IDC_CHK_AUTORUN 1013
// Next default values for new objects
//
#ifdef APSTUDIO_INVOKED
#ifndef APSTUDIO_READONLY_SYMBOLS
#define _APS_NEXT_RESOURCE_VALUE 131
#define _APS_NEXT_COMMAND_VALUE 32771
#define _APS_NEXT_CONTROL_VALUE 1014
#define _APS_NEXT_SYMED_VALUE 101
#endif
#endif

View File

@ -0,0 +1,175 @@
// Microsoft Visual C++ generated resource script.
//
#include "resource.h"
#define APSTUDIO_READONLY_SYMBOLS
/////////////////////////////////////////////////////////////////////////////
//
// Generated from the TEXTINCLUDE 2 resource.
//
#include "afxres.h"
/////////////////////////////////////////////////////////////////////////////
#undef APSTUDIO_READONLY_SYMBOLS
/////////////////////////////////////////////////////////////////////////////
// English (U.S.) resources
#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU)
#ifdef _WIN32
LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US
#pragma code_page(1252)
#endif //_WIN32
#ifdef APSTUDIO_INVOKED
/////////////////////////////////////////////////////////////////////////////
//
// TEXTINCLUDE
//
1 TEXTINCLUDE
BEGIN
"resource.h\0"
END
2 TEXTINCLUDE
BEGIN
"#include ""afxres.h""\r\n"
"\0"
END
3 TEXTINCLUDE
BEGIN
"#define _AFX_NO_SPLITTER_RESOURCES\r\n"
"#define _AFX_NO_OLE_RESOURCES\r\n"
"#define _AFX_NO_TRACKER_RESOURCES\r\n"
"#define _AFX_NO_PROPERTY_RESOURCES\r\n"
"\r\n"
"#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU)\r\n"
"#ifdef _WIN32\r\n"
"LANGUAGE 9, 1\r\n"
"#pragma code_page(1252)\r\n"
"#endif\r\n"
"#include ""..\\res\\WinTestRunner.rc2"" // non-Microsoft Visual C++ edited resources\r\n"
"#include ""afxres.rc"" // Standard components\r\n"
"#endif\0"
END
#endif // APSTUDIO_INVOKED
/////////////////////////////////////////////////////////////////////////////
//
// Version
//
VS_VERSION_INFO VERSIONINFO
FILEVERSION 1,0,0,1
PRODUCTVERSION 1,0,0,1
FILEFLAGSMASK 0x3fL
#ifdef _DEBUG
FILEFLAGS 0x1L
#else
FILEFLAGS 0x0L
#endif
FILEOS 0x4L
FILETYPE 0x2L
FILESUBTYPE 0x0L
BEGIN
BLOCK "StringFileInfo"
BEGIN
BLOCK "040904b0"
BEGIN
VALUE "FileDescription", "CppUnit WinTestRunner DLL"
VALUE "FileVersion", "1, 0, 0, 1"
VALUE "InternalName", "WinTestRunner"
VALUE "LegalCopyright", "Copyright (c) 2005"
VALUE "OriginalFilename", "TestRunner.dll"
VALUE "ProductName", "CppUnit WinTestRunner Dynamic Link Library"
VALUE "ProductVersion", "1, 0, 0, 1"
END
END
BLOCK "VarFileInfo"
BEGIN
VALUE "Translation", 0x409, 1200
END
END
/////////////////////////////////////////////////////////////////////////////
//
// Dialog
//
IDD_DIALOG_TESTRUNNER DIALOGEX 0, 0, 512, 300
STYLE DS_SETFONT | DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU
CAPTION "CppUnit WinTestRunner"
FONT 8, "MS Sans Serif", 0, 0, 0x0
BEGIN
COMBOBOX IDC_COMBO_TEST,7,20,424,273,CBS_DROPDOWNLIST |
WS_VSCROLL | WS_TABSTOP
DEFPUSHBUTTON "Run",ID_RUN,455,7,50,14
DEFPUSHBUTTON "Stop",ID_STOP,455,24,50,14
CONTROL "List1",IDC_LIST,"SysListView32",LVS_REPORT | WS_BORDER |
WS_TABSTOP,7,110,498,160
PUSHBUTTON "Close",IDOK,455,279,50,14
LTEXT "Test Name:",IDC_STATIC,7,9,179,9
LTEXT "Progress:",IDC_STATIC,7,55,49,9
LTEXT "Errors and Failures:",IDC_STATIC,7,99,67,9
LTEXT "Runs:",IDC_STATIC,457,54,26,10
LTEXT "Failures:",IDC_STATIC,457,80,26,10
LTEXT "Errors:",IDC_STATIC,457,67,26,10
RTEXT "0",IDC_STATIC_RUNS,487,54,16,10
RTEXT "0",IDC_STATIC_ERRORS,487,67,16,10
RTEXT "0",IDC_STATIC_FAILURES,487,80,16,10
EDITTEXT IDC_EDIT_TIME,7,281,440,12,ES_AUTOHSCROLL | ES_READONLY |
NOT WS_BORDER
LTEXT "",IDC_PROGRESS,7,67,424,20,SS_SUNKEN | NOT WS_VISIBLE
CONTROL "Auto Run",IDC_CHK_AUTORUN,"Button",BS_AUTOCHECKBOX |
BS_LEFTTEXT | WS_TABSTOP,383,38,46,10
END
/////////////////////////////////////////////////////////////////////////////
//
// DESIGNINFO
//
#ifdef APSTUDIO_INVOKED
GUIDELINES DESIGNINFO
BEGIN
IDD_DIALOG_TESTRUNNER, DIALOG
BEGIN
LEFTMARGIN, 7
RIGHTMARGIN, 505
TOPMARGIN, 7
BOTTOMMARGIN, 293
END
END
#endif // APSTUDIO_INVOKED
#endif // English (U.S.) resources
/////////////////////////////////////////////////////////////////////////////
#ifndef APSTUDIO_INVOKED
/////////////////////////////////////////////////////////////////////////////
//
// Generated from the TEXTINCLUDE 3 resource.
//
#define _AFX_NO_SPLITTER_RESOURCES
#define _AFX_NO_OLE_RESOURCES
#define _AFX_NO_TRACKER_RESOURCES
#define _AFX_NO_PROPERTY_RESOURCES
#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU)
#ifdef _WIN32
LANGUAGE 9, 1
#pragma code_page(1252)
#endif
#include "afxres.rc" // Standard components
#endif
/////////////////////////////////////////////////////////////////////////////
#endif // not APSTUDIO_INVOKED

View File

@ -0,0 +1,44 @@
//
// ActiveTest.cpp
//
// $Id: //poco/1.1.0/CppUnit/WinTestRunner/src/ActiveTest.cpp#1 $
//
#include <afxwin.h>
#include "ActiveTest.h"
CppUnit_BEGIN
// Spawn a thread to a test
void ActiveTest::run(TestResult* result)
{
CWinThread* thread;
setTestResult(result);
_runCompleted.ResetEvent();
thread = AfxBeginThread(threadFunction, this, THREAD_PRIORITY_NORMAL, 0, CREATE_SUSPENDED);
DuplicateHandle(GetCurrentProcess(), thread->m_hThread, GetCurrentProcess(), &_threadHandle, 0, FALSE, DUPLICATE_SAME_ACCESS);
thread->ResumeThread();
}
// Simple execution thread. Assuming that an ActiveTest instance
// only creates one of these at a time.
UINT ActiveTest::threadFunction(LPVOID thisInstance)
{
ActiveTest* test = (ActiveTest*) thisInstance;
test->run();
test->_runCompleted.SetEvent();
return 0;
}
CppUnit_END

View File

@ -0,0 +1,93 @@
//
// ActiveTest.h
//
// $Id: //poco/1.1.0/CppUnit/WinTestRunner/src/ActiveTest.h#1 $
//
#ifndef ActiveTest_INCLUDED
#define ActiveTest_INCLUDED
#ifndef CppUnit_CppUnit_INCLUDED
#include "CppUnit/CppUnit.h"
#endif
#ifndef CppUnit_TestDecorator_INCLUDED
#include "CppUnit/TestDecorator.h"
#endif
#include <afxmt.h>
CppUnit_BEGIN
/* A Microsoft-specific active test
*
* An active test manages its own
* thread of execution. This one
* is very simple and only sufficient
* for the limited use we put it through
* in the TestRunner. It spawns a thread
* on run (TestResult *) and signals
* completion of the test.
*
* We assume that only one thread
* will be active at once for each
* instance.
*
*/
class ActiveTest: public TestDecorator
{
public:
ActiveTest(Test* test);
~ActiveTest();
void run(TestResult* result);
protected:
HANDLE _threadHandle;
CEvent _runCompleted;
TestResult* _currentTestResult;
void run ();
void setTestResult(TestResult* result);
static UINT threadFunction(LPVOID thisInstance);
};
// Construct the active test
inline ActiveTest::ActiveTest(Test *test): TestDecorator(test)
{
_currentTestResult = NULL;
_threadHandle = INVALID_HANDLE_VALUE;
}
// Pend until the test has completed
inline ActiveTest::~ActiveTest()
{
CSingleLock(&_runCompleted, TRUE);
CloseHandle(_threadHandle);
}
// Set the test result that we are to run
inline void ActiveTest::setTestResult(TestResult* result)
{
_currentTestResult = result;
}
// Run our test result
inline void ActiveTest::run()
{
TestDecorator::run(_currentTestResult);
}
CppUnit_END
#endif // ActiveTest_INCLUDED

View File

@ -0,0 +1,50 @@
//
// DLLMain.cpp
//
// $Id: //poco/1.1.0/CppUnit/WinTestRunner/src/DLLMain.cpp#1 $
//
#include <afxwin.h>
#include <afxdllx.h>
static AFX_EXTENSION_MODULE TestRunnerDLL = { NULL, NULL };
extern "C" int APIENTRY
DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID lpReserved)
{
// Remove this if you use lpReserved
UNREFERENCED_PARAMETER(lpReserved);
if (dwReason == DLL_PROCESS_ATTACH)
{
TRACE0("WinTestRunner.DLL Initializing\n");
// Extension DLL one-time initialization
if (!AfxInitExtensionModule(TestRunnerDLL, hInstance))
return 0;
// Insert this DLL into the resource chain
// NOTE: If this Extension DLL is being implicitly linked to by
// an MFC Regular DLL (such as an ActiveX Control)
// instead of an MFC application, then you will want to
// remove this line from DllMain and put it in a separate
// function exported from this Extension DLL. The Regular DLL
// that uses this Extension DLL should then explicitly call that
// function to initialize this Extension DLL. Otherwise,
// the CDynLinkLibrary object will not be attached to the
// Regular DLL's resource chain, and serious problems will
// result.
new CDynLinkLibrary(TestRunnerDLL);
}
else if (dwReason == DLL_PROCESS_DETACH)
{
TRACE0("WinTestRunner.DLL Terminating\n");
// Terminate the library before destructors are called
AfxTermExtensionModule(TestRunnerDLL);
}
return 1; // ok
}

View File

@ -0,0 +1,43 @@
//
// GUITestResult.cpp
//
// $Id: //poco/1.1.0/CppUnit/WinTestRunner/src/GUITestResult.cpp#1 $
//
#include "TestRunnerDlg.h"
#include "GUITestResult.h"
CppUnit_BEGIN
void GUITestResult::addError(Test *test, CppUnitException *e)
{
ExclusiveZone zone(_syncObject);
TestResult::addError(test, e);
_runner->addError(this, test, e);
}
void GUITestResult::addFailure(Test *test, CppUnitException *e)
{
ExclusiveZone zone(_syncObject);
TestResult::addFailure(test, e);
_runner->addFailure(this, test, e);
}
void GUITestResult::endTest(Test *test)
{
ExclusiveZone zone(_syncObject);
TestResult::endTest(test);
_runner->endTest(this, test);
}
CppUnit_END

View File

@ -0,0 +1,86 @@
//
// GUITestResult.h
//
// $Id: //poco/1.1.0/CppUnit/WinTestRunner/src/GUITestResult.h#1 $
//
#ifndef GuiTestResult_INCLUDED
#define GuiTestResult_INCLUDED
#ifndef CppUnit_CppUnit_INCLUDED
#include "CppUnit/CppUnit.h"
#endif
#ifndef CppUnit_TestResult_INCLUDED
#include "CppUnit/TestResult.h"
#endif
#include <afxmt.h>
CppUnit_BEGIN
class TestRunnerDlg;
class GUITestResult: public TestResult
{
public:
GUITestResult(TestRunnerDlg* runner);
~GUITestResult();
void addError(Test* test, CppUnitException* e);
void addFailure(Test* test, CppUnitException* e);
void endTest(Test* test);
void stop();
protected:
class LightweightSynchronizationObject: public TestResult::SynchronizationObject
{
public:
void lock()
{
_syncObject.Lock();
}
void unlock()
{
_syncObject.Unlock();
}
private:
CCriticalSection _syncObject;
};
private:
TestRunnerDlg *_runner;
};
// Construct with lightweight synchronization
inline GUITestResult::GUITestResult(TestRunnerDlg* runner): _runner(runner)
{
setSynchronizationObject(new LightweightSynchronizationObject());
}
// Destructor
inline GUITestResult::~GUITestResult()
{
}
// Override without protection to prevent deadlock
inline void GUITestResult::stop()
{
_stop = true;
}
CppUnit_END
#endif // GuiTestResult_INCLUDED

View File

@ -0,0 +1,140 @@
//
// ProgressBar.cpp
//
// $Id: //poco/1.1.0/CppUnit/WinTestRunner/src/ProgressBar.cpp#1 $
//
#include "ProgressBar.h"
CppUnit_BEGIN
// Paint the progress bar in response to a paint message
void ProgressBar::paint(CDC& dc)
{
paintBackground (dc);
paintStatus (dc);
}
// Paint the background of the progress bar region
void ProgressBar::paintBackground (CDC& dc)
{
CBrush brshBackground;
CPen penGray (PS_SOLID, 1, RGB (128, 128, 128));
CPen penWhite (PS_SOLID, 1, RGB (255, 255, 255));
VERIFY (brshBackground.CreateSolidBrush (::GetSysColor (COLOR_BTNFACE)));
dc.FillRect (_bounds, &brshBackground);
CPen *pOldPen;
pOldPen = dc.SelectObject (&penGray);
{
dc.MoveTo (_bounds.left, _bounds.top);
dc.LineTo (_bounds.left + _bounds.Width () -1, _bounds.top);
dc.MoveTo (_bounds.left, _bounds.top);
dc.LineTo (_bounds.left, _bounds.top + _bounds.Height () -1);
}
dc.SelectObject (&penWhite);
{
dc.MoveTo (_bounds.left + _bounds.Width () -1, _bounds.top);
dc.LineTo (_bounds.left + _bounds.Width () -1, _bounds.top + _bounds.Height () -1);
dc.MoveTo (_bounds.left, _bounds.top + _bounds.Height () -1);
dc.LineTo (_bounds.left + _bounds.Width () -1, _bounds.top + _bounds.Height () -1);
}
dc.SelectObject (pOldPen);
}
// Paint the actual status of the progress bar
void ProgressBar::paintStatus (CDC& dc)
{
if (_progress <= 0)
return;
CBrush brshStatus;
CRect rect (_bounds.left, _bounds.top,
_bounds.left + _progressX, _bounds.bottom);
COLORREF statusColor = getStatusColor ();
VERIFY (brshStatus.CreateSolidBrush (statusColor));
rect.DeflateRect (1, 1);
dc.FillRect (rect, &brshStatus);
}
// Paint the current step
void ProgressBar::paintStep (int startX, int endX)
{
// kludge: painting the whole region on each step
_baseWindow->RedrawWindow (_bounds);
_baseWindow->UpdateWindow ();
}
// Setup the progress bar for execution over a total number of steps
void ProgressBar::start (int total)
{
_total = total;
reset ();
}
// Take one step, indicating whether it was a successful step
void ProgressBar::step (bool successful)
{
_progress++;
int x = _progressX;
_progressX = scale (_progress);
if (!_error && !successful)
{
_error = true;
x = 1;
}
paintStep (x, _progressX);
}
// Map from steps to display units
int ProgressBar::scale (int value)
{
if (_total > 0)
return max (1, value * (_bounds.Width () - 1) / _total);
return value;
}
// Reset the progress bar
void ProgressBar::reset ()
{
_progressX = 1;
_progress = 0;
_error = false;
_baseWindow->RedrawWindow (_bounds);
_baseWindow->UpdateWindow ();
}
CppUnit_END

View File

@ -0,0 +1,76 @@
//
// ProgressBar.h
//
// $Id: //poco/1.1.0/CppUnit/WinTestRunner/src/ProgressBar.h#1 $
//
#ifndef ProgressBar_INCLUDED
#define ProgressBar_INCLUDED
#ifndef CppUnit_CppUnit_INCLUDED
#include "CppUnit/CppUnit.h"
#endif
#include <afxwin.h>
CppUnit_BEGIN
/* A Simple ProgressBar for test execution display
*/
class ProgressBar
{
public:
ProgressBar(CWnd* baseWindow, CRect& bounds);
void step(bool successful);
void paint(CDC& dc);
int scale(int value);
void reset();
void start(int total);
protected:
void paintBackground(CDC& dc);
void paintStatus(CDC& dc);
COLORREF getStatusColor();
void paintStep(int startX, int endX);
CWnd* _baseWindow;
CRect _bounds;
bool _error;
int _total;
int _progress;
int _progressX;
};
// Construct a ProgressBar
inline ProgressBar::ProgressBar(CWnd* baseWindow, CRect& bounds):
_baseWindow(baseWindow),
_bounds(bounds),
_error(false),
_total(0),
_progress(0),
_progressX(0)
{
WINDOWINFO wi;
wi.cbSize = sizeof(WINDOWINFO);
baseWindow->GetWindowInfo(&wi);
_bounds.OffsetRect(-wi.rcClient.left, -wi.rcClient.top);
}
// Get the current color
inline COLORREF ProgressBar::getStatusColor()
{
return _error ? RGB(255, 0, 0) : RGB(0, 255, 0);
}
CppUnit_END
#endif // ProgressBar_INCLUDED

View File

@ -0,0 +1,106 @@
#ifndef SYNCHRONIZEDTESTRESULTDECORATOR_H
#define SYNCHRONIZEDTESTRESULTDECORATOR_H
#include <afxmt.h>
#include "TestResultDecorator.h"
class SynchronizedTestResult : public TestResultDecorator
{
public:
SynchronizedTestResult (TestResult *result);
~SynchronizedTestResult ();
bool shouldStop ();
void addError (Test *test, CppUnitException *e);
void addFailure (Test *test, CppUnitException *e);
void startTest (Test *test);
void endTest (Test *test);
int runTests ();
int testErrors ();
int testFailures ();
bool wasSuccessful ();
void stop ();
vector<TestFailure *>& errors ();
vector<TestFailure *>& failures ();
private:
CCriticalSection m_criticalSection;
};
// Constructor
inline SynchronizedTestResult::SynchronizedTestResult (TestResult *result)
: TestResultDecorator (result) {}
// Destructor
inline SynchronizedTestResult::~SynchronizedTestResult ()
{}
// Returns whether the test should stop
inline bool SynchronizedTestResult::shouldStop ()
{ CSingleLock sync (&m_criticalSection, TRUE); return m_result->shouldStop (); }
// Adds an error to the list of errors. The passed in exception
// caused the error
inline void SynchronizedTestResult::addError (Test *test, CppUnitException *e)
{ CSingleLock sync (&m_criticalSection, TRUE); m_result->addError (test, e); }
// Adds a failure to the list of failures. The passed in exception
// caused the failure.
inline void SynchronizedTestResult::addFailure (Test *test, CppUnitException *e)
{ CSingleLock sync (&m_criticalSection, TRUE); m_result->addFailure (test, e); }
// Informs the result that a test will be started.
inline void SynchronizedTestResult::startTest (Test *test)
{ CSingleLock sync (&m_criticalSection, TRUE); m_result->startTest (test); }
// Informs the result that a test was completed.
inline void SynchronizedTestResult::endTest (Test *test)
{ CSingleLock sync (&m_criticalSection, TRUE); m_result->endTest (test); }
// Gets the number of run tests.
inline int SynchronizedTestResult::runTests ()
{ CSingleLock sync (&m_criticalSection, TRUE); return m_result->runTests (); }
// Gets the number of detected errors.
inline int SynchronizedTestResult::testErrors ()
{ CSingleLock sync (&m_criticalSection, TRUE); return m_result->testErrors (); }
// Gets the number of detected failures.
inline int SynchronizedTestResult::testFailures ()
{ CSingleLock sync (&m_criticalSection, TRUE); return m_result->testFailures (); }
// Returns whether the entire test was successful or not.
inline bool SynchronizedTestResult::wasSuccessful ()
{ CSingleLock sync (&m_criticalSection, TRUE); return m_result->wasSuccessful (); }
// Marks that the test run should stop.
inline void SynchronizedTestResult::stop ()
{ CSingleLock sync (&m_criticalSection, TRUE); m_result->stop (); }
// Returns a vector of the errors.
inline vector<TestFailure *>& SynchronizedTestResult::errors ()
{ CSingleLock sync (&m_criticalSection, TRUE); return m_result->errors (); }
// Returns a vector of the failures.
inline vector<TestFailure *>& SynchronizedTestResult::failures ()
{ CSingleLock sync (&m_criticalSection, TRUE); return m_result->failures (); }
#endif

View File

@ -0,0 +1,102 @@
#ifndef CPP_UNIT_TESTRESULTDECORATOR_H
#define CPP_UNIT_TESTRESULTDECORATOR_H
#include "TestResult.h"
class TestResultDecorator
{
public:
TestResultDecorator (TestResult *result);
virtual ~TestResultDecorator ();
virtual bool shouldStop ();
virtual void addError (Test *test, CppUnitException *e);
virtual void addFailure (Test *test, CppUnitException *e);
virtual void startTest (Test *test);
virtual void endTest (Test *test);
virtual int runTests ();
virtual int testErrors ();
virtual int testFailures ();
virtual bool wasSuccessful ();
virtual void stop ();
vector<TestFailure *>& errors ();
vector<TestFailure *>& failures ();
protected:
TestResult *m_result;
};
inline TestResultDecorator::TestResultDecorator (TestResult *result)
: m_result (result) {}
inline TestResultDecorator::~TestResultDecorator ()
{}
// Returns whether the test should stop
inline bool TestResultDecorator::shouldStop ()
{ return m_result->shouldStop (); }
// Adds an error to the list of errors. The passed in exception
// caused the error
inline void TestResultDecorator::addError (Test *test, CppUnitException *e)
{ m_result->addError (test, e); }
// Adds a failure to the list of failures. The passed in exception
// caused the failure.
inline void TestResultDecorator::addFailure (Test *test, CppUnitException *e)
{ m_result->addFailure (test, e); }
// Informs the result that a test will be started.
inline void TestResultDecorator::startTest (Test *test)
{ m_result->startTest (test); }
// Informs the result that a test was completed.
inline void TestResultDecorator::endTest (Test *test)
{ m_result->endTest (test); }
// Gets the number of run tests.
inline int TestResultDecorator::runTests ()
{ return m_result->runTests (); }
// Gets the number of detected errors.
inline int TestResultDecorator::testErrors ()
{ return m_result->testErrors (); }
// Gets the number of detected failures.
inline int TestResultDecorator::testFailures ()
{ return m_result->testFailures (); }
// Returns whether the entire test was successful or not.
inline bool TestResultDecorator::wasSuccessful ()
{ return m_result->wasSuccessful (); }
// Marks that the test run should stop.
inline void TestResultDecorator::stop ()
{ m_result->stop (); }
// Returns a vector of the errors.
inline vector<TestFailure *>& TestResultDecorator::errors ()
{ return m_result->errors (); }
// Returns a vector of the failures.
inline vector<TestFailure *>& TestResultDecorator::failures ()
{ return m_result->failures (); }
#endif

View File

@ -0,0 +1,424 @@
//
// TestRunnerDlg.cpp
//
// $Id: //poco/1.1.0/CppUnit/WinTestRunner/src/TestRunnerDlg.cpp#1 $
//
#include <afxwin.h>
#include <afxext.h>
#include <afxcmn.h>
#include <mmsystem.h>
#include "TestRunnerDlg.h"
#include "ActiveTest.h"
#include "GUITestResult.h"
#include "ProgressBar.h"
#include "CppUnit/TestSuite.h"
#include "TestRunnerDlg.h"
CppUnit_BEGIN
TestRunnerDlg::TestRunnerDlg(CWnd* pParent): CDialog(TestRunnerDlg::IDD, pParent)
{
//{{AFX_DATA_INIT(TestRunnerDlg)
// NOTE: the ClassWizard will add member initialization here
//}}AFX_DATA_INIT
_testsProgress = 0;
_selectedTest = 0;
}
void TestRunnerDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(TestRunnerDlg)
// NOTE: the ClassWizard will add DDX and DDV calls here
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(TestRunnerDlg, CDialog)
//{{AFX_MSG_MAP(TestRunnerDlg)
ON_BN_CLICKED(ID_RUN, OnRun)
ON_BN_CLICKED(ID_STOP, OnStop)
ON_CBN_SELCHANGE(IDC_COMBO_TEST, OnSelchangeComboTest)
ON_BN_CLICKED(IDC_CHK_AUTORUN, OnBnClickedAutorun)
ON_WM_PAINT()
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
BOOL TestRunnerDlg::OnInitDialog()
{
CDialog::OnInitDialog();
CListCtrl *listCtrl = (CListCtrl *)GetDlgItem (IDC_LIST);
CComboBox *comboBox = (CComboBox *)GetDlgItem (IDC_COMBO_TEST);
ASSERT (listCtrl);
ASSERT (comboBox);
CString title;
GetWindowText(title);
#if defined(_DEBUG)
title.Append(" [debug]");
#else
title.Append(" [release]");
#endif
SetWindowText(title);
listCtrl->InsertColumn (0,"Type", LVCFMT_LEFT, 16 + listCtrl->GetStringWidth ("Type"), 1);
listCtrl->InsertColumn (1,"Name", LVCFMT_LEFT, 16 * listCtrl->GetStringWidth ("X"), 2);
listCtrl->InsertColumn (2,"Failed Condition", LVCFMT_LEFT, 24 * listCtrl->GetStringWidth ("M"), 3);
listCtrl->InsertColumn (3,"Line", LVCFMT_LEFT, 16 + listCtrl->GetStringWidth ("0000"), 4);
listCtrl->InsertColumn (4,"File Name", LVCFMT_LEFT, 36 * listCtrl->GetStringWidth ("M"), 5);
int numberOfCases = 0;
CWinApp* pApp = AfxGetApp();
CString lastTestCS = pApp->GetProfileString("Tests", "lastTest");
std::string lastTest((LPCSTR) lastTestCS);
int sel = -1;
for (std::vector<TestInfo>::iterator it = _tests.begin (); it != _tests.end (); ++it)
{
std::string cbName(it->level*4, ' ');
cbName.append(it->pTest->toString());
comboBox->AddString (cbName.c_str ());
if (sel < 0)
{
if (lastTest.empty() || lastTest == it->pTest->toString())
{
_selectedTest = it->pTest;
sel = numberOfCases;
}
}
numberOfCases++;
}
if (numberOfCases > 0)
{
if (sel < 0)
{
_selectedTest = _tests[0].pTest;
sel = 0;
}
comboBox->SetCurSel (sel);
}
else
{
beRunDisabled ();
}
CWnd *pProgress = GetDlgItem(IDC_PROGRESS);
CRect rect;
pProgress->GetWindowRect(&rect);
_testsProgress = new ProgressBar (this, rect);
CButton* autoRunBtn = (CButton*) GetDlgItem(IDC_CHK_AUTORUN);
autoRunBtn->SetCheck(pApp->GetProfileInt("Tests", "autoRun", BST_UNCHECKED));
reset ();
if (autoRunBtn->GetCheck() == BST_CHECKED)
{
OnRun();
}
return TRUE; // return TRUE unless you set the focus to a control
// EXCEPTION: OCX Property Pages should return FALSE
}
TestRunnerDlg::~TestRunnerDlg ()
{
freeState ();
delete _testsProgress;
}
void TestRunnerDlg::OnRun()
{
if (_selectedTest == 0)
return;
freeState ();
reset ();
beRunning ();
int numberOfTests = _selectedTest->countTestCases ();
_testsProgress->start (numberOfTests);
_result = new GUITestResult ((TestRunnerDlg *)this);
_activeTest = new ActiveTest (_selectedTest);
_testStartTime = timeGetTime ();
_activeTest->run (_result);
_testEndTime = timeGetTime ();
}
void TestRunnerDlg::addListEntry(const std::string& type, TestResult *result, Test *test, CppUnitException *e)
{
char stage [80];
LV_ITEM lvi;
CListCtrl *listCtrl = (CListCtrl *)GetDlgItem (IDC_LIST);
int currentEntry = result->testErrors () + result->testFailures () -1;
sprintf (stage, "%s", type.c_str ());
lvi.mask = LVIF_TEXT;
lvi.iItem = currentEntry;
lvi.iSubItem = 0;
lvi.pszText = stage;
lvi.iImage = 0;
lvi.stateMask = 0;
lvi.state = 0;
listCtrl->InsertItem (&lvi);
// Set class string
listCtrl->SetItemText (currentEntry, 1, test->toString ().c_str ());
// Set the asserted text
listCtrl->SetItemText(currentEntry, 2, e->what ());
// Set the line number
if (e->lineNumber () == CppUnitException::CPPUNIT_UNKNOWNLINENUMBER)
sprintf (stage, "<unknown>");
else
sprintf (stage, "%ld", e->lineNumber ());
listCtrl->SetItemText(currentEntry, 3, stage);
// Set the file name
listCtrl->SetItemText(currentEntry, 4, e->fileName ().c_str ());
listCtrl->RedrawItems (currentEntry, currentEntry);
listCtrl->UpdateWindow ();
}
void TestRunnerDlg::addError (TestResult *result, Test *test, CppUnitException *e)
{
addListEntry ("Error", result, test, e);
_errors++;
updateCountsDisplay ();
}
void TestRunnerDlg::addFailure (TestResult *result, Test *test, CppUnitException *e)
{
addListEntry ("Failure", result, test, e);
_failures++;
updateCountsDisplay ();
}
void TestRunnerDlg::endTest (TestResult *result, Test *test)
{
if (_selectedTest == 0)
return;
_testsRun++;
updateCountsDisplay ();
_testsProgress->step (_failures == 0 && _errors == 0);
_testEndTime = timeGetTime ();
updateCountsDisplay ();
if (_testsRun >= _selectedTest->countTestCases ())
beIdle ();
}
void TestRunnerDlg::beRunning ()
{
CButton *runButton = (CButton *)GetDlgItem (ID_RUN);
CButton *closeButton = (CButton *)GetDlgItem (IDOK);
runButton->EnableWindow (FALSE);
closeButton->EnableWindow (FALSE);
}
void TestRunnerDlg::beIdle ()
{
CButton *runButton = (CButton *)GetDlgItem (ID_RUN);
CButton *closeButton = (CButton *)GetDlgItem (IDOK);
runButton->EnableWindow (TRUE);
closeButton->EnableWindow (TRUE);
}
void TestRunnerDlg::beRunDisabled ()
{
CButton *runButton = (CButton *)GetDlgItem (ID_RUN);
CButton *closeButton = (CButton *)GetDlgItem (IDOK);
CButton *stopButton = (CButton *)GetDlgItem (ID_STOP);
runButton->EnableWindow (FALSE);
stopButton->EnableWindow (FALSE);
closeButton->EnableWindow (TRUE);
}
void TestRunnerDlg::freeState ()
{
delete _activeTest;
delete _result;
}
void TestRunnerDlg::reset ()
{
_testsRun = 0;
_errors = 0;
_failures = 0;
_testEndTime = _testStartTime;
updateCountsDisplay ();
_activeTest = 0;
_result = 0;
CListCtrl *listCtrl = (CListCtrl *)GetDlgItem (IDC_LIST);
listCtrl->DeleteAllItems ();
_testsProgress->reset ();
}
void TestRunnerDlg::updateCountsDisplay ()
{
CStatic *statTestsRun = (CStatic *)GetDlgItem (IDC_STATIC_RUNS);
CStatic *statErrors = (CStatic *)GetDlgItem (IDC_STATIC_ERRORS);
CStatic *statFailures = (CStatic *)GetDlgItem (IDC_STATIC_FAILURES);
CEdit *editTime = (CEdit *)GetDlgItem (IDC_EDIT_TIME);
CString argumentString;
argumentString.Format ("%d", _testsRun);
statTestsRun ->SetWindowText (argumentString);
argumentString.Format ("%d", _errors);
statErrors ->SetWindowText (argumentString);
argumentString.Format ("%d", _failures);
statFailures ->SetWindowText (argumentString);
argumentString.Format ("Execution time: %3.3lf seconds", (_testEndTime - _testStartTime) / 1000.0);
editTime ->SetWindowText (argumentString);
}
void TestRunnerDlg::OnStop()
{
if (_result)
_result->stop ();
beIdle ();
}
void TestRunnerDlg::OnOK()
{
if (_result)
_result->stop ();
CDialog::OnOK ();
}
void TestRunnerDlg::OnSelchangeComboTest()
{
CComboBox *testsSelection = (CComboBox *)GetDlgItem (IDC_COMBO_TEST);
int currentSelection = testsSelection->GetCurSel ();
if (currentSelection >= 0 && currentSelection < _tests.size ())
{
_selectedTest = (_tests.begin () + currentSelection)->pTest;
beIdle ();
CWinApp* pApp = AfxGetApp();
pApp->WriteProfileString("Tests", "lastTest", _selectedTest->toString().c_str());
}
else
{
_selectedTest = 0;
beRunDisabled ();
}
freeState ();
reset ();
}
void TestRunnerDlg::OnBnClickedAutorun()
{
CButton *autoRunBtn = (CButton *)GetDlgItem (IDC_CHK_AUTORUN);
CWinApp* pApp = AfxGetApp();
pApp->WriteProfileInt("Tests", "autoRun", autoRunBtn->GetCheck());
}
void TestRunnerDlg::OnPaint()
{
CPaintDC dc (this);
_testsProgress->paint (dc);
}
void TestRunnerDlg::setTests(const std::vector<Test*>& tests)
{
_tests.clear();
for (std::vector<Test*>::const_iterator it = tests.begin(); it != tests.end(); ++it)
{
addTest(*it, 0);
}
}
void TestRunnerDlg::addTest(Test* pTest, int level)
{
TestInfo ti;
ti.pTest = pTest;
ti.level = level;
_tests.push_back(ti);
TestSuite* pSuite = dynamic_cast<TestSuite*>(pTest);
if (pSuite)
{
const std::vector<Test*>& tests = pSuite->tests();
for (std::vector<Test*>::const_iterator it = tests.begin(); it != tests.end(); ++it)
{
addTest(*it, level + 1);
}
}
}
CppUnit_END

View File

@ -0,0 +1,103 @@
//
// TestRunnerDlg.h
//
// $Id: //poco/1.1.0/CppUnit/WinTestRunner/src/TestRunnerDlg.h#1 $
//
#ifndef TestRunnerDlg_INCLUDED
#define TestRunnerDlg_INCLUDED
#ifndef CppUnit_CppUnit_INCLUDED
#include "CppUnit/CppUnit.h"
#endif
#ifndef CppUnit_CppUnitException_INCLUDED
#include "CppUnit/CppUnitException.h"
#endif
#ifndef ActiveTest_INCLUDED
#include "ActiveTest.h"
#endif
#ifndef STD_VECTOR_INCLUDED
#include <vector>
#define STD_VECTOR_INCLUDED
#endif
#ifndef IDD_DIALOG_TESTRUNNER
#include "../res/Resource.h"
#endif
#include <afxwin.h>
#include "afxwin.h"
CppUnit_BEGIN
class ProgressBar;
class TestRunnerDlg: public CDialog
{
public:
TestRunnerDlg(CWnd* pParent = NULL);
~TestRunnerDlg();
void setTests(const std::vector<Test*>& tests);
void addError(TestResult* result, Test* test, CppUnitException* e);
void addFailure(TestResult* result, Test* test, CppUnitException* e);
void endTest(TestResult* result, Test* test);
//{{AFX_DATA(TestRunnerDlg)
enum { IDD = IDD_DIALOG_TESTRUNNER };
// NOTE: the ClassWizard will add data members here
//}}AFX_DATA
//{{AFX_VIRTUAL(TestRunnerDlg)
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
//}}AFX_VIRTUAL
protected:
//{{AFX_MSG(TestRunnerDlg)
virtual BOOL OnInitDialog();
afx_msg void OnRun();
afx_msg void OnStop();
virtual void OnOK();
afx_msg void OnSelchangeComboTest();
afx_msg void OnBnClickedAutorun();
afx_msg void OnPaint();
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
void addListEntry(const std::string& type, TestResult* result, Test* test, CppUnitException* e);
void beIdle();
void beRunning();
void beRunDisabled();
void reset();
void freeState();
void updateCountsDisplay();
void addTest(Test* pTest, int level);
struct TestInfo
{
Test* pTest;
int level;
};
std::vector<TestInfo> _tests;
ProgressBar* _testsProgress;
Test* _selectedTest;
ActiveTest* _activeTest;
TestResult* _result;
int _testsRun;
int _errors;
int _failures;
DWORD _testStartTime;
DWORD _testEndTime;
};
CppUnit_END
#endif // TestRunnerDlg_INCLUDED

View File

@ -0,0 +1,64 @@
//
// WinTestRunner.cpp
//
// $Id: //poco/1.1.0/CppUnit/WinTestRunner/src/WinTestRunner.cpp#1 $
//
#include "WinTestRunner/WinTestRunner.h"
#include "TestRunnerDlg.h"
CppUnit_BEGIN
WinTestRunner::WinTestRunner()
{
}
WinTestRunner::~WinTestRunner()
{
for (std::vector<Test*>::iterator it = _tests.begin(); it != _tests.end(); ++it)
delete *it;
}
void WinTestRunner::run()
{
TestRunnerDlg dlg;
dlg.setTests(_tests);
dlg.DoModal();
}
void WinTestRunner::addTest(Test* pTest)
{
_tests.push_back(pTest);
}
BEGIN_MESSAGE_MAP(WinTestRunnerApp, CWinApp)
END_MESSAGE_MAP()
BOOL WinTestRunnerApp::InitInstance()
{
AllocConsole();
SetConsoleTitle("CppUnit WinTestRunner Console");
freopen("CONOUT$", "w", stdout);
freopen("CONOUT$", "w", stderr);
freopen("CONIN$", "r", stdin);
TestMain();
FreeConsole();
return FALSE;
}
void WinTestRunnerApp::TestMain()
{
}
CppUnit_END

14
CppUnit/cppunit.vmsbuild Normal file
View File

@ -0,0 +1,14 @@
#
# buildfiles.vms
#
# $Id: //poco/CppUnit/cppunit.vmsbuild#1 $
#
LIB=CppUnit
CppUnitException
TestCase
TestDecorator
TestFailure
TestResult
TestRunner
TestSuite
TextTestResult

75
CppUnit/doc/README.html Normal file
View File

@ -0,0 +1,75 @@
<HTML>
<HEAD>
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=windows-1252">
<META NAME="Generator" CONTENT="Microsoft Word 97">
<TITLE>CppUnit 1.5</TITLE>
<META NAME="Template" CONTENT="C:\Program Files\MSOffice\Office\html.dot">
</HEAD>
<BODY LINK="#0000ff" VLINK="#800080">
<P><!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN"></P>
<H1>CppUnit 1.5</H1>
<P>Last Revision: 12/15/99 - Michael Feathers (mfeathers@acm.org) - written in standard C++, tested under Microsoft Visual C++ 6.0</P>
<P><HR></P>
<H3>Background</H3>
<P>CppUnit is a simple unit test framework for C++. It is a port from JUnit, a testing framework for Java, developed by Kent Beck and Erich Gamma. </P>
<H3>Contents</H3>
<PRE>README.html&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; this file
&nbsp;&nbsp;&nbsp;
&nbsp;&nbsp;&nbsp; test&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; the source code
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; framework&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; the testing framework
&#9;&#9;extensions&#9;some framework extension classes
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; textui&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; a command line interface to run tests
&nbsp;&nbsp;&nbsp;&nbsp;ms&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; code for a Microsoft specific TestRunner
&nbsp;&nbsp;&nbsp;&nbsp;samples&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; some example test cases and extensions to the framework
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; multicaster&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; a sample illustrating a publish/subscribe
&#9;&#9;&#9;&#9;multicaster under test
&nbsp;&nbsp;&nbsp; doc&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; documentation</PRE>
<H3>Installation</H3>
<P>To use the test framework, create a makefile or load all files in test\framework into your IDE. In this incarnation of CppUnit, all includes assume the current directory first. A makefile or project can be used to resolve the dependencies. </P>
<P>The directory test\textui contains a simple command line example that uses the framework.</P>
<H3>Documentation</H3>
<P>CppUnit comes with the following documentation: </P>
<UL>
<LI>a cookbook: doc\cookbook.htm </LI>
<LI>this file </LI></UL>
<H3>Samples</H3>
<P>You can find several sample test cases in the samples directory: </P>
<UL>
<LI>ExampleTestCase - some simple tests </LI>
<LI>Multicaster - test cases for a sample publish/subscribe multicaster class </LI></UL>
<P>Also, the wiki page <a HREF="http://c2.com/cgi/wiki?ClassHierarchyTestingInCppUnit">http://c2.com/cgi/wiki?ClassHierarchyTestingInCppUnit</a> shows how to automatically apply tests of classes to the classes' subclasses.</P>
<H3>Extensions</H3>
<P>You can find several classes that illustrate framework extensions in the extensions directory: </P>
<UL>
<LI>TestDecorator - A Decorator for Test. You can use it as the base class for decorators that extend test cases. </LI>
<LI>TestSetup - A Decorator that can be used to set up and tear down additional fixture state. Subclass TestSetup and insert it into your tests when you want to set up additional state once before the test is run. </LI>
<LI>Orthodox - a template class which can be used to verify operations on an arbitrary class.</LI></UL>
<H3>Notes</H3>
<P>Porting this framework has been fun. I've tried to maintain the spirit and utility of JUnit in a C++ environment. Naturally, the move from Java to standard C++ forces out several nice JUnit features:</P>
<OL>
<LI>Platform independent GUI.</LI>
<LI>Stack traces of test failures</LI>
<LI>Active (threaded) tests</LI>
<LI>Direct invocation of test cases via reflection</LI>
<LI>Run-time loading of new tests</LI></OL>
<P>In addition, the lack of garbage collection in C++ requires some careful use of the framework classes. In particular, TestSuites are composites that manage the lifetime of any tests added to them. Holding onto a TestResult past the lifetime of the tests which filled it is a bad idea. This is because TestResults hold TestFailures and TestFailures hold pointers to the Tests that generated them.</P>
<P>On the plus side, we can use the C++ macro preprocessor to get the exact line at which a failure occurs, along with the actual text inside the assert () call that detected the failure. The features of C++ that enable this are the __LINE__ and __FILE__ preprocessor definitions, along with the <I>stringizing</I> operator. If you find that generating this much literal text bulks up your test executables, you can use the CPP_UNIT_SOURCEANNOT define to disable that portion of the reporting.</P>
<P>Note: If you use the C++ macro "assert ()" in your code, or include assert.h, you may have a name clash with CppUnit's assert macro. This can be remedied by changing the name of the macro to "cu_assert ()" in TestCase.h.</P>
<P>I'd like to thank Kent Beck and Erich Gamma for the inspiration, design, and a wonderful cookbook that was easily/shamelessly mutated to describe CppUnit. Double thanks to Erich for thinking up a way to implement TestCaller. Additional thanks to Kent, Ward Cunningham, Ron Jeffries, Martin Fowler, and several other netizens of the WikiWikiWeb. I don't think any other bunch of people could have convinced me that rapid development with unit tests can be both effective and easy.</P>
<P>Thanks also to Fred Huls for mentioning the idea of template-based testing. The <EM>orthodox</EM> template class demonstrates only a small part of what can be done with templated test cases.</P>
<H3>History Of Changes</H3>
<P>1.2 -- Added the TestCaller template class. There is now no need to use the CPP_UNIT_TESTCASEDISPATCH macro unless you are using a C++ compiler which does not support templates well. CPP_UNIT_TESTCASEDISPATCH remains in TestCase.h for backward compatibility. I've also kept the use of the macro in the Multicaster sample to leave in an example.</P>
<P>1.3 -- Retired the CPP_UNIT_TESTCASEDISPATCH macro and cleaned up the include structure. Fixed bug in the textui version.</P>
<P>1.4 -- Removed using directives for std in CppUnit headers. Merged the old AssertionFailedError into CppUnitException. Fixed a memory leak in the TestRunner class of the MS GUI TestRunner. Removed CppUnit.h file. Now headers for each class must be included directly.</P></BODY></HTML>
<P>1.5 -- Upgraded projects from VC++ 5.0 to 6.0.</P></BODY></HTML>

164
CppUnit/doc/cookbook.htm Normal file
View File

@ -0,0 +1,164 @@
<HTML>
<HEAD>
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=windows-1252">
<META NAME="Generator" CONTENT="Microsoft Word 97">
<TITLE>CppUnit Cookbook</TITLE>
<META NAME="Template" CONTENT="C:\Program Files\MSOffice\Office\html.dot">
</HEAD>
<BODY LINK="#0000ff" VLINK="#800080">
<P><!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN"></P>
<H1>CppUnit Cookbook</H1>
<P>Here is a short cookbook to help you get started. </P>
<H2>Simple Test Case</H2>
<P>You want to know whether your code is working. How do you do it? There are many ways. Stepping through a debugger or littering your code with stream output calls are two of the simpler ways, but they both have drawbacks. Stepping through your code is a good idea, but it is not automatic. You have to do it every time you make changes. Streaming out text is also fine, but it makes code ugly and it generates far more information than you need most of the time.</P>
<P>Tests in CppUnit can be run automatically. They are easy to set up and once you have written them, they are always there to help you keep confidence in the quality of your code.</P>
<P>To make a simple test, here is what you do:</P>
<P>Subclass the TestCase class. Override the method "runTest ()". When you want to check a value, call "assert (bool)" and pass in an expression that is true if the test succeeds. </P>
<P>For example, to test the equality comparison for a Complex number class, write:</P>
<TT><PRE>&#9;class ComplexNumberTest : public TestCase {&nbsp;
&#9;public:
ComplexNumberTest (string name) : TestCase (name) {}
void runTest () {
assert (Complex (10, 1) == Complex (10, 1));
assert (!(Complex (1, 1) == Complex (2, 2)));
}
};</PRE>
</TT><P>That was a very simple test. Ordinarily, you'll have many little test cases that you'll want to run on the same set of objects. To do this, use a fixture.</P>
<P>&nbsp;</P>
<H2>Fixture</H2>
<P>A fixture is a known set of objects that serves as a base for a set of test cases. Fixtures come in very handy when you are testing as you develop. Let's try out this style of development and learn about fixtures along the away. Suppose that we are really developing a complex number class. Let's start by defining a empty class named Complex.</P>
<TT><PRE>&#9;class Complex {};&nbsp;</PRE>
</TT><P>Now create an instance of ComplexNumberTest above, compile the code and see what happens. The first thing we notice is a few compiler errors. The test uses operator==, but it is not defined. Let's fix that.</P>
<TT><PRE>&#9;bool operator== (const Complex&amp; a, const Complex&amp; b) { return true; }</PRE>
</TT><P>Now compile the test, and run it. This time it compiles but the test fails. We need a bit more to get an operator== working correctly, so we revisit the code.</P>
<TT><PRE>&#9;class Complex {&nbsp;
friend bool operator== (const Complex&amp; a, const Complex&amp; b);
double real, imaginary;
public:
Complex () {
real = imaginary = 0.0;
}
};
bool operator== (const Complex&amp; a, const Complex&amp; b)
{ return eq(a.real,b.real) &amp;&amp; eq(a.imaginary,b.imaginary); }</PRE>
</TT><P>If we compile now and run our test it will pass. </P>
<P>Now we are ready to add new operations and new tests. At this point a fixture would be handy. We would probably be better off when doing our tests if we decided to instantiate three or four complex numbers and reuse them across our tests. </P>
<P>Here is how we do it:</P>
<OL>
<LI>Add member variables for each part of the fixture </LI>
<LI>Override "setUp ()" to initialize the variables </LI>
<LI>Override "tearDown ()" to release any permanent resources you allocated in "setUp ()"</LI></OL>
<TT><PRE>&#9;class ComplexNumberTest : public TestCase {
&#9;private:
Complex &#9;*m_10_1, *m_1_1; *m_11_2;
&#9;protected:
&#9;void&#9;&#9;setUp () {
&#9;&#9;&#9; m_10_1 = new Complex (10, 1);
&#9;&#9;&#9; m_1_1 = new Complex (1, 1);
&#9;&#9;&#9; m_11_2 = new Complex (11, 2);
}
&#9;void&#9;&#9;tearDown () {
&#9;&#9;&#9; delete m_10_1, delete m_1_1, delete m_11_2;
&#9;&#9;&#9;}
&#9;};</PRE>
</TT><P>Once we have this fixture, we can add the complex addition test case any any others that we need over the course of our development.</P>
<P>&nbsp;</P>
<H2>Test Case</H2>
<P>How do you write and invoke individual tests using a fixture? </P>
<P>There are two steps to this process:</P>
<OL>
<LI>Write the test case as a method in the fixture class</LI>
<LI>Create a TestCaller which runs that particular method</LI></OL>
<P>Here is our test case class with a few extra case methods:</P>
<TT><PRE>&#9;class ComplexNumberTest : public TestCase {
&#9;private:
Complex &#9;*m_10_1, *m_1_1; *m_11_2;
&#9;protected:
&#9;void&#9;&#9;setUp () {
&#9;&#9;&#9; m_10_1 = new Complex (10, 1);
&#9;&#9;&#9; m_1_1 = new Complex (1, 1);
&#9;&#9;&#9; m_11_2 = new Complex (11, 2);
}
&#9;void&#9;&#9;tearDown () {
&#9;&#9;&#9; delete m_10_1, delete m_1_1, delete m_11_2;
&#9;&#9;&#9;}
&#9;void&#9;&#9;testEquality () {
&#9;&#9;&#9; assert (*m_10_1 == *m_10_1);
&#9;&#9;&#9; assert (!(*m_10_1 == *m_11_2));
&#9;&#9;&#9;}
&#9;void&#9;&#9;testAddition () {
&#9;&#9;&#9; assert (*m_10_1 + *m_1_1 == *m_11_2);
&#9;}
&#9;};</PRE>
</TT><P>Create and run instances for each test case like this:</P>
<TT><PRE>&#9;test = new TestCaller&lt;ComplexNumberTest&gt;("testEquality", ComplexNumberTest::testEquality);
test->run (); </PRE>
</TT><P>The second argument to the test caller constructor is the address of a method on ComplexNumberTest. When the test caller is run, that specific method will be run.</P>
<P>Once you have several tests, organize them into a suite.</P>
<P>&nbsp;</P>
<H2>Suite</H2>
<P>How do you set up your tests so that you can run them all at once?<BR>
<BR>
CppUnit provides a TestSuite class that runs any number of TestCases together. For example, to run a single test case, you execute:</P>
<TT><PRE>&#9;TestResult result;
&#9;TestCaller&lt;ComplexNumberTest&gt; test ("testAddition", ComplexNumberTest::testAddition);
&#9;Test.run (&amp;result);</PRE>
</TT><P>&nbsp;</P>
<P>To create a suite of two or more tests, you do the following:</P>
<TT><PRE>&#9;TestSuite suite;
&#9;TestResult result;
&#9;suite.addTest (new TestCaller&lt;ComplexNumberTest&gt;("testEquality", ComplexNumberTest::testEquality));
&#9;suite.addTest (new TestCaller&lt;ComplexNumberTest&gt;("testAddition", ComplexNumberTest::testAddition));
&#9;suite.run (&amp;result);
</PRE>
</TT><P>TestSuites don't only have to contain callers for TestCases. They can contain any object that implements the Test interface. For example, you can create a TestSuite in your code and I can create one in mine, and we can run them together by creating a TestSuite that contains both: </P>
<TT><PRE>&#9;TestSuite suite;
&#9;suite.addTest (ComplexNumberTest.suite ());
&#9;suite.addTest (SurrealNumberTest.suite ());
&#9;suite.run (&amp;result);</PRE>
</TT><P>&nbsp;</P>
<H2>TestRunner</H2>
<P>How do you run your tests and collect their results? </P>
<P>Once you have a test suite, you'll want to run it. CppUnit provides tools to define the suite to be run and to display its results. You make your suite accessible to a TestRunner program with a static method <I>suite</I> that returns a test suite. <BR>
For example, to make a ComplexNumberTest suite available to a TestRunner, add the following code to ComplexNumberTest: </P>
<TT><PRE>&#9;public: static Test *suite () {
&#9; TestSuite *suiteOfTests = new TestSuite;
&#9; suiteOfTests-&gt;addTest (new TestCaller&lt;ComplexNumberTest&gt;("testEquality", testEquality));
&#9; suiteOfTests-&gt;addTest (new TestCaller&lt;ComplexNumberTest&gt;("testAddition", testAddition));
return suiteOfTests;
&#9;}</PRE>
</TT><P>CppUnit provides both a textual version of a TestRunner tool, and a Micosoft Visual C++ 5.0 graphical version. If you are running on another platform, take a look at the graphical version. It is easy to port.</P>
<P>To use the text version, include the header file for the test in TestRunner.cpp:</P>
<TT><PRE>&#9;#include "ExampleTestCase.h"
&#9;#include "ComplexNumberTest.h"</PRE>
</TT><P>And add a call to "addTest (string, Test *) in the "main ()" function:</P>
<TT><PRE>&#9;int main (int ac, char **av) {
&#9; TestRunner runner;
&#9; runner.addTest (ExampleTestCase::suite ());
&#9; runner.addTest (ComplexNumberTest::suite ());
&#9; runner.run ();
&#9; return 0;
&#9;}</PRE>
</TT><P>The TestRunner will run the tests. If all the tests pass, you'll get an informative message. If any fail, you'll get the following information:</P>
<OL>
<LI>The name of the test case that failed</LI>
<LI>The name of the source file that contains the test</LI>
<LI>The line number where the failure occurred</LI>
<LI>All of the text inside the call to assert which detected the failure</LI></OL>
<P>CppUnit distinguishes between <I>failures</I> and <I>errors</I>. A failure is anticipated and checked for with assertions. Errors are unanticipated problems like division by zero and other exceptions thrown by the C++ runtime or your code.</P>
<P>If you are running MS Developer's Studio, you can build the GUI version rather easily. There are three projects: culib, TestRunner, and HostApp. They make a static library for the framework, a dialog based TestRunner in a DLL and an example Hosting application, respectively. To incorporate a TestRunner in an application you are developing, link with the static library and the TestRunner DLL. Note that the TestRunner DLL must be in the home directory of your application, the system directory or the path. In your application, create an instance of TestRunnerDlg whenever you want to run tests. Pass tests you want to run to the dialog object and then execute.</P>
<P>Here is a screen shot of the TestRunner in use:</P>
<P><IMG SRC="test.gif" WIDTH=574 HEIGHT=351></P>
<P>&nbsp;</P>
<P>More notes about the implementation of CppUnit can be found in README.HTML.</P>
<P>&nbsp;</P>
<P>&nbsp;</P></BODY>
</HTML>

15
CppUnit/doc/license.htm Normal file
View File

@ -0,0 +1,15 @@
<HTML>
<HEAD>
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=windows-1252">
<META NAME="Generator" CONTENT="Microsoft Word 97">
<TITLE>License Agreement</TITLE>
<META NAME="Template" CONTENT="C:\Program Files\MSOffice\Office\html.dot">
</HEAD>
<BODY LINK="#0000ff" VLINK="#800080">
<P>Permission to reproduce and create derivative works from the Software ("Software Derivative Works") is hereby granted to you under the copyright of Michael Feathers.&nbsp; Michael Feathers also grants you the right to distribute the Software and Software Derivative Works. </P>
<P>Michael Feathers licenses the Software to you on an "AS IS" basis, without warranty of any kind. Michael Feathers HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES OR CONDITIONS, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OR CONDITIONS OF MERCHANTABILITY, NON INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE.&nbsp; You are solely responsible for determining the appropriateness of using the Software and assume all risks associated with the use and distribution of this Software, including but not limited to the risks of program errors, damage to or loss of data, programs or equipment, and unavailability or interruption of operations.&nbsp; MICHAEL FEATHERS WILL NOT BE LIABLE FOR ANY DIRECT DAMAGES OR FOR ANY SPECIAL, INCIDENTAL, OR INDIRECT DAMAGES OR FOR ANY ECONOMIC CONSEQUENTIAL DAMAGES (INCLUDING LOST PROFITS OR SAVINGS), EVEN IF MICHAEL FEATHERS HAD BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.&nbsp; Michael Feathers will not be liable for the loss of, or damage to, your records or data, or any damages claimed by you based on a third party claim. </P>
<P>You agree to distribute the Software and any Software Derivatives under a license agreement that: 1) is sufficient to notify all licensees of the Software and Software Derivatives that Michael Feathers assumes no liability for any claim that may arise regarding the Software or Software Derivatives, and 2) that disclaims all warranties, both express and implied, from Michael Feathers regarding the Software and Software Derivatives.&nbsp; (If you include this Agreement with any distribution of the Software and Software Derivatives you will have meet this requirement).&nbsp; You agree that you will not delete any copyright notices in the Software. </P>
<P>This Agreement is the exclusive statement of your rights in the Software as provided by Michael Feathers.&nbsp; Except for the licenses granted to you in the second paragraph above, no other licenses are granted hereunder, by estoppel, implication or otherwise. <BR>
&nbsp; </P></BODY>
</HTML>

BIN
CppUnit/doc/test.gif Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

View File

@ -0,0 +1,63 @@
//
// CppUnit.h
//
// $Id: //poco/1.1.0/CppUnit/include/CppUnit/CppUnit.h#1 $
//
#ifndef CppUnit_CppUnit_INCLUDED
#define CppUnit_CppUnit_INCLUDED
//
// Ensure that POCO_DLL is default unless POCO_STATIC is defined
//
#if defined(_WIN32) && defined(_DLL)
#if !defined(POCO_DLL) && !defined(POCO_STATIC)
#define POCO_DLL
#endif
#endif
//
// The following block is the standard way of creating macros which make exporting
// from a DLL simpler. All files within this DLL are compiled with the CppUnit_EXPORTS
// symbol defined on the command line. this symbol should not be defined on any project
// that uses this DLL. This way any other project whose source files include this file see
// CppUnit_API functions as being imported from a DLL, wheras this DLL sees symbols
// defined with this macro as being exported.
//
#if (defined(_WIN32) || defined(__CYGWIN__)) && defined(POCO_DLL)
#if defined(CppUnit_EXPORTS)
#define CppUnit_API __declspec(dllexport)
#else
#define CppUnit_API __declspec(dllimport)
#endif
#endif
#if !defined(CppUnit_API)
#define CppUnit_API
#endif
//
// Macros to declare the namespace
//
#define CppUnit_BEGIN namespace CppUnit {
#define CppUnit_END }
// Turn off some annoying warnings
#ifdef _MSC_VER
#pragma warning(disable:4786) // identifier truncation warning
#pragma warning(disable:4503) // decorated name length exceeded - mainly a problem with STLPort
#pragma warning(disable:4018) // signed/unsigned comparison
#pragma warning(disable:4284) // return type for operator -> is not UDT
#pragma warning(disable:4251) // ... needs to have dll-interface warning
#pragma warning(disable:4273)
#pragma warning(disable:4275) // ... non dll-interface class used as base for dll-interface class
#endif
#endif // CppUnit_CppUnit_INCLUDED

View File

@ -0,0 +1,110 @@
//
// CppUnitException.h
//
// $Id: //poco/1.1.0/CppUnit/include/CppUnit/CppUnitException.h#1 $
//
#ifndef CppUnit_CppUnitException_INCLUDED
#define CppUnit_CppUnitException_INCLUDED
#ifndef CppUnit_CppUnit_INCLUDED
#include "CppUnit/CppUnit.h"
#endif
#ifndef STD_EXCEPTION_INCLUDED
#include <exception>
#define STD_EXCEPTION_INCLUDED
#endif
#ifndef STD_STRING_INCLUDED
#include <string>
#define STD_STRING_INCLUDED
#endif
CppUnit_BEGIN
class CppUnit_API CppUnitException: public std::exception
/// CppUnitException is an exception that serves
/// descriptive strings through its what() method
{
public:
CppUnitException(const std::string& message = "",
long lineNumber = CPPUNIT_UNKNOWNLINENUMBER,
const std::string& fileName = CPPUNIT_UNKNOWNFILENAME);
CppUnitException(const CppUnitException& other);
virtual ~CppUnitException() throw();
CppUnitException& operator = (const CppUnitException& other);
const char* what() const throw ();
long lineNumber() const;
const std::string& fileName() const;
static const std::string CPPUNIT_UNKNOWNFILENAME;
static const int CPPUNIT_UNKNOWNLINENUMBER;
private:
std::string _message;
long _lineNumber;
std::string _fileName;
};
inline CppUnitException::CppUnitException(const CppUnitException& other): exception (other)
{
_message = other._message;
_lineNumber = other._lineNumber;
_fileName = other._fileName;
}
inline CppUnitException::CppUnitException (const std::string& message, long lineNumber, const std::string& fileName): _message(message), _lineNumber(lineNumber), _fileName(fileName)
{
}
inline CppUnitException::~CppUnitException () throw()
{
}
inline CppUnitException& CppUnitException::operator = (const CppUnitException& other)
{
exception::operator= (other);
if (&other != this)
{
_message = other._message;
_lineNumber = other._lineNumber;
_fileName = other._fileName;
}
return *this;
}
inline const char* CppUnitException::what() const throw ()
{
return _message.c_str();
}
inline long CppUnitException::lineNumber() const
{
return _lineNumber;
}
// The file in which the error occurred
inline const std::string& CppUnitException::fileName() const
{
return _fileName;
}
CppUnit_END
#endif // CppUnit_CppUnitException_INCLUDED

View File

@ -0,0 +1,19 @@
//
// Guards.h
//
// $Id: //poco/1.1.0/CppUnit/include/CppUnit/Guards.h#1 $
//
#ifndef CppUnit_Guards_INCLUDED
#define CppUnit_Guards_INCLUDED
// Prevent copy construction and assignment for a class
#define REFERENCEOBJECT(className) \
private: \
className(const className& other); \
className& operator = (const className& other);
#endif // CppUnit_Guards_INCLUDED

View File

@ -0,0 +1,109 @@
//
// Orthodox.h
//
// $Id: //poco/1.1.0/CppUnit/include/CppUnit/Orthodox.h#1 $
//
#ifndef CppUnit_Orthodox_INCLUDED
#define CppUnit_Orthodox_INCLUDED
#ifndef CppUnit_CppUnit_INCLUDED
#include "CppUnit/CppUnit.h"
#endif
#ifndef CppUnit_TestCase_INCLUDED
#include "CppUnit/TestCase.h"
#endif
CppUnit_BEGIN
/*
* Orthodox performs a simple set of tests on an arbitary
* class to make sure that it supports at least the
* following operations:
*
* default construction - constructor
* equality/inequality - operator== && operator!=
* assignment - operator=
* negation - operator!
* safe passage - copy construction
*
* If operations for each of these are not declared
* the template will not instantiate. If it does
* instantiate, tests are performed to make sure
* that the operations have correct semantics.
*
* Adding an orthodox test to a suite is very
* easy:
*
* public: Test *suite () {
* TestSuite *suiteOfTests = new TestSuite;
* suiteOfTests->addTest (new ComplexNumberTest ("testAdd");
* suiteOfTests->addTest (new TestCaller<Orthodox<Complex> > ());
* return suiteOfTests;
* }
*
* Templated test cases be very useful when you are want to
* make sure that a group of classes have the same form.
*
* see TestSuite
*/
template <class ClassUnderTest>
class Orthodox: public TestCase
{
public:
Orthodox(): TestCase("Orthodox")
{
}
protected:
ClassUnderTest call(ClassUnderTest object);
void runTest ();
};
// Run an orthodoxy test
template <class ClassUnderTest>
void Orthodox<ClassUnderTest>::runTest()
{
// make sure we have a default constructor
ClassUnderTest a, b, c;
// make sure we have an equality operator
assert (a == b);
// check the inverse
b.operator= (a.operator! ());
assert (a != b);
// double inversion
b = !!a;
assert (a == b);
// invert again
b = !a;
// check calls
c = a;
assert (c == call (a));
c = b;
assert (c == call (b));
}
// Exercise a call
template <class ClassUnderTest>
ClassUnderTest Orthodox<ClassUnderTest>::call(ClassUnderTest object)
{
return object;
}
CppUnit_END
#endif // CppUnit_Orthodox_INCLUDED

View File

@ -0,0 +1,83 @@
//
// RepeatedTest.h
//
// $Id: //poco/1.1.0/CppUnit/include/CppUnit/RepeatedTest.h#1 $
//
#ifndef CppUnit_RepeatedTest_INCLUDED
#define CppUnit_RepeatedTest_INCLUDED
#ifndef CppUnit_CppUnit_INCLUDED
#include "CppUnit/CppUnit.h"
#endif
#ifndef CppUnit_Guards_INCLUDED
#include "CppUnit/Guards.h"
#endif
#ifndef CppUnit_TestDecorator_INCLUDED
#include "CppUnit/TestDecorator.h"
#endif
CppUnit_BEGIN
class Test;
class TestResult;
/*
* A decorator that runs a test repeatedly.
* Does not assume ownership of the test it decorates
*
*/
class CppUnit_API RepeatedTest: public TestDecorator
{
REFERENCEOBJECT (RepeatedTest)
public:
RepeatedTest(Test* test, int timesRepeat): TestDecorator (test), _timesRepeat (timesRepeat)
{
}
int countTestCases();
std::string toString();
void run(TestResult *result);
private:
const int _timesRepeat;
};
// Counts the number of test cases that will be run by this test.
inline RepeatedTest::countTestCases ()
{
return TestDecorator::countTestCases () * _timesRepeat;
}
// Returns the name of the test instance.
inline std::string RepeatedTest::toString()
{
return TestDecorator::toString () + " (repeated)";
}
// Runs a repeated test
inline void RepeatedTest::run(TestResult *result)
{
for (int n = 0; n < _timesRepeat; n++)
{
if (result->shouldStop())
break;
TestDecorator::run(result);
}
}
CppUnit_END
#endif // CppUnit_RepeatedTest_INCLUDED

View File

@ -0,0 +1,70 @@
//
// Test.h
//
// $Id: //poco/1.1.0/CppUnit/include/CppUnit/Test.h#1 $
//
#ifndef CppUnit_Test_INCLUDED
#define CppUnit_Test_INCLUDED
#ifndef CppUnit_CppUnit_INCLUDED
#include "CppUnit/CppUnit.h"
#endif
#ifndef STD_STRING_INCLUDED
#include <string>
#define STD_STRING_INCLUDED
#endif
CppUnit_BEGIN
class TestResult;
/*
* A Test can be run and collect its results.
* See TestResult.
*
*/
class CppUnit_API Test
{
public:
virtual ~Test() = 0;
virtual void run(TestResult* result) = 0;
virtual int countTestCases() = 0;
virtual std::string toString() = 0;
};
inline Test::~Test()
{
}
// Runs a test and collects its result in a TestResult instance.
inline void Test::run(TestResult *result)
{
}
// Counts the number of test cases that will be run by this test.
inline int Test::countTestCases()
{
return 0;
}
// Returns the name of the test instance.
inline std::string Test::toString()
{
return "";
}
CppUnit_END
#endif // CppUnit_Test_INCLUDED

View File

@ -0,0 +1,101 @@
//
// TestCaller.h
//
// $Id: //poco/1.1.0/CppUnit/include/CppUnit/TestCaller.h#1 $
//
#ifndef CppUnit_TestCaller_INCLUDED
#define CppUnit_TestCaller_INCLUDED
#ifndef CppUnit_CppUnit_INCLUDED
#include "CppUnit/CppUnit.h"
#endif
#ifndef CppUnit_Guards_INCLUDED
#include "Guards.h"
#endif
#ifndef CppUnit_TestCase_INCLUDED
#include "TestCase.h"
#endif
#ifndef STD_MEMORY_INCLUDED
#include <memory>
#define STD_MEMORY_INCLUDED
#endif
CppUnit_BEGIN
/*
* A test caller provides access to a test case method
* on a test case class. Test callers are useful when
* you want to run an individual test or add it to a
* suite.
*
* Here is an example:
*
* class MathTest : public TestCase {
* ...
* public:
* void setUp ();
* void tearDown ();
*
* void testAdd ();
* void testSubtract ();
* };
*
* Test *MathTest::suite () {
* TestSuite *suite = new TestSuite;
*
* suite->addTest (new TestCaller<MathTest> ("testAdd", testAdd));
* return suite;
* }
*
* You can use a TestCaller to bind any test method on a TestCase
* class, as long as it returns accepts void and returns void.
*
* See TestCase
*/
template <class Fixture>
class TestCaller: public TestCase
{
REFERENCEOBJECT (TestCaller)
typedef void (Fixture::*TestMethod)();
public:
TestCaller(const std::string& name, TestMethod test): TestCase(name), _fixture(new Fixture(name)), _test(test)
{
}
protected:
void runTest()
{
(_fixture.get()->*_test)();
}
void setUp()
{
_fixture.get()->setUp();
}
void tearDown()
{
_fixture.get()->tearDown();
}
private:
TestMethod _test;
std::auto_ptr<Fixture> _fixture;
};
CppUnit_END
#define CppUnit_addTest(suite, cls, mth) \
suite->addTest(new CppUnit::TestCaller<cls>(#mth, &cls::mth))
#endif // CppUnit_TestCaller_INCLUDED

View File

@ -0,0 +1,244 @@
//
// TestCase.h
//
// $Id: //poco/1.1.0/CppUnit/include/CppUnit/TestCase.h#1 $
//
#ifndef CppUnit_TestCase_INCLUDED
#define CppUnit_TestCase_INCLUDED
#ifndef CppUnit_CppUnit_INCLUDED
#include "CppUnit/CppUnit.h"
#endif
#ifndef CppUnit_Guards_INCLUDED
#include "CppUnit/Guards.h"
#endif
#ifndef CppUnit_Test_INCLUDED
#include "CppUnit/Test.h"
#endif
#ifndef CppUnit_CppUnitException_INCLUDED
#include "CppUnit/CppUnitException.h"
#endif
#ifndef STD_STRING_INCLUDED
#include <string>
#define STD_STRING_INCLUDED
#endif
#ifndef STD_TYPEINFO_INCLUDED
#include <typeinfo>
#define STD_TYPEINFO_INCLUDED
#endif
CppUnit_BEGIN
class TestResult;
/*
* A test case defines the fixture to run multiple tests. To define a test case
* 1) implement a subclass of TestCase
* 2) define instance variables that store the state of the fixture
* 3) initialize the fixture state by overriding setUp
* 4) clean-up after a test by overriding tearDown.
*
* Each test runs in its own fixture so there
* can be no side effects among test runs.
* Here is an example:
*
* class MathTest : public TestCase {
* protected: int m_value1;
* protected: int m_value2;
*
* public: MathTest (std::string name)
* : TestCase (name) {
* }
*
* protected: void setUp () {
* m_value1 = 2;
* m_value2 = 3;
* }
* }
*
*
* For each test implement a method which interacts
* with the fixture. Verify the expected results with assertions specified
* by calling assert on the expression you want to test:
*
* protected: void testAdd () {
* int result = value1 + value2;
* assert (result == 5);
* }
*
* Once the methods are defined you can run them. To do this, use
* a TestCaller.
*
* Test *test = new TestCaller<MathTest>("testAdd", MathTest::testAdd);
* test->run ();
*
*
* The tests to be run can be collected into a TestSuite. CppUnit provides
* different test runners which can run a test suite and collect the results.
* The test runners expect a static method suite as the entry
* point to get a test to run.
*
* public: static MathTest::suite () {
* TestSuite *suiteOfTests = new TestSuite;
* suiteOfTests->addTest(new TestCaller<MathTest>("testAdd", testAdd));
* suiteOfTests->addTest(new TestCaller<MathTest>("testDivideByZero", testDivideByZero));
* return suiteOfTests;
* }
*
* Note that the caller of suite assumes lifetime control
* for the returned suite.
*
* see TestResult, TestSuite and TestCaller
*
*/
class CppUnit_API TestCase: public Test
{
REFERENCEOBJECT (TestCase)
public:
TestCase(const std::string& Name);
~TestCase();
virtual void run(TestResult* result);
virtual TestResult* run();
virtual int countTestCases();
const std::string& name() const;
std::string toString();
virtual void setUp();
virtual void tearDown();
protected:
virtual void runTest();
TestResult* defaultResult();
void assertImplementation(bool condition,
const std::string& conditionExpression = "",
long lineNumber = CppUnitException::CPPUNIT_UNKNOWNLINENUMBER,
const std::string& fileName = CppUnitException::CPPUNIT_UNKNOWNFILENAME);
void assertEquals(long expected,
long actual,
long lineNumber = CppUnitException::CPPUNIT_UNKNOWNLINENUMBER,
const std::string& fileName = CppUnitException::CPPUNIT_UNKNOWNFILENAME);
void assertEquals(double expected,
double actual,
double delta,
long lineNumber = CppUnitException::CPPUNIT_UNKNOWNLINENUMBER,
const std::string& fileName = CppUnitException::CPPUNIT_UNKNOWNFILENAME);
void assertEquals(const std::string& expected,
const std::string& actual,
long lineNumber = CppUnitException::CPPUNIT_UNKNOWNLINENUMBER,
const std::string& fileName = CppUnitException::CPPUNIT_UNKNOWNFILENAME);
void assertEquals(const void* expected,
const void* actual,
long lineNumber = CppUnitException::CPPUNIT_UNKNOWNLINENUMBER,
const std::string& fileName = CppUnitException::CPPUNIT_UNKNOWNFILENAME);
std::string notEqualsMessage(long expected, long actual);
std::string notEqualsMessage(double expected, double actual);
std::string notEqualsMessage(const void* expected, const void* actual);
std::string notEqualsMessage(const std::string& expected, const std::string& actual);
void assertNotNull(const void* pointer,
const std::string& pointerExpression = "",
long lineNumber = CppUnitException::CPPUNIT_UNKNOWNLINENUMBER,
const std::string& fileName = CppUnitException::CPPUNIT_UNKNOWNFILENAME);
void assertNull(const void* pointer,
const std::string& pointerExpression = "",
long lineNumber = CppUnitException::CPPUNIT_UNKNOWNLINENUMBER,
const std::string& fileName = CppUnitException::CPPUNIT_UNKNOWNFILENAME);
void fail(const std::string&message = "",
long lineNumber = CppUnitException::CPPUNIT_UNKNOWNLINENUMBER,
const std::string& fileName = CppUnitException::CPPUNIT_UNKNOWNFILENAME);
private:
const std::string _name;
};
// Constructs a test case
inline TestCase::TestCase(const std::string& name): _name (name)
{
}
// Destructs a test case
inline TestCase::~TestCase()
{
}
// Returns a count of all the tests executed
inline int TestCase::countTestCases()
{
return 1;
}
// Returns the name of the test case
inline const std::string& TestCase::name() const
{
return _name;
}
// A hook for fixture set up
inline void TestCase::setUp()
{
}
// A hook for fixture tear down
inline void TestCase::tearDown()
{
}
// Returns the name of the test case instance
inline std::string TestCase::toString()
{
const std::type_info& thisClass = typeid(*this);
return std::string(thisClass.name()) + "." + name();
}
// A set of macros which allow us to get the line number
// and file name at the point of an error.
// Just goes to show that preprocessors do have some
// redeeming qualities.
#undef assert
#define assert(condition) \
(this->assertImplementation((condition), (#condition), __LINE__, __FILE__))
#define assertEqualDelta(expected, actual, delta) \
(this->assertEquals((expected), (actual), (delta), __LINE__, __FILE__))
#define assertEqual(expected, actual) \
(this->assertEquals((expected), (actual), __LINE__, __FILE__))
#define assertNullPtr(ptr) \
(this->assertNull((ptr), #ptr, __LINE__, __FILE__))
#define assertNotNullPtr(ptr) \
(this->assertNotNull((ptr), #ptr, __LINE__, __FILE__))
#define failmsg(msg) \
(this->fail(msg, __LINE__, __FILE__))
CppUnit_END
#endif // CppUnit_TestCase_INCLUDED

View File

@ -0,0 +1,58 @@
//
// TestDecorator.h
//
// $Id: //poco/1.1.0/CppUnit/include/CppUnit/TestDecorator.h#1 $
//
#ifndef CppUnit_TestDecorator_INCLUDED
#define CppUnit_TestDecorator_INCLUDED
#ifndef CppUnit_CppUnit_INCLUDED
#include "CppUnit/CppUnit.h"
#endif
#ifndef CppUnit_Guards_INCLUDED
#include "CppUnit/Guards.h"
#endif
#ifndef CppUnit_Test_INCLUDED
#include "CppUnit/Test.h"
#endif
CppUnit_BEGIN
class TestResult;
/*
* A Decorator for Tests
*
* Does not assume ownership of the test it decorates
*
*/
class CppUnit_API TestDecorator: public Test
{
REFERENCEOBJECT(TestDecorator)
public:
TestDecorator(Test* test);
virtual ~TestDecorator();
int countTestCases();
void run(TestResult* result);
std::string toString();
protected:
Test* _test;
};
CppUnit_END
#endif // CppUnit_TestDecorator_INCLUDED

View File

@ -0,0 +1,92 @@
//
// TestFailure.h
//
// $Id: //poco/1.1.0/CppUnit/include/CppUnit/TestFailure.h#1 $
//
#ifndef CppUnit_TestFailure_INCLUDED
#define CppUnit_TestFailure_INCLUDED
#ifndef CppUnit_CppUnit_INCLUDED
#include "CppUnit/CppUnit.h"
#endif
#ifndef CppUnit_CppUnitException_INCLUDED
#include "CppUnit/CppUnitException.h"
#endif
#ifndef CppUnit_Guards_INCLUDED
#include "CppUnit/Guards.h"
#endif
CppUnit_BEGIN
class Test;
/*
* A TestFailure collects a failed test together with
* the caught exception.
*
* TestFailure assumes lifetime control for any exception
* passed to it. The lifetime of tests is handled by
* their TestSuite (if they have been added to one) or
* whomever creates them.
*
* see TestResult
* see TestSuite
*
*/
class CppUnit_API TestFailure
{
REFERENCEOBJECT (TestFailure)
public:
TestFailure(Test* failedTest, CppUnitException* thrownException);
~TestFailure();
Test* failedTest();
CppUnitException* thrownException();
std::string toString();
protected:
Test* _failedTest;
CppUnitException *_thrownException;
};
// Constructs a TestFailure with the given test and exception.
inline TestFailure::TestFailure(Test* failedTest, CppUnitException* thrownException): _failedTest(failedTest), _thrownException(thrownException)
{
}
// Deletes the owned exception.
inline TestFailure::~TestFailure()
{
delete _thrownException;
}
// Gets the failed test.
inline Test* TestFailure::failedTest()
{
return _failedTest;
}
// Gets the thrown exception.
inline CppUnitException* TestFailure::thrownException()
{
return _thrownException;
}
CppUnit_END
#endif // CppUnit_TestFailure_INCLUDED

View File

@ -0,0 +1,240 @@
//
// TestResult.h
//
// $Id: //poco/1.1.0/CppUnit/include/CppUnit/TestResult.h#1 $
//
#ifndef CppUnit_TestResult_INCLUDED
#define CppUnit_TestResult_INCLUDED
#ifndef CppUnit_CppUnit_INCLUDED
#include "CppUnit/CppUnit.h"
#endif
#ifndef CppUnit_Guards_INCLUDED
#include "CppUnit/Guards.h"
#endif
#ifndef CppUnit_TestFailure_INCLUDED
#include "CppUnit/TestFailure.h"
#endif
#ifndef STD_VECTOR_INCLUDED
#include <vector>
#define STD_VECTOR_INCLUDED
#endif
CppUnit_BEGIN
class CppUnitException;
class Test;
/*
* A TestResult collects the results of executing a test case. It is an
* instance of the Collecting Parameter pattern.
*
* The test framework distinguishes between failures and errors.
* A failure is anticipated and checked for with assertions. Errors are
* unanticipated problems signified by exceptions that are not generated
* by the framework.
*
* TestResult supplies a template method 'setSynchronizationObject ()'
* so that subclasses can provide mutual exclusion in the face of multiple
* threads. This can be useful when tests execute in one thread and
* they fill a subclass of TestResult which effects change in another
* thread. To have mutual exclusion, override setSynchronizationObject ()
* and make sure that you create an instance of ExclusiveZone at the
* beginning of each method.
*
* see Test
*/
class CppUnit_API TestResult
{
REFERENCEOBJECT (TestResult)
public:
TestResult();
virtual ~TestResult();
virtual void addError(Test* test, CppUnitException* e);
virtual void addFailure(Test* test, CppUnitException* e);
virtual void startTest(Test* test);
virtual void endTest(Test* test);
virtual int runTests();
virtual int testErrors();
virtual int testFailures();
virtual bool wasSuccessful();
virtual bool shouldStop();
virtual void stop();
virtual std::vector<TestFailure*>& errors();
virtual std::vector<TestFailure*>& failures();
class SynchronizationObject
{
public:
SynchronizationObject()
{
}
virtual ~SynchronizationObject()
{
}
virtual void lock()
{
}
virtual void unlock()
{
}
};
class ExclusiveZone
{
SynchronizationObject* m_syncObject;
public:
ExclusiveZone(SynchronizationObject* syncObject): m_syncObject(syncObject)
{
m_syncObject->lock();
}
~ExclusiveZone()
{
m_syncObject->unlock();
}
};
protected:
virtual void setSynchronizationObject(SynchronizationObject* syncObject);
std::vector<TestFailure*> _errors;
std::vector<TestFailure*> _failures;
int _runTests;
bool _stop;
SynchronizationObject* _syncObject;
};
// Construct a TestResult
inline TestResult::TestResult(): _syncObject(new SynchronizationObject())
{
_runTests = 0;
_stop = false;
}
// Adds an error to the list of errors. The passed in exception
// caused the error
inline void TestResult::addError(Test* test, CppUnitException* e)
{
ExclusiveZone zone(_syncObject);
_errors.push_back(new TestFailure(test, e));
}
// Adds a failure to the list of failures. The passed in exception
// caused the failure.
inline void TestResult::addFailure(Test* test, CppUnitException* e)
{
ExclusiveZone zone(_syncObject);
_failures.push_back(new TestFailure(test, e));
}
// Informs the result that a test will be started.
inline void TestResult::startTest(Test* test)
{
ExclusiveZone zone(_syncObject);
_runTests++;
}
// Informs the result that a test was completed.
inline void TestResult::endTest(Test* test)
{
ExclusiveZone zone(_syncObject);
}
// Gets the number of run tests.
inline int TestResult::runTests()
{
ExclusiveZone zone(_syncObject);
return _runTests;
}
// Gets the number of detected errors.
inline int TestResult::testErrors()
{
ExclusiveZone zone(_syncObject);
return (int) _errors.size();
}
// Gets the number of detected failures.
inline int TestResult::testFailures()
{
ExclusiveZone zone(_syncObject);
return (int) _failures.size();
}
// Returns whether the entire test was successful or not.
inline bool TestResult::wasSuccessful()
{
ExclusiveZone zone(_syncObject);
return _failures.size() == 0 && _errors.size () == 0;
}
// Returns a std::vector of the errors.
inline std::vector<TestFailure*>& TestResult::errors()
{
ExclusiveZone zone(_syncObject);
return _errors;
}
// Returns a std::vector of the failures.
inline std::vector<TestFailure*>& TestResult::failures()
{
ExclusiveZone zone(_syncObject);
return _failures;
}
// Returns whether testing should be stopped
inline bool TestResult::shouldStop()
{
ExclusiveZone zone(_syncObject);
return _stop;
}
// Stop testing
inline void TestResult::stop()
{
ExclusiveZone zone(_syncObject);
_stop = true;
}
// Accept a new synchronization object for protection of this instance
// TestResult assumes ownership of the object
inline void TestResult::setSynchronizationObject(SynchronizationObject* syncObject)
{
delete _syncObject;
_syncObject = syncObject;
}
CppUnit_END
#endif // CppUnit_TestResult_INCLUDED

View File

@ -0,0 +1,83 @@
//
// TestRunner.h
//
// $Id: //poco/1.1.0/CppUnit/include/CppUnit/TestRunner.h#1 $
//
#ifndef CppUnit_TestRunner_INCLUDED
#define CppUnit_TestRunner_INCLUDED
#ifndef CppUnit_CppUnit_INCLUDED
#include "CppUnit/CppUnit.h"
#endif
#ifndef STD_VECTOR_INCLUDED
#include <vector>
#define STD_VECTOR_INCLUDED
#endif
#ifndef STD_STRING_INCLUDED
#include <string>
#define STD_STRING_INCLUDED
#endif
CppUnit_BEGIN
class Test;
/*
* A command line based tool to run tests.
* TestRunner expects as its only argument the name of a TestCase class.
* TestRunner prints out a trace as the tests are executed followed by a
* summary at the end.
*
* You can add to the tests that the TestRunner knows about by
* making additional calls to "addTest (...)" in main.
*
* Here is the synopsis:
*
* TestRunner [-all] [-print] [-wait] ExampleTestCase
*
*/
class CppUnit_API TestRunner
{
typedef std::pair<std::string, Test*> Mapping;
typedef std::vector<Mapping> Mappings;
public:
TestRunner();
~TestRunner();
bool run(const std::vector<std::string>& args);
void addTest(const std::string& name, Test* test);
protected:
bool run(Test* test);
void printBanner();
void print(const std::string& name, Test* pTest, int indent);
Test* find(const std::string& name, Test* pTest, const std::string& testName);
private:
Mappings _mappings;
};
CppUnit_END
#define CppUnitMain(testCase) \
int main(int ac, char **av) \
{ \
std::vector<std::string> args; \
for (int i = 0; i < ac; ++i) \
args.push_back(std::string(av[i])); \
CppUnit::TestRunner runner; \
runner.addTest(#testCase, testCase::suite()); \
return runner.run(args) ? 0 : 1; \
}
#endif // CppUnit_TestRunner_INCLUDED

View File

@ -0,0 +1,63 @@
//
// TestSetup.h
//
// $Id: //poco/1.1.0/CppUnit/include/CppUnit/TestSetup.h#1 $
//
#ifndef CppUnit_TestSetup_INCLUDED
#define CppUnit_TestSetup_INCLUDED
#ifndef CppUnit_CppUnit_INCLUDED
#include "CppUnit/CppUnit.h"
#endif
#ifndef CppUnit_Guards_INCLUDED
#include "CppUnit/Guards.h"
#endif
#ifndef CppUnit_TestDecorator_INCLUDED
#include "CppUnit/TestDecorator.h"
#endif
CppUnit_BEGIN
class Test;
class TestResult;
class CppUnit_API TestSetup: public TestDecorator
{
REFERENCEOBJECT (TestSetup)
public:
TestSetup(Test* test): TestDecorator(test)
{
}
void run(TestResult* result);
protected:
void setUp()
{
}
void tearDown()
{
}
};
inline void TestSetup::run(TestResult* result)
{
setUp();
TestDecorator::run(result);
tearDown();
}
CppUnit_END
#endif // CppUnit_TestSetup_INCLUDED

View File

@ -0,0 +1,110 @@
//
// TestSuite.h
//
// $Id: //poco/1.1.0/CppUnit/include/CppUnit/TestSuite.h#1 $
//
#ifndef CppUnit_TestSuite_INCLUDED
#define CppUnit_TestSuite_INCLUDED
#ifndef CppUnit_CppUnit_INCLUDED
#include "CppUnit/CppUnit.h"
#endif
#ifndef CppUnit_Guards_INCLUDED
#include "CppUnit/Guards.h"
#endif
#ifndef CppUnit_Test_INCLUDED
#include "CppUnit/Test.h"
#endif
#ifndef STD_VECTOR_INCLUDED
#include <vector>
#define STD_VECTOR_INCLUDED
#endif
#ifndef STD_STRING_INCLUDED
#include <string>
#define STD_STRING_INCLUDED
#endif
CppUnit_BEGIN
class TestResult;
/*
* A TestSuite is a Composite of Tests.
* It runs a collection of test cases. Here is an example.
*
* TestSuite *suite= new TestSuite();
* suite->addTest(new TestCaller<MathTest> ("testAdd", testAdd));
* suite->addTest(new TestCaller<MathTest> ("testDivideByZero", testDivideByZero));
*
* Note that TestSuites assume lifetime
* control for any tests added to them.
*
* see Test and TestCaller
*/
class CppUnit_API TestSuite: public Test
{
REFERENCEOBJECT (TestSuite)
public:
TestSuite(const std::string& name = "");
~TestSuite();
void run(TestResult* result);
int countTestCases();
void addTest(Test* test);
std::string toString();
virtual void deleteContents();
const std::vector<Test*> tests() const;
private:
std::vector<Test*> _tests;
const std::string _name;
};
// Default constructor
inline TestSuite::TestSuite(const std::string& name): _name(name)
{
}
// Destructor
inline TestSuite::~TestSuite()
{
deleteContents();
}
// Adds a test to the suite.
inline void TestSuite::addTest(Test* test)
{
_tests.push_back(test);
}
// Returns a std::string representation of the test suite.
inline std::string TestSuite::toString()
{
return "suite " + _name;
}
// Returns all tests
inline const std::vector<Test*> TestSuite::tests() const
{
return _tests;
}
CppUnit_END
#endif // CppUnit_TestSuite_INCLUDED

View File

@ -0,0 +1,54 @@
//
// TextTestResult.h
//
// $Id: //poco/1.1.0/CppUnit/include/CppUnit/TextTestResult.h#1 $
//
#ifndef CppUnit_TextTestResult_INCLUDED
#define CppUnit_TextTestResult_INCLUDED
#ifndef CppUnit_CppUnit_INCLUDED
#include "CppUnit/CppUnit.h"
#endif
#ifndef CppUnit_TestResult_INCLUDED
#include "CppUnit/TestResult.h"
#endif
#ifndef STD_OSTREAM_INCLUDED
#include <ostream>
#define STD_OSTREAM_INCLUDED
#endif
CppUnit_BEGIN
class CppUnit_API TextTestResult: public TestResult
{
public:
virtual void addError(Test* test, CppUnitException* e);
virtual void addFailure(Test* test, CppUnitException* e);
virtual void startTest(Test* test);
virtual void print(std::ostream& stream);
virtual void printErrors(std::ostream& stream);
virtual void printFailures(std::ostream& stream);
virtual void printHeader(std::ostream& stream);
protected:
std::string shortName(const std::string& testName);
};
/* insertion operator for easy output */
inline std::ostream& operator<< (std::ostream& stream, TextTestResult& result)
{
result.print(stream);
return stream;
}
CppUnit_END
#endif // CppUnit_TextTestResult_INCLUDED

View File

@ -0,0 +1,81 @@
//
// estring.h
//
// $Id: //poco/1.1.0/CppUnit/include/CppUnit/estring.h#1 $
//
#ifndef CppUnit_estring_INCLUDED
#define CppUnit_estring_INCLUDED
#ifndef CppUnit_CppUnit_INCLUDED
#include "CppUnit/CppUnit.h"
#endif
#ifndef STD_STRING_INCLUDED
#include <string>
#define STD_STRING_INCLUDED
#endif
#ifndef STD_STDIO_INCLUDED
#include <stdio.h>
#define STD_STDIO_INCLUDED
#endif
CppUnit_BEGIN
// Create a std::string from a const char pointer
inline std::string estring(const char *cstring)
{
return std::string(cstring);
}
// Create a std::string from a std::string (for uniformities' sake)
inline std::string estring(std::string& expandedString)
{
return expandedString;
}
// Create a std::string from an int
inline std::string estring(int number)
{
char buffer[50];
sprintf(buffer, "%d", number);
return std::string (buffer);
}
// Create a string from a long
inline std::string estring(long number)
{
char buffer[50];
sprintf(buffer, "%ld", number);
return std::string (buffer);
}
// Create a std::string from a double
inline std::string estring(double number)
{
char buffer[50];
sprintf(buffer, "%lf", number);
return std::string(buffer);
}
// Create a std::string from a double
inline std::string estring(const void* ptr)
{
char buffer[50];
sprintf(buffer, "%p", ptr);
return std::string(buffer);
}
CppUnit_END
#endif // CppUnit_estring_INCLUDED

View File

@ -0,0 +1,18 @@
//
// CppUnitException.cpp
//
// $Id: //poco/1.1.0/CppUnit/src/CppUnitException.cpp#1 $
//
#include "CppUnit/CppUnitException.h"
CppUnit_BEGIN
const std::string CppUnitException::CPPUNIT_UNKNOWNFILENAME = "<unknown>";
const int CppUnitException::CPPUNIT_UNKNOWNLINENUMBER = -1;
CppUnit_END

168
CppUnit/src/TestCase.cpp Normal file
View File

@ -0,0 +1,168 @@
//
// TestCase.cpp
//
// $Id: //poco/1.1.0/CppUnit/src/TestCase.cpp#1 $
//
#include <stdexcept>
#include <math.h>
#include "CppUnit/TestCase.h"
#include "CppUnit/TestResult.h"
#include "CppUnit/estring.h"
#include <typeinfo>
using namespace std;
CppUnit_BEGIN
// Create a default TestResult
TestResult* TestCase::defaultResult()
{
return new TestResult;
}
// Check for a failed general assertion
void TestCase::assertImplementation(bool condition, const std::string& conditionExpression, long lineNumber, const std::string& fileName)
{
if (!condition)
throw CppUnitException(conditionExpression, lineNumber, fileName);
}
// Check for a failed equality assertion
void TestCase::assertEquals(long expected, long actual, long lineNumber, const std::string& fileName)
{
if (expected != actual)
assertImplementation(false, notEqualsMessage(expected, actual), lineNumber, fileName);
}
// Check for a failed equality assertion
void TestCase::assertEquals(double expected, double actual, double delta, long lineNumber, const std::string& fileName)
{
if (fabs(expected - actual) > delta)
assertImplementation(false, notEqualsMessage(expected, actual), lineNumber, fileName);
}
// Check for a failed equality assertion
void TestCase::assertEquals(const void* expected, const void* actual, long lineNumber, const std::string& fileName)
{
if (expected != actual)
assertImplementation(false, notEqualsMessage(expected, actual), lineNumber, fileName);
}
// Check for a failed equality assertion
void TestCase::assertEquals(const std::string& expected, const std::string& actual, long lineNumber, const std::string& fileName)
{
if (expected != actual)
assertImplementation(false, notEqualsMessage(expected, actual), lineNumber, fileName);
}
void TestCase::assertNotNull(const void* pointer, const std::string& pointerExpression, long lineNumber, const std::string& fileName)
{
if (pointer == NULL)
throw CppUnitException(pointerExpression + " must not be NULL", lineNumber, fileName);
}
void TestCase::assertNull(const void* pointer, const std::string& pointerExpression, long lineNumber, const std::string& fileName)
{
if (pointer != NULL)
throw CppUnitException(pointerExpression + " must be NULL", lineNumber, fileName);
}
void TestCase::fail (const std::string& message, long lineNumber, const std::string& fileName)
{
throw CppUnitException(std::string("fail: ") + message, lineNumber, fileName);
}
// Run the test and catch any exceptions that are triggered by it
void TestCase::run(TestResult *result)
{
result->startTest(this);
setUp();
try
{
runTest();
}
catch (CppUnitException& e)
{
CppUnitException* copy = new CppUnitException(e);
result->addFailure(this, copy);
}
catch (std::exception& e)
{
std::string msg(typeid(e).name());
msg.append(": ");
msg.append(e.what());
result->addError(this, new CppUnitException(msg));
}
#if !defined(_WIN32)
catch (...)
{
CppUnitException *e = new CppUnitException ("unknown exception");
result->addError (this, e);
}
#endif
tearDown ();
result->endTest(this);
}
// A default run method
TestResult* TestCase::run()
{
TestResult* result = defaultResult();
run(result);
return result;
}
// All the work for runTest is deferred to subclasses
void TestCase::runTest()
{
}
// Build a message about a failed equality check
std::string TestCase::notEqualsMessage(long expected, long actual)
{
return "expected: " + estring(expected) + " but was: " + estring(actual);
}
// Build a message about a failed equality check
std::string TestCase::notEqualsMessage(double expected, double actual)
{
return "expected: " + estring(expected) + " but was: " + estring(actual);
}
// Build a message about a failed equality check
std::string TestCase::notEqualsMessage(const void* expected, const void* actual)
{
return "expected: " + estring(expected) + " but was: " + estring(actual);
}
// Build a message about a failed equality check
std::string TestCase::notEqualsMessage(const std::string& expected, const std::string& actual)
{
return "expected: \"" + expected + "\" but was: \"" + actual + "\"";
}
CppUnit_END

View File

@ -0,0 +1,43 @@
//
// TestDecorator.cpp
//
// $Id: //poco/1.1.0/CppUnit/src/TestDecorator.cpp#1 $
//
#include "CppUnit/TestDecorator.h"
CppUnit_BEGIN
TestDecorator::TestDecorator(Test* test)
{
_test = test;
}
TestDecorator::~TestDecorator()
{
}
int TestDecorator::countTestCases()
{
return _test->countTestCases();
}
void TestDecorator::run(TestResult* result)
{
_test->run(result);
}
std::string TestDecorator::toString()
{
return _test->toString();
}
CppUnit_END

View File

@ -0,0 +1,22 @@
//
// TestFailure.cpp
//
// $Id: //poco/1.1.0/CppUnit/src/TestFailure.cpp#1 $
//
#include "CppUnit/TestFailure.h"
#include "CppUnit/Test.h"
CppUnit_BEGIN
// Returns a short description of the failure.
std::string TestFailure::toString()
{
return _failedTest->toString () + ": " + _thrownException->what();
}
CppUnit_END

View File

@ -0,0 +1,29 @@
//
// TestResult.cpp
//
// $Id: //poco/1.1.0/CppUnit/src/TestResult.cpp#1 $
//
#include "CppUnit/TestResult.h"
CppUnit_BEGIN
// Destroys a test result
TestResult::~TestResult()
{
std::vector<TestFailure*>::iterator it;
for (it = _errors.begin(); it != _errors.end(); ++it)
delete *it;
for (it = _failures.begin(); it != _failures.end(); ++it)
delete *it;
delete _syncObject;
}
CppUnit_END

181
CppUnit/src/TestRunner.cpp Normal file
View File

@ -0,0 +1,181 @@
//
// TestRunner.cpp
//
// $Id: //poco/1.1.0/CppUnit/src/TestRunner.cpp#1 $
//
#include "CppUnit/TestRunner.h"
#include "CppUnit/Test.h"
#include "CppUnit/TestSuite.h"
#include "CppUnit/TextTestResult.h"
#include <iostream>
CppUnit_BEGIN
TestRunner::TestRunner()
{
}
TestRunner::~TestRunner()
{
for (Mappings::iterator it = _mappings.begin(); it != _mappings.end(); ++it)
delete it->second;
}
void TestRunner::printBanner()
{
std::cout
<< "Usage: driver [-all] [-print] [-wait] [name] ..." << std::endl
<< " where name is the name of a test case class" << std::endl;
}
bool TestRunner::run(const std::vector<std::string>& args)
{
std::string testCase;
int numberOfTests = 0;
bool success = true;
bool all = false;
bool wait = false;
bool printed = false;
for (int i = 1; i < args.size(); i++)
{
const std::string& arg = args[i];
if (arg == "-wait")
{
wait = true;
continue;
}
else if (arg == "-all")
{
all = true;
continue;
}
else if (arg == "-print")
{
for (Mappings::iterator it = _mappings.begin(); it != _mappings.end(); ++it)
{
print(it->first, it->second, 0);
}
printed = true;
continue;
}
if (!all)
{
testCase = arg;
if (testCase == "")
{
printBanner();
return false;
}
Test* testToRun = 0;
for (Mappings::iterator it = _mappings.begin(); !testToRun && it != _mappings.end(); ++it)
{
testToRun = find(testCase, it->second, it->first);
}
if (testToRun)
{
if (!run(testToRun)) success = false;
}
numberOfTests++;
if (!testToRun)
{
std::cout << "Test " << testCase << " not found." << std::endl;
return false;
}
}
}
if (all)
{
for (Mappings::iterator it = _mappings.begin(); it != _mappings.end(); ++it)
{
if (!run(it->second)) success = false;
numberOfTests++;
}
}
if (numberOfTests == 0 && !printed)
{
printBanner();
return false;
}
if (wait)
{
std::cout << "<RETURN> to continue" << std::endl;
std::cin.get();
}
return success;
}
bool TestRunner::run(Test* test)
{
TextTestResult result;
test->run(&result);
std::cout << result << std::endl;
return result.wasSuccessful();
}
void TestRunner::addTest(const std::string& name, Test* test)
{
_mappings.push_back(Mapping(name, test));
}
void TestRunner::print(const std::string& name, Test* pTest, int indent)
{
for (int i = 0; i < indent; ++i)
std::cout << " ";
std::cout << name << std::endl;
TestSuite* pSuite = dynamic_cast<TestSuite*>(pTest);
if (pSuite)
{
const std::vector<Test*>& tests = pSuite->tests();
for (std::vector<Test*>::const_iterator it = tests.begin(); it != tests.end(); ++it)
{
print((*it)->toString(), *it, indent + 1);
}
}
}
Test* TestRunner::find(const std::string& name, Test* pTest, const std::string& testName)
{
if (testName.find(name) != std::string::npos)
{
return pTest;
}
else
{
TestSuite* pSuite = dynamic_cast<TestSuite*>(pTest);
if (pSuite)
{
const std::vector<Test*>& tests = pSuite->tests();
for (std::vector<Test*>::const_iterator it = tests.begin(); it != tests.end(); ++it)
{
Test* result = find(name, *it, (*it)->toString());
if (result) return result;
}
}
return 0;
}
}
CppUnit_END

49
CppUnit/src/TestSuite.cpp Normal file
View File

@ -0,0 +1,49 @@
//
// TestSuite.cpp
//
// $Id: //poco/1.1.0/CppUnit/src/TestSuite.cpp#1 $
//
#include "CppUnit/TestSuite.h"
#include "CppUnit/TestResult.h"
CppUnit_BEGIN
// Deletes all tests in the suite.
void TestSuite::deleteContents()
{
for (std::vector<Test*>::iterator it = _tests.begin(); it != _tests.end(); ++it)
delete *it;
}
// Runs the tests and collects their result in a TestResult.
void TestSuite::run(TestResult *result)
{
for (std::vector<Test*>::iterator it = _tests.begin(); it != _tests.end(); ++it)
{
if (result->shouldStop ())
break;
Test *test = *it;
test->run(result);
}
}
// Counts the number of test cases that will be run by this test.
int TestSuite::countTestCases()
{
int count = 0;
for (std::vector<Test*>::iterator it = _tests.begin (); it != _tests.end (); ++it)
count += (*it)->countTestCases();
return count;
}
CppUnit_END

View File

@ -0,0 +1,133 @@
//
// TextTestResult.cpp
//
// $Id: //poco/1.1.0/CppUnit/src/TextTestResult.cpp#1 $
//
#include "CppUnit/TextTestResult.h"
#include "CppUnit/CppUnitException.h"
#include "CppUnit/Test.h"
#include "CppUnit/estring.h"
#include <iostream>
#include <iomanip>
CppUnit_BEGIN
void TextTestResult::addError(Test* test, CppUnitException* e)
{
TestResult::addError(test, e);
std::cerr << "ERROR" << std::flush;
}
void TextTestResult::addFailure(Test* test, CppUnitException* e)
{
TestResult::addFailure(test, e);
std::cerr << "FAILURE" << std::flush;
}
void TextTestResult::startTest(Test* test)
{
TestResult::startTest(test);
std::cerr << "\n" << shortName(test->toString()) << ": ";
}
void TextTestResult::printErrors(std::ostream& stream)
{
if (testErrors() != 0)
{
stream << "\n";
if (testErrors() == 1)
stream << "There was " << testErrors() << " error: " << std::endl;
else
stream << "There were " << testErrors() << " errors: " << std::endl;
int i = 1;
for (std::vector<TestFailure*>::iterator it = errors().begin(); it != errors().end(); ++it)
{
TestFailure* failure = *it;
CppUnitException* e = failure->thrownException();
stream << std::setw(2) << i
<< ": "
<< failure->failedTest()->toString() << "\n"
<< " \"" << (e ? e->what() : "") << "\"\n"
<< " in \"" << (e ? e->fileName() : std::string()) << "\", line " << (e ? e->lineNumber() : 0) << "\n";
i++;
}
}
}
void TextTestResult::printFailures(std::ostream& stream)
{
if (testFailures() != 0)
{
stream << "\n";
if (testFailures() == 1)
stream << "There was " << testFailures() << " failure: " << std::endl;
else
stream << "There were " << testFailures() << " failures: " << std::endl;
int i = 1;
for (std::vector<TestFailure*>::iterator it = failures().begin(); it != failures().end(); ++it)
{
TestFailure* failure = *it;
CppUnitException* e = failure->thrownException();
stream << std::setw(2) << i
<< ": "
<< failure->failedTest()->toString() << "\n"
<< " \"" << (e ? e->what() : "") << "\"\n"
<< " in \"" << (e ? e->fileName() : std::string()) << "\", line " << (e ? e->lineNumber() : 0) << "\n";
i++;
}
}
}
void TextTestResult::print(std::ostream& stream)
{
printHeader(stream);
printErrors(stream);
printFailures(stream);
}
void TextTestResult::printHeader(std::ostream& stream)
{
std::cout << "\n\n";
if (wasSuccessful())
std::cout << "OK ("
<< runTests() << " tests)"
<< std::endl;
else
std::cout << "!!!FAILURES!!!" << std::endl
<< "Runs: "
<< runTests ()
<< " Failures: "
<< testFailures ()
<< " Errors: "
<< testErrors ()
<< std::endl;
}
std::string TextTestResult::shortName(const std::string& testName)
{
std::string::size_type pos = testName.rfind('.');
if (pos != std::string::npos)
return std::string(testName, pos + 1);
else
return testName;
}
CppUnit_END

View File

@ -0,0 +1,48 @@
Microsoft Visual Studio Solution File, Format Version 8.00
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Foundation", "Foundation_vs71.vcproj", "{8164D41D-B053-405B-826C-CF37AC0EF176}"
ProjectSection(ProjectDependencies) = postProject
EndProjectSection
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TestSuite", "testsuite\TestSuite_vs71.vcproj", "{F1EE93DF-347F-4CB3-B191-C4E63F38E972}"
ProjectSection(ProjectDependencies) = postProject
{0955EB03-544B-4BD4-9C10-89CF38078F5F} = {0955EB03-544B-4BD4-9C10-89CF38078F5F}
{8164D41D-B053-405B-826C-CF37AC0EF176} = {8164D41D-B053-405B-826C-CF37AC0EF176}
EndProjectSection
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TestLibrary", "testsuite\TestLibrary_vs71.vcproj", "{0955EB03-544B-4BD4-9C10-89CF38078F5F}"
ProjectSection(ProjectDependencies) = postProject
{8164D41D-B053-405B-826C-CF37AC0EF176} = {8164D41D-B053-405B-826C-CF37AC0EF176}
EndProjectSection
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TestApp", "testsuite\TestApp_vs71.vcproj", "{6C41E55D-C0FC-4E01-AA8D-B7DA40E31D3A}"
ProjectSection(ProjectDependencies) = postProject
EndProjectSection
EndProject
Global
GlobalSection(SolutionConfiguration) = preSolution
debug_shared = debug_shared
release_shared = release_shared
EndGlobalSection
GlobalSection(ProjectConfiguration) = postSolution
{8164D41D-B053-405B-826C-CF37AC0EF176}.debug_shared.ActiveCfg = debug_shared|Win32
{8164D41D-B053-405B-826C-CF37AC0EF176}.debug_shared.Build.0 = debug_shared|Win32
{8164D41D-B053-405B-826C-CF37AC0EF176}.release_shared.ActiveCfg = release_shared|Win32
{8164D41D-B053-405B-826C-CF37AC0EF176}.release_shared.Build.0 = release_shared|Win32
{F1EE93DF-347F-4CB3-B191-C4E63F38E972}.debug_shared.ActiveCfg = debug_shared|Win32
{F1EE93DF-347F-4CB3-B191-C4E63F38E972}.debug_shared.Build.0 = debug_shared|Win32
{F1EE93DF-347F-4CB3-B191-C4E63F38E972}.release_shared.ActiveCfg = release_shared|Win32
{F1EE93DF-347F-4CB3-B191-C4E63F38E972}.release_shared.Build.0 = release_shared|Win32
{0955EB03-544B-4BD4-9C10-89CF38078F5F}.debug_shared.ActiveCfg = debug_shared|Win32
{0955EB03-544B-4BD4-9C10-89CF38078F5F}.debug_shared.Build.0 = debug_shared|Win32
{0955EB03-544B-4BD4-9C10-89CF38078F5F}.release_shared.ActiveCfg = release_shared|Win32
{0955EB03-544B-4BD4-9C10-89CF38078F5F}.release_shared.Build.0 = release_shared|Win32
{6C41E55D-C0FC-4E01-AA8D-B7DA40E31D3A}.debug_shared.ActiveCfg = debug_shared|Win32
{6C41E55D-C0FC-4E01-AA8D-B7DA40E31D3A}.debug_shared.Build.0 = debug_shared|Win32
{6C41E55D-C0FC-4E01-AA8D-B7DA40E31D3A}.release_shared.ActiveCfg = release_shared|Win32
{6C41E55D-C0FC-4E01-AA8D-B7DA40E31D3A}.release_shared.Build.0 = release_shared|Win32
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
EndGlobalSection
GlobalSection(ExtensibilityAddIns) = postSolution
EndGlobalSection
EndGlobal

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,45 @@
Microsoft Visual Studio Solution File, Format Version 9.00
# Visual Studio 2005
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Foundation", "Foundation_vs80.vcproj", "{8164D41D-B053-405B-826C-CF37AC0EF176}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TestSuite", "testsuite\TestSuite_vs80.vcproj", "{F1EE93DF-347F-4CB3-B191-C4E63F38E972}"
ProjectSection(ProjectDependencies) = postProject
{0955EB03-544B-4BD4-9C10-89CF38078F5F} = {0955EB03-544B-4BD4-9C10-89CF38078F5F}
{6C41E55D-C0FC-4E01-AA8D-B7DA40E31D3A} = {6C41E55D-C0FC-4E01-AA8D-B7DA40E31D3A}
{8164D41D-B053-405B-826C-CF37AC0EF176} = {8164D41D-B053-405B-826C-CF37AC0EF176}
EndProjectSection
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TestLibrary", "testsuite\TestLibrary_vs80.vcproj", "{0955EB03-544B-4BD4-9C10-89CF38078F5F}"
ProjectSection(ProjectDependencies) = postProject
{8164D41D-B053-405B-826C-CF37AC0EF176} = {8164D41D-B053-405B-826C-CF37AC0EF176}
EndProjectSection
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TestApp", "testsuite\TestApp_vs80.vcproj", "{6C41E55D-C0FC-4E01-AA8D-B7DA40E31D3A}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
debug_shared|Win32 = debug_shared|Win32
release_shared|Win32 = release_shared|Win32
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{8164D41D-B053-405B-826C-CF37AC0EF176}.debug_shared|Win32.ActiveCfg = debug_shared|Win32
{8164D41D-B053-405B-826C-CF37AC0EF176}.debug_shared|Win32.Build.0 = debug_shared|Win32
{8164D41D-B053-405B-826C-CF37AC0EF176}.release_shared|Win32.ActiveCfg = release_shared|Win32
{8164D41D-B053-405B-826C-CF37AC0EF176}.release_shared|Win32.Build.0 = release_shared|Win32
{F1EE93DF-347F-4CB3-B191-C4E63F38E972}.debug_shared|Win32.ActiveCfg = debug_shared|Win32
{F1EE93DF-347F-4CB3-B191-C4E63F38E972}.debug_shared|Win32.Build.0 = debug_shared|Win32
{F1EE93DF-347F-4CB3-B191-C4E63F38E972}.release_shared|Win32.ActiveCfg = release_shared|Win32
{F1EE93DF-347F-4CB3-B191-C4E63F38E972}.release_shared|Win32.Build.0 = release_shared|Win32
{0955EB03-544B-4BD4-9C10-89CF38078F5F}.debug_shared|Win32.ActiveCfg = debug_shared|Win32
{0955EB03-544B-4BD4-9C10-89CF38078F5F}.debug_shared|Win32.Build.0 = debug_shared|Win32
{0955EB03-544B-4BD4-9C10-89CF38078F5F}.release_shared|Win32.ActiveCfg = release_shared|Win32
{0955EB03-544B-4BD4-9C10-89CF38078F5F}.release_shared|Win32.Build.0 = release_shared|Win32
{6C41E55D-C0FC-4E01-AA8D-B7DA40E31D3A}.debug_shared|Win32.ActiveCfg = debug_shared|Win32
{6C41E55D-C0FC-4E01-AA8D-B7DA40E31D3A}.debug_shared|Win32.Build.0 = debug_shared|Win32
{6C41E55D-C0FC-4E01-AA8D-B7DA40E31D3A}.release_shared|Win32.ActiveCfg = release_shared|Win32
{6C41E55D-C0FC-4E01-AA8D-B7DA40E31D3A}.release_shared|Win32.Build.0 = release_shared|Win32
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal

File diff suppressed because it is too large Load Diff

40
Foundation/Makefile Normal file
View File

@ -0,0 +1,40 @@
#
# Makefile
#
# $Id: //poco/1.1.0/Foundation/Makefile#1 $
#
# Makefile for Poco Foundation
#
include $(POCO_BASE)/build/rules/global
objects = ArchiveStrategy ASCIIEncoding AsyncChannel Base64Decoder Base64Encoder \
BinaryReader BinaryWriter Bugcheck ByteOrder Channel Configurable ConsoleChannel \
CountingStream DateTime LocalDateTime DateTimeFormat DateTimeFormatter DateTimeParser \
Debugger DeflatingStream DigestEngine DigestStream DirectoryIterator \
Environment Event EventArgs ErrorHandler Exception FPEnvironment File Glob \
FileChannel Formatter FormattingChannel HexBinaryDecoder LineEndingConverter \
HexBinaryEncoder InflatingStream Latin1Encoding Latin9Encoding LogFile Logger \
LoggingFactory LoggingRegistry NamedEvent NamedMutex NullChannel \
MemoryPool MD2Engine MD4Engine MD5Engine Manifest Message Mutex \
NestedDiagnosticContext Notification NotificationCenter \
NotificationQueue NullStream NumberFormatter NumberParser Observer \
Path PatternFormatter Process PurgeStrategy RWLock Random RandomStream \
RegularExpression RefCountedObject Runnable RotateStrategy \
SHA1Engine Semaphore SharedLibrary SimpleFileChannel \
SignalHandler SplitterChannel Stopwatch StreamChannel StreamConverter StreamCopier \
StreamTokenizer String StringTokenizer SynchronizedObject SyslogChannel \
Task TaskManager TaskNotification TeeStream \
TemporaryFile TextConverter TextEncoding TextIterator Thread ThreadLocal \
ThreadPool Timer Timespan Timestamp Timezone Token URI \
FileStreamFactory URIStreamFactory URIStreamOpener UTF16Encoding Windows1252Encoding \
UTF8Encoding UnicodeConverter UUID UUIDGenerator \
adler32 chartables compress crc32 \
deflate get gzio infback inffast inflate inftrees maketables pcre study \
trees zutil
target = PocoFoundation
target_version = 1
target_libs =
include $(POCO_BASE)/build/rules/lib

View File

@ -0,0 +1,125 @@
#
# Foundation.vmsbuild
#
# $Id: //poco/Foundation/foundation.vmsbuild#8 $
#
LIB=PocoFoundation
ASCIIEncoding
AsyncChannel
Base64Decoder
Base64Encoder
BinaryReader
BinaryWriter
Bugcheck
ByteOrder
Channel
Configurable
ConsoleChannel
CountingStream
DateTime
LocalDateTime
DateTimeFormat
DateTimeFormatter
DateTimeParser
Debugger
DeflatingStream
DigestEngine
DigestStream
DirectoryIterator
Environment
Event
EventArgs
Exception
FPEnvironment
File
Glob
FileChannel
Formatter
FormattingChannel
HexBinaryDecoder
HexBinaryEncoder
InflatingStream
Latin1Encoding
Latin9Encoding
Logger
LoggingFactory
LoggingRegistry
NamedEvent
NamedMutex
NullChannel
MD2Engine
MD4Engine
MD5Engine
Manifest
Message
Mutex
NestedDiagnosticContext
Notification
NotificationCenter
NotificationQueue
NullStream
NumberFormatter
NumberParser
Observer
Path
PatternFormatter
Process
RWLock
Random
RandomStream
RegularExpression
RefCountedObject
Runnable
SHA1Engine
Semaphore
SharedLibrary
SignalHandler
SplitterChannel
Stopwatch
StreamChannel
StreamConverter
StreamCopier
StreamTokenizer
String
StringTokenizer
SynchronizedObject
SyslogChannel
Task
TaskManager
TaskNotification
TemporaryFile
TextConverter
TextEncoding
TextIterator
Thread
ThreadLocal
ThreadPool
Timer
Timespan
Timestamp
Timezone
Token
URI
URIFileStreamFactory
URIStreamFactory
URIStreamOpener
UTF16Encoding
UTF8Encoding
UUID
UUIDGenerator
adler32
chartables
compress
crc32
deflate
get
gzio
infback
inffast
inflate
inftrees
maketables
pcre
study
trees
zutil

View File

@ -0,0 +1,72 @@
//
// ASCIIEncoding.h
//
// $Id: //poco/1.1.0/Foundation/include/Foundation/ASCIIEncoding.h#2 $
//
// Library: Foundation
// Package: Text
// Module: ASCIIEncoding
//
// Definition of the ASCIIEncoding class.
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#ifndef Foundation_ASCIIEncoding_INCLUDED
#define Foundation_ASCIIEncoding_INCLUDED
#ifndef Foundation_Foundation_INCLUDED
#include "Foundation/Foundation.h"
#endif
#ifndef Foundation_TextEncoding_INCLUDED
#include "Foundation/TextEncoding.h"
#endif
Foundation_BEGIN
class Foundation_API ASCIIEncoding: public TextEncoding
/// 7-bit ASCII text encoding.
{
public:
ASCIIEncoding();
~ASCIIEncoding();
const CharacterMap& characterMap() const;
int convert(const unsigned char* bytes) const;
int convert(int ch, unsigned char* bytes, int length) const;
private:
static const CharacterMap _charMap;
};
Foundation_END
#endif // Foundation_ASCIIEncoding_INCLUDED

View File

@ -0,0 +1,258 @@
//
// AbstractCache.h
//
// $Id: //poco/1.1.0/Foundation/include/Foundation/AbstractCache.h#2 $
//
// Library: Foundation
// Package: Cache
// Module: AbstractCache
//
// Definition of the AbstractCache class.
//
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#ifndef Foundation_AbstractCache_INCLUDED
#define Foundation_AbstractCache_INCLUDED
#include "Foundation/KeyValueArgs.h"
#include "Foundation/ValidArgs.h"
#include "Foundation/ScopedLock.h"
#include "Foundation/Mutex.h"
#include "Foundation/Exception.h"
#include "Foundation/BasicEvent.h"
#include "Foundation/EventArgs.h"
#include "Foundation/Delegate.h"
#include "Foundation/SharedPtr.h"
#include <map>
#include <set>
Foundation_BEGIN
template <class TKey, class TValue, class TStrategy>
class AbstractCache
/// An AbstractCache is the interface of all caches.
{
public:
BasicEvent<const KeyValueArgs<TKey, TValue > > Add;
BasicEvent<const TKey> Remove;
BasicEvent<const TKey> Get;
BasicEvent<const EventArgs> Clear;
typedef std::map<TKey, SharedPtr<TValue > > DataHolder;
typedef typename DataHolder::iterator Iterator;
typedef typename DataHolder::const_iterator ConstIterator;
typedef std::set<TKey> KeySet;
AbstractCache()
{
initialize();
}
AbstractCache(const TStrategy& strat):_strategy(strat)
{
initialize();
}
virtual ~AbstractCache()
{
uninitialize();
}
void add(const TKey& key, const TValue& val)
/// Adds the key value pair to the cache.
/// If for the key already an entry exists, it will be overwritten.
{
FastMutex::ScopedLock lock(_mutex);
doAdd(key, val);
}
void remove(const TKey& key)
/// Removes an entry from the cache. If the entry is not found,
/// the remove is ignored.
{
FastMutex::ScopedLock lock(_mutex);
doRemove(key);
}
bool has(const TKey& key) const
/// Returns true if the cache contains a value for the key.
{
FastMutex::ScopedLock lock(_mutex);
return doHas(key);
}
SharedPtr<TValue> get(const TKey& key)
/// Returns a SharedPtr of the value. The SharedPointer will remain valid
/// even when cache replacement removes the element.
/// If for the key no value exists, an empty SharedPtr is returned.
{
FastMutex::ScopedLock lock(_mutex);
return doGet (key);
}
void clear()
/// Removes all elements from the cache.
{
FastMutex::ScopedLock lock(_mutex);
doClear();
}
protected:
mutable BasicEvent<ValidArgs<TKey> > IsValid;
mutable BasicEvent<KeySet> Replace;
void initialize()
/// Sets up event registration.
{
Add += Delegate<TStrategy, const KeyValueArgs<TKey, TValue> >(&_strategy, &TStrategy::onAdd);
Remove += Delegate<TStrategy, const TKey>(&_strategy, &TStrategy::onRemove);
Get += Delegate<TStrategy, const TKey>(&_strategy, &TStrategy::onGet);
Clear += Delegate<TStrategy, const EventArgs>(&_strategy, &TStrategy::onClear);
IsValid += Delegate<TStrategy, ValidArgs<TKey> >(&_strategy, &TStrategy::onIsValid);
Replace += Delegate<TStrategy, KeySet>(&_strategy, &TStrategy::onReplace);
}
void uninitialize()
/// Reverts event registration.
{
Add -= Delegate<TStrategy, const KeyValueArgs<TKey, TValue> >(&_strategy, &TStrategy::onAdd );
Remove -= Delegate<TStrategy, const TKey>(&_strategy, &TStrategy::onRemove);
Get -= Delegate<TStrategy, const TKey>(&_strategy, &TStrategy::onGet);
Clear -= Delegate<TStrategy, const EventArgs>(&_strategy, &TStrategy::onClear);
IsValid -= Delegate<TStrategy, ValidArgs<TKey> >(&_strategy, &TStrategy::onIsValid);
Replace -= Delegate<TStrategy, KeySet>(&_strategy, &TStrategy::onReplace);
}
void doAdd(const TKey& key, const TValue& val)
/// Adds the key value pair to the cache.
/// If for the key already an entry exists, it will be overwritten.
{
if (doHas(key))
{
doRemove(key);
}
KeyValueArgs<TKey, TValue> args(key, val);
Add.notify(this, args);
_data.insert(std::make_pair(key, SharedPtr<TValue>(new TValue(val))));
doReplace();
}
void doRemove(const TKey& key)
/// Removes an entry from the cache. If the entry is not found
/// the remove is ignored.
{
Remove.notify(this, key);
_data.erase(key);
}
bool doHas(const TKey& key) const
/// Returns true if the cache contains a value for the key
{
// ask the strategy if the key is valid
ConstIterator it = _data.find(key);
bool result = false;
if (it != _data.end())
{
ValidArgs<TKey> args(key);
IsValid.notify(this, args);
result = args.isValid();
}
return result;
}
SharedPtr<TValue> doGet(const TKey& key)
/// Returns a SharedPtr of the cache entry, returns 0 if for
/// the key no value was found
{
Iterator it = _data.find(key);
SharedPtr<TValue> result;
if (it != _data.end())
{
// inform all strategies that a read-access to an element happens
Get.notify(this, key);
// ask all strategies if the key is valid
ValidArgs<TKey> args(key);
IsValid.notify(this, args);
if (!args.isValid())
{
doRemove(key);
}
else
{
result = it->second;
}
}
return result;
}
void doClear()
{
static EventArgs _emptyArgs;
Clear.notify(this, _emptyArgs);
_data.clear();
}
void doReplace()
{
std::set<TKey> delMe;
Replace.notify(this, delMe);
// delMe contains the to be removed elements
typename std::set<TKey>::const_iterator it = delMe.begin();
typename std::set<TKey>::const_iterator endIt = delMe.end();
for (it; it != endIt; ++it)
{
doRemove(*it);
}
}
TStrategy _strategy;
mutable DataHolder _data;
mutable FastMutex _mutex;
private:
AbstractCache(const AbstractCache& aCache);
AbstractCache& operator = (const AbstractCache& aCache);
};
Foundation_END
#endif

View File

@ -0,0 +1,79 @@
//
// AbstractDelegate.h
//
// $Id: //poco/1.1.0/Foundation/include/Foundation/AbstractDelegate.h#2 $
//
// Library: Foundation
// Package: Events
// Module: AbstractDelegate
//
// Implementation of the AbstractDelegate template.
//
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#ifndef Foundation_AbstractDelegate_INCLUDED
#define Foundation_AbstractDelegate_INCLUDED
#include "Foundation/Foundation.h"
Foundation_BEGIN
template <class TArgs>
class AbstractDelegate
/// Interface for Delegate and Expire
/// Very similar to AbstractPriorityDelegate but having two separate files (no inheritance)
/// allows one to have compile-time checks when registering an observer
/// instead of run-time checks.
{
public:
AbstractDelegate()
{
}
virtual ~AbstractDelegate()
{
}
virtual bool notify(const void* sender, TArgs& arguments) = 0;
/// Returns false, if the Delegate is no longer valid, thus indicating an expire
virtual AbstractDelegate* clone() const = 0;
/// Returns a deep-copy of the AbstractDelegate
virtual bool operator < (const AbstractDelegate<TArgs>& other) const = 0;
/// For comparing AbstractDelegates in a collection.
};
Foundation_END
#endif

View File

@ -0,0 +1,301 @@
//
// AbstractEvent.h
//
// $Id: //poco/1.1.0/Foundation/include/Foundation/AbstractEvent.h#2 $
//
// Library: Foundation
// Package: Events
// Module: AbstractEvent
//
// Definition of the AbstractEvent class.
//
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#ifndef Foundation_AbstractFoundation_INCLUDED
#define Foundation_AbstractFoundation_INCLUDED
#include "Foundation/Foundation.h"
#include "Foundation/SingletonHolder.h"
#include "Foundation/SharedPtr.h"
#include "Foundation/ActiveResult.h"
#include "Foundation/ActiveMethod.h"
#include "Foundation/ScopedLock.h"
#include "Foundation/Mutex.h"
Foundation_BEGIN
template <class TArgs, class TStrategy, class TDelegate>
class AbstractEvent
/// An abstractEvent is the super-class of all events.
/// It works similar to the way C# handles notifications (aka events in C#).
/// Events can be used to send information to a set of observers
/// which are registered at the event. The type of the data is specified with
/// the template parameter TArgs. The TStrategy parameter must be a subclass
/// of NotificationStrategy. The parameter TDelegate can either be a subclass of AbstractDelegate
/// or of PriorityAbstractDelegate.
///
/// Note that AbstractEvent should never be used directly. One ought to use
/// one of its subclasses which set the TStrategy and TDelegate template parameters
/// to fixed values. For most use-cases the BasicEvent template will be sufficient.
///
/// Use events by adding them as public members to the object which is throwing notifications:
///
/// class MyData
/// {
/// public:
/// Foundation::BasicEvent<int> AgeChanged;
///
/// MyData();
/// ...
/// };
///
/// Throwing the event can be done either by the events notify or notifyAsync method:
///
/// void MyData::setAge(int i)
/// {
/// this->_age = i;
/// AgeChanged.notify(this, this->_age);
/// }
///
/// Note that notify and notifyAsync do not catch exceptions, i.e. in case a delegate
/// throws an exception, the notify is immediately aborted and the exception is thrown
/// back to the caller.
///
/// Delegates can register methods at the event. In the case of a BasicEvent or FIFOEvent
/// the Delegate template is used, in case of an PriorityEvent a PriorityDelegate is used.
/// Mixing of observers, e.g. using a PriorityDelegate with a BasicEvent is not possible and
/// checked for during compile time.
/// Events require the observers to follow the following method signature:
///
/// void onEvent(const void* pSender, TArgs& args);
///
/// For performance reasons arguments are always sent by reference. This also allows observers
/// to modify the sent argument. To prevent that, use <const TArg> as template
/// parameter. A non-conformant method signature leads to compile errors.
///
/// Assuming that the observer meets the method signature requirement, it can register
/// this method with the += operator:
///
/// class MyController
/// {
/// protected:
/// MyData _data;
///
/// void onDataChanged(void* pSender, int& data);
/// ...
/// };
///
/// MyController::MyController()
/// {
/// _data.AgeChanged += Delegate<MyController, int>(this, &MyController::onDataChanged);
/// }
///
/// In some cases it might be desirable to work with automatically expiring registrations:
///
/// _data.DataChanged += Expire<int>(Delegate<MyController, int>(this, &MyController::onDataChanged), 1000);
///
/// This will add a delegate to the event which will automatically be removed in 1000 millisecs.
///
/// Unregistering happens via the -= operator. Forgetting to unregister a method will lead to
/// segmentation faults later, when one tries to send a notify to a no longer existing object.
///
/// MyController::~MyController()
/// {
/// _data.DataChanged -= Delegate<MyController, int>(this, &MyController::onDataChanged);
/// }
///
/// For further examples refer to the event testsuites.
{
public:
AbstractEvent():
_enabled(true),
_executeAsync(this, &AbstractEvent::executeAsyncImpl)
{
}
AbstractEvent(const TStrategy& strat):
_enabled(true),
_strategy(strat),
_executeAsync(this, &AbstractEvent::executeAsyncImpl)
{
}
virtual ~AbstractEvent()
{
}
void operator += (const TDelegate& aDelegate)
/// Adds a delegate to the event. If the observer is equal to an
/// already existing one (determined by the < operator),
/// it will simply replace the existing observer.
/// This behavior is determined by the TStrategy. Current implementations
/// (DefaultStrategy, FIFOStrategy) follow that guideline but future ones
/// can deviate.
{
FastMutex::ScopedLock lock(_mutex);
_strategy.add(aDelegate);
}
void operator -= (const TDelegate& aDelegate)
/// Removes a delegate from the event. If the delegate is equal to an
/// already existing one is determined by the < operator.
/// If the observer is not found, the unregister will be ignored
{
FastMutex::ScopedLock lock(_mutex);
_strategy.remove(aDelegate);
}
void notify(const void* pSender, TArgs& args)
/// Sends a notification to all registered delegates. The order is
/// determined by the TStrategy. This method is blocking. While executing,
/// other objects can change the list of delegates. These changes don't
/// influence the current active notifications but are activated with
/// the next notify. If one of the delegates throws an exception, the notify
/// method is immediately aborted and the exception is reported to the caller.
{
Foundation::SharedPtr<TStrategy> ptrStrat;
bool enabled = false;
{
FastMutex::ScopedLock lock(_mutex);
enabled = _enabled;
if (_enabled)
{
// thread-safeness:
// copy should be faster and safer than blocking until
// execution ends
ptrStrat = new TStrategy(_strategy);
}
}
if (enabled)
{
ptrStrat->notify(pSender, args);
}
}
Foundation::ActiveResult<TArgs> notifyAsync(const void* pSender, const TArgs& args)
/// Sends a notification to all registered delegates. The order is
/// determined by the TStrategy. This method is not blocking and will
/// immediately return. The delegates are invoked in a seperate thread.
/// Call activeResult.wait() to wait until the notification has ended.
/// While executing, other objects can change the delegate list. These changes don't
/// influence the current active notifications but are activated with
/// the next notify. If one of the delegates throws an exception, the execution
/// is aborted and the exception is reported to the caller.
{
NotifyAsyncParams params;
{
FastMutex::ScopedLock lock(_mutex);
// thread-safeness:
// copy should be faster and safer than blocking until
// execution ends
// make a copy of the strategy here to guarantee that
// between notifyAsync and the execution of the method no changes can occur
params.ptrStrat = Foundation::SharedPtr<TStrategy>(new TStrategy(_strategy));
params.pSender = pSender;
params.args = args;
params.enabled = _enabled;
}
Foundation::ActiveResult<TArgs> result = _executeAsync(params);
return result;
}
void enable()
/// Enables the event
{
FastMutex::ScopedLock lock(_mutex);
_enabled = true;
}
void disable()
/// Disables the event. notify and notifyAsnyc will be ignored,
/// but adding/removing delegates is still allowed.
{
FastMutex::ScopedLock lock(_mutex);
_enabled = false;
}
bool isEnabled() const
{
FastMutex::ScopedLock lock(_mutex);
return _enabled;
}
void clear()
/// Removes all delegates.
{
FastMutex::ScopedLock lock(_mutex);
_strategy.clear();
}
protected:
struct NotifyAsyncParams
{
Foundation::SharedPtr<TStrategy> ptrStrat;
const void* pSender;
TArgs args;
bool enabled;
};
Foundation::ActiveMethod<TArgs, NotifyAsyncParams, AbstractEvent> _executeAsync;
TArgs executeAsyncImpl(const NotifyAsyncParams& par)
{
if (!par.enabled)
{
return par.args;
}
NotifyAsyncParams params = par;
TArgs retArgs = params.args;
params.ptrStrat->notify(params.pSender, retArgs);
return retArgs;
}
TStrategy _strategy; /// The strategy used to notify observers.
bool _enabled; /// Stores if an event is enabled. Notfies on disabled events have no effect
/// but it is possible to change the observers.
mutable Foundation::FastMutex _mutex;
private:
AbstractEvent(const AbstractEvent& other);
AbstractEvent& operator = (const AbstractEvent& other);
};
Foundation_END
#endif

View File

@ -0,0 +1,79 @@
//
// AbstractPriorityDelegate.h
//
// $Id: //poco/1.1.0/Foundation/include/Foundation/AbstractPriorityDelegate.h#2 $
//
// Library: Foundation
// Package: Events
// Module: AbstractPriorityDelegate
//
// Implementation of the AbstractPriorityDelegate template.
//
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#ifndef Foundation_AbstractPriorityDelegate_INCLUDED
#define Foundation_AbstractPriorityDelegate_INCLUDED
#include "Foundation/Foundation.h"
Foundation_BEGIN
template <class TArgs>
class AbstractPriorityDelegate
/// Interface for PriorityDelegate and PriorityExpire.
/// Very similar to AbstractDelegate but having two separate files (no inheritance)
/// allows to have compile-time checks when registering an observer
/// instead of run-time checks.
{
public:
AbstractPriorityDelegate()
{
}
virtual ~AbstractPriorityDelegate()
{
}
virtual bool notify(const void* sender, TArgs & arguments) = 0;
/// Returns false, if the Delegate is no longer valid, thus indicating an expire
virtual AbstractPriorityDelegate* clone() const = 0;
// Returns a deep-copy of the object.
virtual bool operator < (const AbstractPriorityDelegate<TArgs>& other) const = 0;
/// Operator used for comparing AbstractPriorityDelegates in a collection.
};
Foundation_END
#endif

View File

@ -0,0 +1,91 @@
//
// AbstractStrategy.h
//
// $Id: //poco/1.1.0/Foundation/include/Foundation/AbstractStrategy.h#2 $
//
// Library: Foundation
// Package: Cache
// Module: AbstractCache
//
// Definition of the AbstractStrategy class.
//
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#ifndef Foundation_AbstractStrategy_INCLUDED
#define Foundation_AbstractStrategy_INCLUDED
#include "Foundation/KeyValueArgs.h"
#include "Foundation/ValidArgs.h"
#include "Foundation/EventArgs.h"
Foundation_BEGIN
template <class TKey, class TValue>
class AbstractStrategy
/// An AbstractStrategy is the interface for all strategies.
{
public:
AbstractStrategy()
{
}
virtual ~AbstractStrategy()
{
}
virtual void onAdd(const void* pSender, const KeyValueArgs <TKey, TValue>& key) = 0;
/// Adds the key to the strategy.
/// If for the key already an entry exists, an excpetion will be thrown.
virtual void onRemove(const void* pSender, const TKey& key) = 0;
/// Removes an entry from the strategy. If the entry is not found
/// the remove is ignored.
virtual void onGet(const void* pSender, const TKey& key) = 0;
/// Informs the strategy that a read-access happens to an element.
virtual void onClear(const void* pSender, const EventArgs& args) = 0;
/// Removes all elements from the cache.
virtual void onIsValid(const void* pSender, ValidArgs<TKey>& key) = 0;
/// Used to query if a key is still valid (i.e. cached).
virtual void onReplace(const void* pSender, std::set<TKey>& elemsToRemove) = 0;
/// Used by the Strategy to indicate which elements should be removed from
/// the cache. Note that onReplace does not change the current list of keys.
/// The cache object is reponsible to remove the elements.
};
Foundation_END
#endif

View File

@ -0,0 +1,180 @@
//
// ActiveMethod.h
//
// $Id: //poco/1.1.0/Foundation/include/Foundation/ActiveMethod.h#2 $
//
// Library: Foundation
// Package: Threading
// Module: ActiveObjects
//
// Definition of the ActiveMethod class.
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#ifndef Foundation_ActiveMethod_INCLUDED
#define Foundation_ActiveMethod_INCLUDED
#ifndef Foundation_Foundation_INCLUDED
#include "Foundation/Foundation.h"
#endif
#ifndef Foundation_ActiveResult_INCLUDED
#include "Foundation/ActiveResult.h"
#endif
#ifndef Foundation_Runnable_INCLUDED
#include "Foundation/Runnable.h"
#endif
#ifndef Foundation_ThreadPool_INCLUDED
#include "Foundation/ThreadPool.h"
#endif
#ifndef Foundation_Exception_INCLUDED
#include "Foundation/Exception.h"
#endif
Foundation_BEGIN
template <class ResultType, class ArgType, class OwnerType>
class ActiveRunnable: public Runnable
/// This class is used by ActiveMethod.
/// See the ActiveMethod class for more information.
{
public:
typedef ResultType (OwnerType::*Callback)(const ArgType&);
typedef ActiveResult<ResultType> ActiveResultType;
ActiveRunnable(OwnerType* pOwner, Callback method, const ArgType& arg, const ActiveResultType& result):
_pOwner(pOwner),
_method(method),
_arg(arg),
_result(result)
{
poco_check_ptr (pOwner);
}
void run()
{
try
{
_result.data() = (_pOwner->*_method)(_arg);
}
catch (Exception& e)
{
_result.error(e.message());
}
catch (std::exception& e)
{
_result.error(e.what());
}
catch (...)
{
_result.error("unknown exception");
}
_result.notify();
delete this;
}
private:
OwnerType* _pOwner;
Callback _method;
ArgType _arg;
ActiveResultType _result;
};
template <class ResultType, class ArgType, class OwnerType>
class ActiveMethod
/// An active method is a method that, when called, executes
/// in its own thread. ActiveMethod's take exactly one
/// argument and can return a value. To pass more than one
/// argument to the method, use a struct.
/// The following example shows how to add an ActiveMethod
/// to a class:
///
/// class ActiveObject
/// {
/// public:
/// ActiveObject():
/// exampleActiveMethod(this, &ActiveObject::exampleActiveMethodImpl)
/// {
/// }
///
/// ActiveMethod<std::string, std::string, ActiveObject> exampleActiveMethod;
///
/// protected:
/// std::string exampleActiveMethodImpl(const std::string& arg)
/// {
/// ...
/// }
/// };
///
/// And following is an example that shows how to invoke an ActiveMethod.
///
/// ActiveObject myActiveObject;
/// ActiveResult<std::string> result = myActiveObject.exampleActiveMethod("foo");
/// ...
/// result.wait();
/// std::cout << result.data() << std::endl;
{
public:
typedef ResultType (OwnerType::*Callback)(const ArgType&);
typedef ActiveResult<ResultType> ActiveResultType;
typedef ActiveRunnable<ResultType, ArgType, OwnerType> ActiveRunnableType;
ActiveMethod(OwnerType* pOwner, Callback method):
_pOwner(pOwner),
_method(method)
/// Creates an ActiveMethod object.
{
poco_check_ptr (pOwner);
}
ActiveResultType operator () (const ArgType& arg)
/// Invokes the ActiveMethod.
{
ActiveResultType result(new ActiveResultHolder<ResultType>());
ActiveRunnableType* pRunnable = new ActiveRunnableType(_pOwner, _method, arg, result);
ThreadPool::defaultPool().start(*pRunnable);
return result;
}
private:
ActiveMethod();
ActiveMethod(const ActiveMethod&);
ActiveMethod& operator = (const ActiveMethod&);
OwnerType* _pOwner;
Callback _method;
};
Foundation_END
#endif // Foundation_ActiveMethod_INCLUDED

View File

@ -0,0 +1,266 @@
//
// ActiveResult.h
//
// $Id: //poco/1.1.0/Foundation/include/Foundation/ActiveResult.h#2 $
//
// Library: Foundation
// Package: Threading
// Module: ActiveObjects
//
// Definition of the ActiveResult class.
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#ifndef Foundation_ActiveResult_INCLUDED
#define Foundation_ActiveResult_INCLUDED
#ifndef Foundation_Foundation_INCLUDED
#include "Foundation/Foundation.h"
#endif
#ifndef Foundation_Mutex_INCLUDED
#include "Foundation/Mutex.h"
#endif
#ifndef Foundation_Event_INCLUDED
#include "Foundation/Event.h"
#endif
#ifndef Foundation_RefCountedObject_INCLUDED
#include "Foundation/RefCountedObject.h"
#endif
Foundation_BEGIN
template <class ResultType>
class ActiveResultHolder: public RefCountedObject
/// This class holds the result of an asynchronous method
/// invocation. It is used to pass the result from the
/// execution thread back to the invocation thread.
/// The class uses reference counting for memory management.
/// Do not use this class directly, use ActiveResult instead.
{
public:
ActiveResultHolder():
_failed(false),
_event(false)
/// Creates an ActiveResultHolder.
{
}
ResultType& data()
/// Returns a reference to the actual result.
{
return _data;
}
void wait()
/// Pauses the caller until the result becomes available.
{
_event.wait();
}
bool tryWait(long milliseconds)
/// Waits up to the specified interval for the result to
/// become available. Returns true if the result became
/// available, false otherwise.
{
return _event.tryWait(milliseconds);
}
void wait(long milliseconds)
/// Waits up to the specified interval for the result to
/// become available. Throws a TimeoutException if the
/// result did not became available.
{
_event.wait(milliseconds);
}
void notify()
/// Notifies the invoking thread that the result became available.
{
_event.set();
}
bool failed() const
/// Returns true if the active method failed (and threw an exception).
/// Information about the exception can be obtained by calling error().
{
return _failed;
}
const std::string& error() const
/// If the active method threw an exception, a textual representation
/// of the exception is returned. An empty string is returned if the
/// active method completed successfully.
{
return _error;
}
void error(const std::string& msg)
/// Sets the failed flag and the exception message.
{
_error = msg;
_failed = true;
}
protected:
~ActiveResultHolder()
{
}
private:
ResultType _data;
std::string _error;
bool _failed;
Event _event;
};
template <class RT>
class ActiveResult
/// This class holds the result of an asynchronous method
/// invocation (see class ActiveMethod). It is used to pass the
/// result from the execution thread back to the invocation thread.
{
public:
typedef RT ResultType;
typedef ActiveResultHolder<ResultType> ActiveResultHolderType;
ActiveResult(ActiveResultHolderType* pHolder):
_pHolder(pHolder)
/// Creates the active result. For internal use only.
{
poco_check_ptr (pHolder);
}
ActiveResult(const ActiveResult& result)
/// Copy constructor.
{
_pHolder = result._pHolder;
_pHolder->duplicate();
}
~ActiveResult()
/// Destroys the result.
{
_pHolder->release();
}
ActiveResult& operator = (const ActiveResult& result)
/// Assignment operator.
{
if (&result != this)
{
_pHolder->release();
_pHolder = result._pHolder;
_pHolder->duplicate();
}
return *this;
}
const ResultType& data() const
/// Returns a reference to the result data.
{
return _pHolder->data();
}
void wait()
/// Pauses the caller until the result becomes available.
{
_pHolder->wait();
}
bool tryWait(long milliseconds)
/// Waits up to the specified interval for the result to
/// become available. Returns true if the result became
/// available, false otherwise.
{
return _pHolder->tryWait(milliseconds);
}
void wait(long milliseconds)
/// Waits up to the specified interval for the result to
/// become available. Throws a TimeoutException if the
/// result did not became available.
{
_pHolder->wait(milliseconds);
}
bool available() const
/// Returns true if a result is available.
{
return _pHolder->tryWait(0);
}
bool failed() const
/// Returns true if the active method failed (and threw an exception).
/// Information about the exception can be obtained by calling error().
{
return _pHolder->failed();
}
const std::string& error() const
/// If the active method threw an exception, a textual representation
/// of the exception is returned. An empty string is returned if the
/// active method completed successfully.
{
return _pHolder->error();
}
void notify()
/// Notifies the invoking thread that the result became available.
/// For internal use only.
{
_pHolder->notify();
}
ResultType& data()
/// Returns a non-const reference to the result data. For internal
/// use only.
{
return _pHolder->data();
}
void error(const std::string& msg)
/// Sets the failed flag and the exception message.
{
_pHolder->error(msg);
}
private:
ActiveResult();
ActiveResultHolderType* _pHolder;
};
Foundation_END
#endif // Foundation_ActiveResult_INCLUDED

View File

@ -0,0 +1,228 @@
//
// Activity.h
//
// $Id: //poco/1.1.0/Foundation/include/Foundation/Activity.h#2 $
//
// Library: Foundation
// Package: Threading
// Module: ActiveObjects
//
// Definition of the Activity template class.
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#ifndef Foundation_Activity_INCLUDED
#define Foundation_Activity_INCLUDED
#ifndef Foundation_Foundation_INCLUDED
#include "Foundation/Foundation.h"
#endif
#ifndef Foundation_RunnableAdapter_INCLUDED
#include "Foundation/RunnableAdapter.h"
#endif
#ifndef Foundation_ThreadPool_INCLUDED
#include "Foundation/ThreadPool.h"
#endif
#ifndef Foundation_Event_INCLUDED
#include "Foundation/Event.h"
#endif
#ifndef Foundation_Mutex_INCLUDED
#include "Foundation/Mutex.h"
#endif
Foundation_BEGIN
template <class C>
class Activity: public Runnable
/// This template class helps to implement active objects.
/// An active object uses threads to decouple method
/// execution from method invocation, or to perform tasks
/// autonomously, without intervention of a caller.
///
/// An activity is a (typically longer running) method
/// that executes within its own task. Activities can
/// be started automatically (upon object construction)
/// or manually at a later time. Activities can also
/// be stopped at any time. However, to make stopping
/// an activity work, the method implementing the
/// activity has to check periodically whether it
/// has been requested to stop, and if so, return.
/// Activities are stopped before the object they belong to is
/// destroyed. Methods implementing activities cannot have arguments
/// or return values.
///
/// Activity objects are used as follows:
///
/// class ActiveObject
/// {
/// public:
/// ActiveObject():
/// _activity(this, &ActiveObject::runActivity)
/// {
/// ...
/// }
///
/// ...
///
/// protected:
/// void runActivity()
/// {
/// while (!_activity.isStopped())
/// {
/// ...
/// }
/// }
///
/// private:
/// Activity<ActiveObject> _activity;
/// };
{
public:
typedef RunnableAdapter<C> RunnableAdapterType;
typedef typename RunnableAdapterType::Callback Callback;
Activity(C* pOwner, Callback method):
_pOwner(pOwner),
_runnable(*pOwner, method),
_stopped(true),
_running(false),
_done(false)
/// Creates the activity. Call start() to
/// start it.
{
poco_check_ptr (pOwner);
}
~Activity()
/// Stops and destroys the activity.
{
stop();
wait();
}
void start()
/// Starts the activity by acquiring a
/// thread for it from the default thread pool.
{
FastMutex::ScopedLock lock(_mutex);
if (_stopped)
{
_done.reset();
_stopped = false;
_running = true;
try
{
ThreadPool::defaultPool().start(*this);
}
catch (...)
{
_running = false;
throw;
}
}
}
void stop()
/// Requests to stop the activity.
{
FastMutex::ScopedLock lock(_mutex);
_stopped = true;
}
void wait()
/// Waits for the activity to complete.
{
if (_running)
{
_done.wait();
}
}
void wait(long milliseconds)
/// Waits the given interval for the activity to complete.
/// An TimeoutException is thrown if the activity does not
/// complete within the given interval.
{
if (_running)
{
_done.wait(milliseconds);
}
}
bool isStopped() const
/// Returns true if the activity has been requested to stop.
{
return _stopped;
}
bool isRunning() const
/// Returns true if the activity is running.
{
return _running;
}
protected:
void run()
{
try
{
_runnable.run();
}
catch (...)
{
_running = false;
_done.set();
throw;
}
_running = false;
_done.set();
}
private:
Activity();
Activity(const Activity&);
Activity& operator = (const Activity&);
C* _pOwner;
RunnableAdapterType _runnable;
volatile bool _stopped;
volatile bool _running;
Event _done;
FastMutex _mutex;
};
Foundation_END
#endif // Foundation_Activity_INCLUDED

View File

@ -0,0 +1,278 @@
//
// Any.h
//
// $Id: //poco/1.1.0/Foundation/include/Foundation/Any.h#1 $
//
// Library: Foundation
// Package: Core
// Module: Any
//
// Copyright Kevlin Henney, 2000, 2001, 2002. All rights reserved.
//
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// what: variant type boost::any
// who: contributed by Kevlin Henney,
// with features contributed and bugs found by
// Ed Brey, Mark Rodgers, Peter Dimov, and James Curran
// when: July 2001
// where: tested with BCC 5.5, MSVC 6.0, and g++ 2.95
// modified: extracted from Boost 1.33.1 lib and adapted for poco: Peter Schojer/AppliedInformatics 2006-02-02
//
#ifndef Foundation_Any_INCLUDED
#define Foundation_Any_INCLUDED
#include "Foundation/Exception.h"
#include <algorithm>
#include <typeinfo>
Foundation_BEGIN
class Any
/// An Any class represents a general type and is capable of storing any type, supporting type-safe extraction
/// of the internally stored data.
///
/// Code taken from the Boost 1.33.1 library. Original copyright by Kevlin Henney. Modified for Poco
/// by Applied Informatics. This file is under the BOOST license, see http://www.boost.org/LICENSE_1_0.txt
{
public:
Any():
_content(0)
/// Creates an empty any type.
{
}
template<typename ValueType>
Any(const ValueType& value):
_content(new Holder<ValueType>(value))
/// Creates an any which stores the init parameter inside.
///
/// Example:
/// Any a(13);
/// Any a(string("12345"));
{
}
Any(const Any& other):
_content(other._content ? other._content->clone() : 0)
/// Copy constructor, works with empty Anys and initialized Any values.
{
}
~Any()
{
delete _content;
}
Any& swap(Any& rhs)
/// Swaps the content of the two Anys.
{
std::swap(_content, rhs._content);
return *this;
}
template<typename ValueType>
Any& operator = (const ValueType& rhs)
/// Assignment operator for all types != Any.
///
/// Example:
/// Any a = 13;
/// Any a = string("12345");
{
Any(rhs).swap(*this);
return *this;
}
Any& operator = (const Any& rhs)
/// Assignment operator for Any.
{
Any(rhs).swap(*this);
return *this;
}
bool empty() const
/// returns true if the Any is empty
{
return !_content;
}
const std::type_info& type() const
/// Returns the type information of the stored content.
/// If the Any is empty typeid(void) is returned.
/// It is suggested to always query an Any for its type info before trying to extract
/// data via an AnyCast/RefAnyCast.
{
return _content ? _content->type() : typeid(void);
}
private:
class Placeholder
{
public:
virtual ~Placeholder()
{
}
virtual const std::type_info& type() const = 0;
virtual Placeholder* clone() const = 0;
};
template<typename ValueType>
class Holder: public Placeholder
{
public:
Holder(const ValueType& value):
_held(value)
{
}
virtual const std::type_info& type() const
{
return typeid(ValueType);
}
virtual Placeholder* clone() const
{
return new Holder(_held);
}
ValueType _held;
};
private:
template<typename ValueType>
friend ValueType* AnyCast(Any*);
template<typename ValueType>
friend ValueType* UnsafeAnyCast(Any*);
Placeholder* _content;
};
template<typename ValueType>
ValueType* AnyCast(Any* operand)
/// AnyCast operator used to extract the ValueType from an Any*. Will return a pointer
/// to the stored value.
///
/// Example Usage:
/// MyType* pTmp = AnyCast<MyType*>(pAny).
/// Will return NULL if the cast fails, i.e. types don't match.
{
return operand && operand->type() == typeid(ValueType)
? &static_cast<Any::Holder<ValueType>*>(operand->_content)->_held
: 0;
}
template<typename ValueType>
const ValueType* AnyCast(const Any* operand)
/// AnyCast operator used to extract a const ValueType pointer from an const Any*. Will return a const pointer
/// to the stored value.
///
/// Example Usage:
/// const MyType* pTmp = AnyCast<MyType*>(pAny).
/// Will return NULL if the cast fails, i.e. types don't match.
{
return AnyCast<ValueType>(const_cast<Any*>(operand));
}
template<typename ValueType>
ValueType AnyCast(const Any& operand)
/// AnyCast operator used to extract a copy of the ValueType from an const Any&.
///
/// Example Usage:
/// MyType tmp = AnyCast<MyType>(anAny).
/// Will throw a Foundation::BadCastException if the cast fails.
/// Dont use an AnyCast in combination with references, i.e. MyType& tmp = ... or const MyType& = ...
/// Some compilers will accept this code although a copy is returned. Use the RefAnyCast in
/// these cases.
{
ValueType* result = AnyCast<ValueType>(const_cast<Any*>(&operand));
if(!result)
throw BadCastException("Failed to convert between const Any types");
return *result;
}
template<typename ValueType>
ValueType AnyCast(Any& operand)
/// AnyCast operator used to extract a copy of the ValueType from an Any&.
///
/// Example Usage:
/// MyType tmp = AnyCast<MyType>(anAny).
/// Will throw a Foundation::BadCastException if the cast fails.
/// Dont use an AnyCast in combination with references, i.e. MyType& tmp = ... or const MyType& tmp = ...
/// Some compilers will accept this code although a copy is returned. Use the RefAnyCast in
/// these cases.
{
ValueType* result = AnyCast<ValueType>(&operand);
if(!result)
throw BadCastException("Failed to convert between Any types");
return *result;
}
template<typename ValueType>
const ValueType& RefAnyCast(const Any & operand)
/// AnyCast operator used to return a const reference to the internal data.
///
/// Example Usage:
/// const MyType& tmp = RefAnyCast<MyType>(anAny);
{
ValueType* result = AnyCast<ValueType>(const_cast<Any*>(&operand));
if(!result)
throw BadCastException("RefAnyCast: Failed to convert between const Any types");
return *result;
}
template<typename ValueType>
ValueType& RefAnyCast(Any& operand)
/// AnyCast operator used to return a reference to the internal data.
///
/// Example Usage:
/// MyType& tmp = RefAnyCast<MyType>(anAny);
{
ValueType* result = AnyCast<ValueType>(&operand);
if(!result)
throw BadCastException("RefAnyCast: Failed to convert between Any types");
return *result;
}
template<typename ValueType>
ValueType* UnsafeAnyCast(Any* operand)
/// The "unsafe" versions of AnyCast are not part of the
/// public interface and may be removed at any time. They are
/// required where we know what type is stored in the any and can't
/// use typeid() comparison, e.g., when our types may travel across
/// different shared libraries.
{
return &static_cast<Any::Holder<ValueType>*>(operand->_content)->_held;
}
template<typename ValueType>
const ValueType* UnsafeAnyCast(const Any* operand)
/// The "unsafe" versions of AnyCast are not part of the
/// public interface and may be removed at any time. They are
/// required where we know what type is stored in the any and can't
/// use typeid() comparison, e.g., when our types may travel across
/// different shared libraries.
{
return AnyCast<ValueType>(const_cast<Any*>(operand));
}
Foundation_END
#endif

View File

@ -0,0 +1,133 @@
//
// ArchiveStrategy.h
//
// $Id: //poco/1.1.0/Foundation/include/Foundation/ArchiveStrategy.h#2 $
//
// Library: Foundation
// Package: Logging
// Module: FileChannel
//
// Definition of the ArchiveStrategy class and subclasses.
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#ifndef Foundation_ArchiveStrategy_INCLUDED
#define Foundation_ArchiveStrategy_INCLUDED
#ifndef Foundation_Foundation_INCLUDED
#include "Foundation/Foundation.h"
#endif
#ifndef Foundation_LogFile_INCLUDED
#include "Foundation/LogFile.h"
#endif
#ifndef Foundation_File_INCLUDED
#include "Foundation/File.h"
#endif
#ifndef Foundation_DateTimeFormatter_INCLUDED
#include "Foundation/DateTimeFormatter.h"
#endif
Foundation_BEGIN
class Foundation_API ArchiveStrategy
/// The ArchiveStrategy is used by FileChannel
/// to rename a rotated log file for archiving.
///
/// Archived files can be automatically compressed,
/// using the gzip file format.
{
public:
ArchiveStrategy();
virtual ~ArchiveStrategy();
virtual LogFile* archive(LogFile* pFile) = 0;
/// Renames the given log file for archiving
/// and creates and returns a new log file.
/// The given LogFile object is deleted.
void compress(bool flag = true);
/// Enables or disables compression of archived files.
protected:
void moveFile(const std::string& oldName, const std::string& newName);
bool exists(const std::string& name);
private:
ArchiveStrategy(const ArchiveStrategy&);
ArchiveStrategy& operator = (const ArchiveStrategy&);
bool _compress;
};
class Foundation_API ArchiveByNumberStrategy: public ArchiveStrategy
/// A monotonic increasing number is appended to the
/// log file name. The most recent archived file
/// always has the number zero.
{
public:
ArchiveByNumberStrategy();
~ArchiveByNumberStrategy();
LogFile* archive(LogFile* pFile);
};
template<class DT>
class ArchiveByTimestampStrategy: public ArchiveStrategy
/// A timestamp (YYYYMMDDhhmmss) is appended to archived
/// log files.
{
public:
ArchiveByTimestampStrategy()
{
}
~ArchiveByTimestampStrategy()
{
}
LogFile* archive(LogFile* pFile)
{
std::string path = pFile->path();
delete pFile;
std::string archPath = path;
archPath.append(".");
archPath.append(DateTimeFormatter::format(DT().timestamp(), "%Y%m%d%H%M%S"));
moveFile(path, archPath);
return new LogFile(path);
}
};
Foundation_END
#endif // Foundation_ArchiveStrategy_INCLUDED

View File

@ -0,0 +1,122 @@
//
// AsyncChannel.h
//
// $Id: //poco/1.1.0/Foundation/include/Foundation/AsyncChannel.h#2 $
//
// Library: Foundation
// Package: Logging
// Module: AsyncChannel
//
// Definition of the AsyncChannel class.
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#ifndef Foundation_AsyncChannel_INCLUDED
#define Foundation_AsyncChannel_INCLUDED
#ifndef Foundation_Foundation_INCLUDED
#include "Foundation/Foundation.h"
#endif
#ifndef Foundation_Channel_INCLUDED
#include "Foundation/Channel.h"
#endif
#ifndef Foundation_Thread_INCLUDED
#include "Foundation/Thread.h"
#endif
#ifndef Foundation_Mutex_INCLUDED
#include "Foundation/Mutex.h"
#endif
#ifndef Foundation_Runnable_INCLUDED
#include "Foundation/Runnable.h"
#endif
#ifndef Foundation_NotificationQueue_INCLUDED
#include "Foundation/NotificationQueue.h"
#endif
Foundation_BEGIN
class Foundation_API AsyncChannel: public Channel, public Runnable
/// A channel uses a separate thread for logging.
///
/// Using this channel can help to improve the performance of
/// applications that produce huge amounts of log messages or
/// that write log messages to multiple channels simultaneously.
///
/// All log messages are put into a queue and this queue is
/// then processed by a separate thread.
{
public:
AsyncChannel(Channel* pChannel = 0);
/// Creates the AsyncChannel and connects it to
/// the given channel.
void setChannel(Channel* pChannel);
/// Connects the AsyncChannel to the given target channel.
/// All messages will be forwarded to this channel.
Channel* getChannel() const;
/// Returns the target channel.
void open();
/// Opens the channel and creates the
/// background ;ogging thread.
void close();
/// Closes the channel and stops the background
/// logging thread.
void log(const Message& msg);
/// Queues the message for processing by the
/// background thread.
void setProperty(const std::string& name, const std::string& value);
/// Sets or changes a configuration property.
///
/// Only the "channel" property is supported, which allows
/// setting the target channel via the LoggingRegistry.
/// The "channel" property is set-only.
protected:
~AsyncChannel();
void run();
private:
Channel* _pChannel;
Thread _thread;
FastMutex _mutex;
NotificationQueue _queue;
};
Foundation_END
#endif // Foundation_AsyncChannel_INCLUDED

View File

@ -0,0 +1,321 @@
//
// AutoPtr.h
//
// $Id: //poco/1.1.0/Foundation/include/Foundation/AutoPtr.h#2 $
//
// Library: Foundation
// Package: Core
// Module: AutoPtr
//
// Definition of the AutoPtr template class.
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#ifndef Foundation_AutoPtr_INCLUDED
#define Foundation_AutoPtr_INCLUDED
#ifndef Foundation_Foundation_INCLUDED
#include "Foundation/Foundation.h"
#endif
#ifndef Foundation_Exception_INCLUDED
#include "Foundation/Exception.h"
#endif
#ifndef STD_ALGORITHM_INCLUDED
#include <algorithm>
#define STD_ALGORITHM_INCLUDED
#endif
Foundation_BEGIN
template <class C>
class AutoPtr
/// AutoPtr is a "smart" pointer for classes implementing
/// reference counting based garbage collection.
/// To be usable with the AutoPtr template, a class must
/// implement the following behaviour:
/// A class must maintain a reference count.
/// The constructors of the object initialize the reference
/// count to one.
/// The class must implement a public duplicate() method:
/// void duplicate();
/// that increments the reference count by one.
/// The class must implement a public release() method:
/// void release()
/// that decrements the reference count by one, and,
/// if the reference count reaches zero, deletes the
/// class.
/// AutoPtr works in the following way:
/// If an AutoPtr is assigned an ordinary pointer to
/// an object (via the constructor or the assignment operator),
/// it takes ownership of the object and the object's reference
/// count remains unchanged.
/// If the AutoPtr is assigned another AutoPtr, the
/// object's reference count is incremented by one by
/// calling duplicate() on its object.
/// The destructor of AutoPtr calls release() on its
/// object.
/// AutoPtr supports dereferencing with both the ->
/// and the * operator. An attempt to dereference a null
/// AutoPtr results in a NullPointerException being thrown.
/// AutoPtr also implements all relational operators.
{
public:
AutoPtr(): _ptr(0)
{
}
AutoPtr(C* ptr): _ptr(ptr)
{
}
AutoPtr(C* ptr, bool shared): _ptr(ptr)
{
if (shared && _ptr) _ptr->duplicate();
}
AutoPtr(const AutoPtr& ptr): _ptr(ptr._ptr)
{
if (_ptr) _ptr->duplicate();
}
template <class Other>
AutoPtr(const AutoPtr<Other>& ptr): _ptr(const_cast<Other*>(ptr.get()))
{
if (_ptr) _ptr->duplicate();
}
~AutoPtr()
{
if (_ptr) _ptr->release();
}
AutoPtr& operator = (C* ptr)
{
if (_ptr != ptr)
{
if (_ptr) _ptr->release();
_ptr = ptr;
}
return *this;
}
AutoPtr& operator = (const AutoPtr& ptr)
{
if (&ptr != this)
{
if (_ptr) _ptr->release();
_ptr = ptr._ptr;
if (_ptr) _ptr->duplicate();
}
return *this;
}
void swap(AutoPtr& ptr)
{
std::swap(_ptr, ptr._ptr);
}
template <class Other>
AutoPtr& operator = (const AutoPtr<Other>& ptr)
{
if (ptr.get() != _ptr)
{
if (_ptr) _ptr->release();
_ptr = const_cast<Other*>(ptr.get());
if (_ptr) _ptr->duplicate();
}
return *this;
}
C* operator -> ()
{
if (_ptr)
return _ptr;
else
throw NullPointerException();
}
const C* operator -> () const
{
if (_ptr)
return _ptr;
else
throw NullPointerException();
}
C& operator * ()
{
if (_ptr)
return *_ptr;
else
throw NullPointerException();
}
const C& operator * () const
{
if (_ptr)
return *_ptr;
else
throw NullPointerException();
}
C* get()
{
return _ptr;
}
operator C* ()
{
return _ptr;
}
operator const C* () const
{
return _ptr;
}
const C* get() const
{
return _ptr;
}
C* duplicate()
{
if (_ptr) _ptr->duplicate();
return _ptr;
}
bool operator == (const AutoPtr& ptr) const
{
return _ptr == ptr._ptr;
}
bool operator == (const C* ptr) const
{
return _ptr == ptr;
}
bool operator == (C* ptr) const
{
return _ptr == ptr;
}
bool operator != (const AutoPtr& ptr) const
{
return _ptr != ptr._ptr;
}
bool operator != (const C* ptr) const
{
return _ptr != ptr;
}
bool operator != (C* ptr) const
{
return _ptr != ptr;
}
bool operator < (const AutoPtr& ptr) const
{
return _ptr < ptr._ptr;
}
bool operator < (const C* ptr) const
{
return _ptr < ptr;
}
bool operator < (C* ptr) const
{
return _ptr < ptr;
}
bool operator <= (const AutoPtr& ptr) const
{
return _ptr <= ptr._ptr;
}
bool operator <= (const C* ptr) const
{
return _ptr <= ptr;
}
bool operator <= (C* ptr) const
{
return _ptr <= ptr;
}
bool operator > (const AutoPtr& ptr) const
{
return _ptr > ptr._ptr;
}
bool operator > (const C* ptr) const
{
return _ptr > ptr;
}
bool operator > (C* ptr) const
{
return _ptr > ptr;
}
bool operator >= (const AutoPtr& ptr) const
{
return _ptr >= ptr._ptr;
}
bool operator >= (const C* ptr) const
{
return _ptr >= ptr;
}
bool operator >= (C* ptr) const
{
return _ptr >= ptr;
}
private:
C* _ptr;
};
template <class C>
inline void swap(AutoPtr<C>& p1, AutoPtr<C>& p2)
{
p1.swap(p2);
}
Foundation_END
#endif // Foundation_AutoPtr_INCLUDED

View File

@ -0,0 +1,113 @@
//
// AutoReleasePool.h
//
// $Id: //poco/1.1.0/Foundation/include/Foundation/AutoReleasePool.h#2 $
//
// Library: Foundation
// Package: Core
// Module: AutoReleasePool
//
// Definition of the AutoReleasePool class.
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#ifndef Foundation_AutoReleasePool_INCLUDED
#define Foundation_AutoReleasePool_INCLUDED
#ifndef Foundation_Foundation_INCLUDED
#include "Foundation/Foundation.h"
#endif
#ifndef STD_LIST_INCLUDED
#include <list>
#define STD_LIST_INCLUDED
#endif
Foundation_BEGIN
template <class C>
class AutoReleasePool
/// An AutoReleasePool implements simple garbage collection for
/// reference-counted objects.
/// It temporarily takes ownwership of reference-counted objects that
/// nobody else wants to take ownership of and releases them
/// at a later, appropriate point in time.
///
/// Note: The correct way to add an object hold by an AutoPtr<> to
/// an AutoReleasePool is by invoking the AutoPtr's duplicate()
/// method. Example:
/// AutoReleasePool<C> arp;
/// AutoPtr<C> ptr = new C;
/// ...
/// arp.add(ptr.duplicate());
{
public:
AutoReleasePool()
/// Creates the AutoReleasePool.
{
}
~AutoReleasePool()
/// Destroys the AutoReleasePool and releases
/// all objects it currently holds.
{
release();
}
void add(C* pObject)
/// Adds the given object to the AutoReleasePool.
/// The object's reference count is not modified
{
if (pObject)
_list.push_back(pObject);
}
void release()
/// Releases all objects the AutoReleasePool currently holds
/// by calling each object's release() method.
{
while (!_list.empty())
{
_list.front()->release();
_list.pop_front();
}
}
private:
typedef std::list<C*> ObjectList;
ObjectList _list;
};
Foundation_END
#endif // Foundation_AutoReleasePool_INCLUDED

View File

@ -0,0 +1,109 @@
//
// Base64Decoder.h
//
// $Id: //poco/1.1.0/Foundation/include/Foundation/Base64Decoder.h#2 $
//
// Library: Foundation
// Package: Streams
// Module: Base64
//
// Definition of class Base64Decoder.
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#ifndef Foundation_Base64Decoder_INCLUDED
#define Foundation_Base64Decoder_INCLUDED
#ifndef Foundation_Foundation_INCLUDED
#include "Foundation/Foundation.h"
#endif
#ifndef Foundation_UnbufferedStreamBuf_INCLUDED
#include "Foundation/UnbufferedStreamBuf.h"
#endif
#ifndef STD_ISTREAM_INCLUDED
#include <istream>
#define STD_ISTREAM_INCLUDED
#endif
Foundation_BEGIN
class Foundation_API Base64DecoderBuf: public UnbufferedStreamBuf
/// This streambuf base64-decodes all data read
/// from the istream connected to it.
{
public:
Base64DecoderBuf(std::istream& istr);
~Base64DecoderBuf();
private:
int readFromDevice();
int readOne();
unsigned char _group[3];
int _groupLength;
int _groupIndex;
std::istream& _istr;
static unsigned char IN_ENCODING[256];
static bool IN_ENCODING_INIT;
};
class Foundation_API Base64DecoderIOS: public virtual std::ios
/// The base class for Base64Decoder.
///
/// This class is needed to ensure the correct initialization
/// order of the stream buffer and base classes.
{
public:
Base64DecoderIOS(std::istream& istr);
~Base64DecoderIOS();
Base64DecoderBuf* rdbuf();
protected:
Base64DecoderBuf _buf;
};
class Foundation_API Base64Decoder: public Base64DecoderIOS, public std::istream
/// This istream base64-decodes all data
/// read from the istream connected to it.
{
public:
Base64Decoder(std::istream& istr);
~Base64Decoder();
};
Foundation_END
#endif // Foundation_Base64Decoder_INCLUDED

View File

@ -0,0 +1,119 @@
//
// Base64Encoder.h
//
// $Id: //poco/1.1.0/Foundation/include/Foundation/Base64Encoder.h#2 $
//
// Library: Foundation
// Package: Streams
// Module: Base64
//
// Definition of class Base64Encoder.
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#ifndef Foundation_Base64Encoder_INCLUDED
#define Foundation_Base64Encoder_INCLUDED
#ifndef Foundation_Foundation_INCLUDED
#include "Foundation/Foundation.h"
#endif
#ifndef Foundation_UnbufferedStreamBuf_INCLUDED
#include "Foundation/UnbufferedStreamBuf.h"
#endif
#ifndef STD_OSTREAM_INCLUDED
#include <ostream>
#define STD_OSTREAM_INCLUDED
#endif
Foundation_BEGIN
class Foundation_API Base64EncoderBuf: public UnbufferedStreamBuf
/// This streambuf base64-encodes all data written
/// to it and forwards it to a connected
/// ostream.
{
public:
Base64EncoderBuf(std::ostream& ostr);
~Base64EncoderBuf();
int close();
void setLineLength(int lineLength);
int getLineLength() const;
private:
int writeToDevice(char c);
unsigned char _group[3];
int _groupLength;
int _pos;
int _lineLength;
std::ostream& _ostr;
static const unsigned char OUT_ENCODING[64];
friend class Base64DecoderBuf;
};
class Foundation_API Base64EncoderIOS: public virtual std::ios
/// The base class for Base64Encoder.
///
/// This class is needed to ensure the correct initialization
/// order of the stream buffer and base classes.
{
public:
Base64EncoderIOS(std::ostream& ostr);
~Base64EncoderIOS();
int close();
Base64EncoderBuf* rdbuf();
protected:
Base64EncoderBuf _buf;
};
class Foundation_API Base64Encoder: public Base64EncoderIOS, public std::ostream
/// This ostream base64-encodes all data
/// written to it and forwards it to
/// a connected ostream.
/// Always call close() when done
/// writing data, to ensure proper
/// completion of the encoding operation.
{
public:
Base64Encoder(std::ostream& ostr);
~Base64Encoder();
};
Foundation_END
#endif // Foundation_Base64Encoder_INCLUDED

View File

@ -0,0 +1,88 @@
//
// BasicEvent.h
//
// $Id: //poco/1.1.0/Foundation/include/Foundation/BasicEvent.h#2 $
//
// Library: Foundation
// Package: Events
// Module: BasicEvent
//
// Implementation of the BasicEvent template.
//
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#ifndef Foundation_BasicEvent_INCLUDED
#define Foundation_BasicEvent_INCLUDED
#include "Foundation/AbstractEvent.h"
#include "Foundation/DefaultStrategy.h"
#include "Foundation/AbstractDelegate.h"
#include "Foundation/CompareFunctions.h"
Foundation_BEGIN
template <class TArgs>
class BasicEvent: public AbstractEvent <
TArgs, DefaultStrategy<TArgs, AbstractDelegate<TArgs>, p_less<AbstractDelegate<TArgs> > >,
AbstractDelegate<TArgs>
>
/// A BasicEvent uses internally a DefaultStrategy which
/// invokes delegates in an arbitrary manner.
/// Note that one object can only register one method to a BasicEvent.
/// Subsequent registrations will overwrite the existing delegate.
/// For example:
/// BasicEvent<int> event;
/// MyClass myObject;
/// event += Delegate<MyClass, int>(&myObject, &MyClass::myMethod1);
/// event += Delegate<MyClass, int>(&myObject, &MyClass::myMethod2);
///
/// The second registration will overwrite the first one. The reason is simply that
/// function pointers can only be compared by equality but not by lower than.
{
public:
BasicEvent()
{
}
~BasicEvent()
{
}
private:
BasicEvent(const BasicEvent& e);
BasicEvent& operator = (const BasicEvent& e);
};
Foundation_END
#endif

View File

@ -0,0 +1,192 @@
//
// BinaryReader.h
//
// $Id: //poco/1.1.0/Foundation/include/Foundation/BinaryReader.h#2 $
//
// Library: Foundation
// Package: Streams
// Module: BinaryReaderWriter
//
// Definition of the BinaryReader class.
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#ifndef Foundation_BinaryReader_INCLUDED
#define Foundation_BinaryReader_INCLUDED
#ifndef Foundation_Foundation_INCLUDED
#include "Foundation/Foundation.h"
#endif
#ifndef STD_ISTREAM_INCLUDED
#include <istream>
#define STD_ISTREAM_INCLUDED
#endif
Foundation_BEGIN
class Foundation_API BinaryReader
/// This class reads basic types in binary form into an input stream.
/// It provides an extractor-based interface similar to istream.
/// The reader also supports automatic conversion from big-endian
/// (network byte order) to little-endian and vice-versa.
/// Use a BinaryWriter to create a stream suitable for a BinaryReader.
{
public:
enum StreamByteOrder
{
NATIVE_BYTE_ORDER = 1, /// the host's native byte-order
BIG_ENDIAN_BYTE_ORDER = 2, /// big-endian (network) byte-order
NETWORK_BYTE_ORDER = 2, /// big-endian (network) byte-order
LITTLE_ENDIAN_BYTE_ORDER = 3, /// little-endian byte-order
UNSPECIFIED_BYTE_ORDER = 4 /// unknown, byte-order will be determined by reading the byte-order mark
};
BinaryReader(std::istream& istr, StreamByteOrder byteOrder = NATIVE_BYTE_ORDER);
/// Creates the BinaryReader.
~BinaryReader();
/// Destroys the BinaryReader.
BinaryReader& operator >> (bool& value);
BinaryReader& operator >> (char& value);
BinaryReader& operator >> (unsigned char& value);
BinaryReader& operator >> (signed char& value);
BinaryReader& operator >> (short& value);
BinaryReader& operator >> (unsigned short& value);
BinaryReader& operator >> (int& value);
BinaryReader& operator >> (unsigned int& value);
BinaryReader& operator >> (long& value);
BinaryReader& operator >> (unsigned long& value);
BinaryReader& operator >> (float& value);
BinaryReader& operator >> (double& value);
#if defined(POCO_HAVE_INT64) && !defined(POCO_LONG_IS_64_BIT)
BinaryReader& operator >> (Int64& value);
BinaryReader& operator >> (UInt64& value);
#endif
BinaryReader& operator >> (std::string& value);
void read7BitEncoded(UInt32& value);
/// Reads a 32-bit unsigned integer in compressed format.
/// See BinaryWriter::write7BitEncoded() for a description
/// of the compression algorithm.
#if defined(POCO_HAVE_INT64)
void read7BitEncoded(UInt64& value);
/// Reads a 64-bit unsigned integer in compressed format.
/// See BinaryWriter::write7BitEncoded() for a description
/// of the compression algorithm.
#endif
void readRaw(int length, std::string& value);
/// Reads length bytes of raw data into value.
void readBOM();
/// Reads a byte-order mark from the stream and configures
/// the reader for the encountered byte order.
/// A byte-order mark is a 16-bit integer with a value of 0xFEFF,
/// written in host byte order.
bool good();
/// Returns _istr.good();
bool fail();
/// Returns _istr.fail();
bool bad();
/// Returns _istr.bad();
bool eof();
/// Returns _istr.eof();
std::istream& stream() const;
/// Returns the underlying stream.
StreamByteOrder byteOrder() const;
/// Returns the byte-order used by the reader, which is
/// either BIG_ENDIAN_BYTE_ORDER or LITTLE_ENDIAN_BYTE_ORDER.
private:
std::istream& _istr;
bool _flipBytes;
};
//
// inlines
//
inline bool BinaryReader::good()
{
return _istr.good();
}
inline bool BinaryReader::fail()
{
return _istr.fail();
}
inline bool BinaryReader::bad()
{
return _istr.bad();
}
inline bool BinaryReader::eof()
{
return _istr.eof();
}
inline std::istream& BinaryReader::stream() const
{
return _istr;
}
inline BinaryReader::StreamByteOrder BinaryReader::byteOrder() const
{
#if defined(POCO_ARCH_BIG_ENDIAN)
return _flipBytes ? LITTLE_ENDIAN_BYTE_ORDER : BIG_ENDIAN_BYTE_ORDER;
#else
return _flipBytes ? BIG_ENDIAN_BYTE_ORDER : LITTLE_ENDIAN_BYTE_ORDER;
#endif
}
Foundation_END
#endif // Foundation_BinaryReader_INCLUDED

View File

@ -0,0 +1,204 @@
//
// BinaryWriter.h
//
// $Id: //poco/1.1.0/Foundation/include/Foundation/BinaryWriter.h#2 $
//
// Library: Foundation
// Package: Streams
// Module: BinaryReaderWriter
//
// Definition of the BinaryWriter class.
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#ifndef Foundation_BinaryWriter_INCLUDED
#define Foundation_BinaryWriter_INCLUDED
#ifndef Foundation_Foundation_INCLUDED
#include "Foundation/Foundation.h"
#endif
#ifndef STD_OSTREAM_INCLUDED
#include <ostream>
#define STD_OSTREAM_INCLUDED
#endif
Foundation_BEGIN
class Foundation_API BinaryWriter
/// This class writes basic types in binary form into an output stream.
/// It provides an inserter-based interface similar to ostream.
/// The writer also supports automatic conversion from big-endian
/// (network byte order) to little-endian and vice-versa.
/// Use a BinaryReader to read from a stream created by a BinaryWriter.
/// Be careful when exchanging data between systems with different
/// data type sizes (e.g., 32-bit and 64-bit architectures), as the sizes
/// of some of the basic types may be different. For example, writing a
/// long integer on a 64-bit system and reading it on a 32-bit system
/// may yield an incorrent result. Use fixed-size types (Int32, Int64, etc.)
/// in such a case.
{
public:
enum StreamByteOrder
{
NATIVE_BYTE_ORDER = 1, /// the host's native byte-order
BIG_ENDIAN_BYTE_ORDER = 2, /// big-endian (network) byte-order
NETWORK_BYTE_ORDER = 2, /// big-endian (network) byte-order
LITTLE_ENDIAN_BYTE_ORDER = 3 /// little-endian byte-order
};
BinaryWriter(std::ostream& ostr, StreamByteOrder byteOrder = NATIVE_BYTE_ORDER);
/// Creates the BinaryWriter.
~BinaryWriter();
/// Destroys the BinaryWriter.
BinaryWriter& operator << (bool value);
BinaryWriter& operator << (char value);
BinaryWriter& operator << (unsigned char value);
BinaryWriter& operator << (signed char value);
BinaryWriter& operator << (short value);
BinaryWriter& operator << (unsigned short value);
BinaryWriter& operator << (int value);
BinaryWriter& operator << (unsigned int value);
BinaryWriter& operator << (long value);
BinaryWriter& operator << (unsigned long value);
BinaryWriter& operator << (float value);
BinaryWriter& operator << (double value);
#if defined(POCO_HAVE_INT64) && !defined(POCO_LONG_IS_64_BIT)
BinaryWriter& operator << (Int64 value);
BinaryWriter& operator << (UInt64 value);
#endif
BinaryWriter& operator << (const std::string& value);
BinaryWriter& operator << (const char* value);
void write7BitEncoded(UInt32 value);
/// Writes a 32-bit unsigned integer in a compressed format.
/// The value is written out seven bits at a time, starting
/// with the seven least-significant bits.
/// The high bit of a byte indicates whether there are more bytes to be
/// written after this one.
/// If value will fit in seven bits, it takes only one byte of space.
/// If value will not fit in seven bits, the high bit is set on the first byte and
/// written out. value is then shifted by seven bits and the next byte is written.
/// This process is repeated until the entire integer has been written.
#if defined(POCO_HAVE_INT64)
void write7BitEncoded(UInt64 value);
/// Writes a 64-bit unsigned integer in a compressed format.
/// The value written out seven bits at a time, starting
/// with the seven least-significant bits.
/// The high bit of a byte indicates whether there are more bytes to be
/// written after this one.
/// If value will fit in seven bits, it takes only one byte of space.
/// If value will not fit in seven bits, the high bit is set on the first byte and
/// written out. value is then shifted by seven bits and the next byte is written.
/// This process is repeated until the entire integer has been written.
#endif
void writeRaw(const std::string& rawData);
/// Writes the string as-is to the stream.
void writeBOM();
/// Writes a byte-order mark to the stream. A byte order mark is
/// a 16-bit integer with a value of 0xFEFF, written in host byte-order.
/// A BinaryReader uses the byte-order mark to determine the byte-order
/// of the stream.
void flush();
/// Flushes the underlying stream.
bool good();
/// Returns _ostr.good();
bool fail();
/// Returns _ostr.fail();
bool bad();
/// Returns _ostr.bad();
std::ostream& stream() const;
/// Returns the underlying stream.
StreamByteOrder byteOrder() const;
/// Returns the byte ordering used by the writer, which is
/// either BIG_ENDIAN_BYTE_ORDER or LITTLE_ENDIAN_BYTE_ORDER.
private:
std::ostream& _ostr;
bool _flipBytes;
};
//
// inlines
//
inline std::ostream& BinaryWriter::stream() const
{
return _ostr;
}
inline bool BinaryWriter::good()
{
return _ostr.good();
}
inline bool BinaryWriter::fail()
{
return _ostr.fail();
}
inline bool BinaryWriter::bad()
{
return _ostr.bad();
}
inline BinaryWriter::StreamByteOrder BinaryWriter::byteOrder() const
{
#if defined(POCO_ARCH_BIG_ENDIAN)
return _flipBytes ? LITTLE_ENDIAN_BYTE_ORDER : BIG_ENDIAN_BYTE_ORDER;
#else
return _flipBytes ? BIG_ENDIAN_BYTE_ORDER : LITTLE_ENDIAN_BYTE_ORDER;
#endif
}
Foundation_END
#endif // Foundation_BinaryWriter_INCLUDED

View File

@ -0,0 +1,131 @@
//
// Buffer.h
//
// $Id: //poco/1.1.0/Foundation/include/Foundation/Buffer.h#2 $
//
// Library: Foundation
// Package: Core
// Module: Buffer
//
// Definition of the Buffer class.
//
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#ifndef Foundation_Buffer_INCLUDED
#define Foundation_Buffer_INCLUDED
#ifndef Foundation_Foundation_INCLUDED
#include "Foundation/Foundation.h"
#endif
Foundation_BEGIN
template <class T>
class Buffer
/// A very simple buffer class that allocates a buffer of
/// a given type and size in the constructor and
/// deallocates the buffer in the destructor.
///
/// This class is useful everywhere where a temporary buffer
/// is needed.
{
public:
Buffer(int size):
_size(size),
_ptr(new T[size])
/// Creates and allocates the Buffer.
{
}
~Buffer()
/// Destroys the Buffer.
{
delete [] _ptr;
}
int size() const
/// Returns the size of the buffer.
{
return _size;
}
T* begin()
/// Returns a pointer to the beginning of the buffer.
{
return _ptr;
}
const T* begin() const
/// Returns a pointer to the beginning of the buffer.
{
return _ptr;
}
T* end()
/// Returns a pointer to end of the buffer.
{
return _ptr + _size;
}
const T* end() const
/// Returns a pointer to the end of the buffer.
{
return _ptr + _size;
}
T& operator [] (int index)
{
poco_assert (index >= 0 && index < _size);
return _ptr[index];
}
const T& operator [] (int index) const
{
poco_assert (index >= 0 && index < _size);
return _ptr[index];
}
private:
Buffer();
Buffer(const Buffer&);
Buffer& operator = (const Buffer&);
int _size;
T* _ptr;
};
Foundation_END
#endif // Foundation_Buffer_INCLUDED

View File

@ -0,0 +1,78 @@
//
// BufferAllocator.h
//
// $Id: //poco/1.1.0/Foundation/include/Foundation/BufferAllocator.h#2 $
//
// Library: Foundation
// Package: Streams
// Module: BufferAllocator
//
// Definition of the BufferAllocator class.
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#ifndef Foundation_BufferAllocator_INCLUDED
#define Foundation_BufferAllocator_INCLUDED
#ifndef Foundation_Foundation_INCLUDED
#include "Foundation/Foundation.h"
#endif
#ifndef STD_IOS_INCLUDED
#include <ios>
#define STD_IOS_INCLUDED
#endif
Foundation_BEGIN
template <typename ch>
class BufferAllocator
/// The BufferAllocator used if no specific
/// BufferAllocator has been specified.
{
public:
typedef ch char_type;
static char_type* allocate(std::streamsize size)
{
return new char_type[size];
}
static void deallocate(char_type* ptr, std::streamsize size)
{
delete [] ptr;
}
};
Foundation_END
#endif // Foundation_BufferAllocator_INCLUDED

View File

@ -0,0 +1,192 @@
//
// BufferedBidirectionalStreamBuf.h
//
// $Id: //poco/1.1.0/Foundation/include/Foundation/BufferedBidirectionalStreamBuf.h#2 $
//
// Library: Foundation
// Package: Streams
// Module: StreamBuf
//
// Definition of template BasicBufferedBidirectionalStreamBuf and class BufferedBidirectionalStreamBuf.
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#ifndef Foundation_BufferedBidirectionalStreamBuf_INCLUDED
#define Foundation_BufferedBidirectionalStreamBuf_INCLUDED
#ifndef Foundation_Foundation_INCLUDED
#include "Foundation/Foundation.h"
#endif
#ifndef Foundation_BufferAllocator_INCLUDED
#include "Foundation/BufferAllocator.h"
#endif
#ifndef Foundation_StreamUtil_INCLUDED
#include "Foundation/StreamUtil.h"
#endif
#ifndef STD_STREAMBUF_INCLUDED
#include <streambuf>
#define STD_STREAMBUF_INCLUDED
#endif
#ifndef STD_IOSFWD_INCLUDED
#include <iosfwd>
#define STD_IOSFWD_INCLUDED
#endif
#ifndef STD_IOS_INCLUDED
#include <ios>
#define STD_IOS_INCLUDED
#endif
Foundation_BEGIN
template<typename ch, typename tr, typename ba = BufferAllocator<ch> >
class BasicBufferedBidirectionalStreamBuf: public std::basic_streambuf<ch, tr>
/// This is an implementation of a buffered bidirectional
/// streambuf that greatly simplifies the implementation of
/// custom streambufs of various kinds.
/// Derived classes only have to override the methods
/// readFromDevice() or writeToDevice().
///
/// In contrast to BasicBufferedStreambuf, this class supports
/// simultaneous read and write access, so in addition to
/// istream and ostream this streambuf can also be used
/// for implementing an iostream.
{
protected:
typedef std::basic_streambuf<ch, tr> Base;
typedef std::basic_ios<ch, tr> IOS;
typedef ch char_type;
typedef tr char_traits;
typedef ba Allocator;
typedef typename Base::int_type int_type;
typedef typename Base::pos_type pos_type;
typedef typename Base::off_type off_type;
typedef typename IOS::openmode openmode;
public:
BasicBufferedBidirectionalStreamBuf(std::streamsize bufferSize, openmode mode):
_bufsize(bufferSize),
_pReadBuffer(Allocator::allocate(_bufsize)),
_pWriteBuffer(Allocator::allocate(_bufsize)),
_mode(mode)
{
this->setg(_pReadBuffer + 4, _pReadBuffer + 4, _pReadBuffer + 4);
this->setp(_pWriteBuffer, _pWriteBuffer + (_bufsize - 1));
}
~BasicBufferedBidirectionalStreamBuf()
{
Allocator::deallocate(_pReadBuffer, _bufsize);
Allocator::deallocate(_pWriteBuffer, _bufsize);
}
virtual int_type overflow(int_type c)
{
if (!(_mode & IOS::out)) return char_traits::eof();
if (c != char_traits::eof())
{
*this->pptr() = char_traits::to_char_type(c);
this->pbump(1);
}
if (flush_buffer() == std::streamsize(-1)) return char_traits::eof();
return c;
}
virtual int_type underflow()
{
if (!(_mode & IOS::in)) return char_traits::eof();
if (this->gptr() && (this->gptr() < this->egptr()))
return char_traits::to_int_type(*this->gptr());
int putback = int(this->gptr() - this->eback());
if (putback > 4) putback = 4;
char_traits::copy(_pReadBuffer + (4 - putback), this->gptr() - putback, putback);
int n = readFromDevice(_pReadBuffer + 4, _bufsize - 4);
if (n <= 0) return char_traits::eof();
this->setg(_pReadBuffer + (4 - putback), _pReadBuffer + 4, _pReadBuffer + 4 + n);
// return next character
return char_traits::to_int_type(*this->gptr());
}
virtual int sync()
{
if (this->pptr() && this->pptr() > this->pbase())
{
if (flush_buffer() == -1) return -1;
}
return 0;
}
private:
virtual int readFromDevice(char_type* buffer, std::streamsize length)
{
return 0;
}
virtual int writeToDevice(const char_type* buffer, std::streamsize length)
{
return 0;
}
int flush_buffer()
{
int n = int(this->pptr() - this->pbase());
if (writeToDevice(this->pbase(), n) == n)
{
this->pbump(-n);
return n;
}
return -1;
}
std::streamsize _bufsize;
char_type* _pReadBuffer;
char_type* _pWriteBuffer;
openmode _mode;
};
//
// We provide an instantiation for char
//
typedef BasicBufferedBidirectionalStreamBuf<char, std::char_traits<char> > BufferedBidirectionalStreamBuf;
Foundation_END
#endif // Foundation_BufferedBidirectionalStreamBuf_INCLUDED

View File

@ -0,0 +1,189 @@
//
// BufferedStreamBuf.h
//
// $Id: //poco/1.1.0/Foundation/include/Foundation/BufferedStreamBuf.h#2 $
//
// Library: Foundation
// Package: Streams
// Module: StreamBuf
//
// Definition of template BasicBufferedStreamBuf and class BufferedStreamBuf.
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#ifndef Foundation_BufferedStreamBuf_INCLUDED
#define Foundation_BufferedStreamBuf_INCLUDED
#ifndef Foundation_Foundation_INCLUDED
#include "Foundation/Foundation.h"
#endif
#ifndef Foundation_BufferAllocator_INCLUDED
#include "Foundation/BufferAllocator.h"
#endif
#ifndef Foundation_StreamUtil_INCLUDED
#include "Foundation/StreamUtil.h"
#endif
#ifndef STD_STREAMBUF_INCLUDED
#include <streambuf>
#define STD_STREAMBUF_INCLUDED
#endif
#ifndef STD_IOSFWD_INCLUDED
#include <iosfwd>
#define STD_IOSFWD_INCLUDED
#endif
#ifndef STD_IOS_INCLUDED
#include <ios>
#define STD_IOS_INCLUDED
#endif
Foundation_BEGIN
template <typename ch, typename tr, typename ba = BufferAllocator<ch> >
class BasicBufferedStreamBuf: public std::basic_streambuf<ch, tr>
/// This is an implementation of a buffered streambuf
/// that greatly simplifies the implementation of
/// custom streambufs of various kinds.
/// Derived classes only have to override the methods
/// readFromDevice() or writeToDevice().
///
/// This streambuf only supports unidirectional streams.
/// In other words, the BasicBufferedStreamBuf can be
/// used for the implementation of an istream or an
/// ostream, but not for an iostream.
{
protected:
typedef std::basic_streambuf<ch, tr> Base;
typedef std::basic_ios<ch, tr> IOS;
typedef ch char_type;
typedef tr char_traits;
typedef ba Allocator;
typedef typename Base::int_type int_type;
typedef typename Base::pos_type pos_type;
typedef typename Base::off_type off_type;
typedef typename IOS::openmode openmode;
public:
BasicBufferedStreamBuf(std::streamsize bufferSize, openmode mode):
_bufsize(bufferSize),
_pBuffer(Allocator::allocate(_bufsize)),
_mode(mode)
{
this->setg(_pBuffer + 4, _pBuffer + 4, _pBuffer + 4);
this->setp(_pBuffer, _pBuffer + (_bufsize - 1));
}
~BasicBufferedStreamBuf()
{
Allocator::deallocate(_pBuffer, _bufsize);
}
virtual int_type overflow(int_type c)
{
if (!(_mode & IOS::out)) return char_traits::eof();
if (c != char_traits::eof())
{
*this->pptr() = char_traits::to_char_type(c);
this->pbump(1);
}
if (flush_buffer() == std::streamsize(-1)) return char_traits::eof();
return c;
}
virtual int_type underflow()
{
if (!(_mode & IOS::in)) return char_traits::eof();
if (this->gptr() && (this->gptr() < this->egptr()))
return char_traits::to_int_type(*this->gptr());
int putback = int(this->gptr() - this->eback());
if (putback > 4) putback = 4;
char_traits::copy(_pBuffer + (4 - putback), this->gptr() - putback, putback);
int n = readFromDevice(_pBuffer + 4, _bufsize - 4);
if (n <= 0) return char_traits::eof();
this->setg(_pBuffer + (4 - putback), _pBuffer + 4, _pBuffer + 4 + n);
// return next character
return char_traits::to_int_type(*this->gptr());
}
virtual int sync()
{
if (this->pptr() && this->pptr() > this->pbase())
{
if (flush_buffer() == -1) return -1;
}
return 0;
}
private:
virtual int readFromDevice(char_type* buffer, std::streamsize length)
{
return 0;
}
virtual int writeToDevice(const char_type* buffer, std::streamsize length)
{
return 0;
}
int flush_buffer()
{
int n = int(this->pptr() - this->pbase());
if (writeToDevice(this->pbase(), n) == n)
{
this->pbump(-n);
return n;
}
return -1;
}
std::streamsize _bufsize;
char_type* _pBuffer;
openmode _mode;
};
//
// We provide an instantiation for char
//
typedef BasicBufferedStreamBuf<char, std::char_traits<char> > BufferedStreamBuf;
Foundation_END
#endif // Foundation_BufferedStreamBuf_INCLUDED

View File

@ -0,0 +1,131 @@
//
// Bugcheck.h
//
// $Id: //poco/1.1.0/Foundation/include/Foundation/Bugcheck.h#2 $
//
// Library: Foundation
// Package: Core
// Module: Bugcheck
//
// Definition of the Bugcheck class and the self-testing macros.
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#ifndef Foundation_Bugcheck_INCLUDED
#define Foundation_Bugcheck_INCLUDED
#ifndef Foundation_Foundation_INCLUDED
#include "Foundation/Foundation.h"
#endif
#ifndef STD_STRING_INCLUDED
#include <string>
#define STD_STRING_INCLUDED
#endif
Foundation_BEGIN
class Foundation_API Bugcheck
/// This class provides some static methods that are
/// used by the
/// poco_assert_dbg(), poco_assert(), poco_check_ptr()
/// and poco_bugcheck() macros.
/// You should not invoke these methods
/// directly. Use the macros instead, as they
/// automatically provide useful context information.
{
public:
static void assertion(const char* cond, const char* file, int line);
/// An assertion failed. Break into the debugger, if
/// possible, then throw an AssertionViolationException.
static void nullPointer(const char* ptr, const char* file, int line);
/// An null pointer was encountered. Break into the debugger, if
/// possible, then throw an NullPointerException.
static void bugcheck(const char* file, int line);
/// An internal error was encountered. Break into the debugger, if
/// possible, then throw an BugcheckException.
static void bugcheck(const char* msg, const char* file, int line);
/// An internal error was encountered. Break into the debugger, if
/// possible, then throw an BugcheckException.
static void debugger(const char* file, int line);
/// An internal error was encountered. Break into the debugger, if
/// possible.
static void debugger(const char* msg, const char* file, int line);
/// An internal error was encountered. Break into the debugger, if
/// possible.
protected:
static std::string what(const char* msg, const char* file, int line);
};
//
// useful macros (these automatically supply line number and file name)
//
#if defined(_DEBUG)
#define poco_assert_dbg(cond) if (!(cond)) Foundation::Bugcheck::assertion(#cond, __FILE__, __LINE__); else (void) 0
#else
#define poco_assert_dbg(cond)
#endif
#define poco_assert(cond) \
if (!(cond)) Foundation::Bugcheck::assertion(#cond, __FILE__, __LINE__); else (void) 0
#define poco_check_ptr(ptr) \
if (!(ptr)) Foundation::Bugcheck::nullPointer(#ptr, __FILE__, __LINE__); else (void) 0
#define poco_bugcheck() \
Foundation::Bugcheck::bugcheck(__FILE__, __LINE__)
#define poco_bugcheck_msg(msg) \
Foundation::Bugcheck::bugcheck(msg, __FILE__, __LINE__)
#define poco_debugger() \
Foundation::Bugcheck::debugger(__FILE__, __LINE__)
#define poco_debugger_msg(msg) \
Foundation::Bugcheck::debugger(msg, __FILE__, __LINE__)
Foundation_END
#endif // Foundation_Bugcheck_INCLUDED

View File

@ -0,0 +1,231 @@
//
// ByteOrder.h
//
// $Id: //poco/1.1.0/Foundation/include/Foundation/ByteOrder.h#2 $
//
// Library: Foundation
// Package: Core
// Module: ByteOrder
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#ifndef Foundation_ByteOrder_INCLUDED
#define Foundation_ByteOrder_INCLUDED
#ifndef Foundation_Foundation_INCLUDED
#include "Foundation/Foundation.h"
#endif
#ifndef Foundation_Types_INCLUDED
#include "Foundation/Types.h"
#endif
Foundation_BEGIN
class Foundation_API ByteOrder
/// This class contains a number of static methods
/// to convert between big-endian and little-endian
/// integers of various sizes.
{
public:
static Int16 flipBytes(Int16 value);
static UInt16 flipBytes(UInt16 value);
static Int32 flipBytes(Int32 value);
static UInt32 flipBytes(UInt32 value);
#if defined(POCO_HAVE_INT64)
static Int64 flipBytes(Int64 value);
static UInt64 flipBytes(UInt64 value);
#endif
static Int16 toBigEndian(Int16 value);
static UInt16 toBigEndian (UInt16 value);
static Int32 toBigEndian(Int32 value);
static UInt32 toBigEndian (UInt32 value);
#if defined(POCO_HAVE_INT64)
static Int64 toBigEndian(Int64 value);
static UInt64 toBigEndian (UInt64 value);
#endif
static Int16 fromBigEndian(Int16 value);
static UInt16 fromBigEndian (UInt16 value);
static Int32 fromBigEndian(Int32 value);
static UInt32 fromBigEndian (UInt32 value);
#if defined(POCO_HAVE_INT64)
static Int64 fromBigEndian(Int64 value);
static UInt64 fromBigEndian (UInt64 value);
#endif
static Int16 toLittleEndian(Int16 value);
static UInt16 toLittleEndian (UInt16 value);
static Int32 toLittleEndian(Int32 value);
static UInt32 toLittleEndian (UInt32 value);
#if defined(POCO_HAVE_INT64)
static Int64 toLittleEndian(Int64 value);
static UInt64 toLittleEndian (UInt64 value);
#endif
static Int16 fromLittleEndian(Int16 value);
static UInt16 fromLittleEndian (UInt16 value);
static Int32 fromLittleEndian(Int32 value);
static UInt32 fromLittleEndian (UInt32 value);
#if defined(POCO_HAVE_INT64)
static Int64 fromLittleEndian(Int64 value);
static UInt64 fromLittleEndian (UInt64 value);
#endif
static Int16 toNetwork(Int16 value);
static UInt16 toNetwork (UInt16 value);
static Int32 toNetwork(Int32 value);
static UInt32 toNetwork (UInt32 value);
#if defined(POCO_HAVE_INT64)
static Int64 toNetwork(Int64 value);
static UInt64 toNetwork (UInt64 value);
#endif
static Int16 fromNetwork(Int16 value);
static UInt16 fromNetwork (UInt16 value);
static Int32 fromNetwork(Int32 value);
static UInt32 fromNetwork (UInt32 value);
#if defined(POCO_HAVE_INT64)
static Int64 fromNetwork(Int64 value);
static UInt64 fromNetwork (UInt64 value);
#endif
};
//
// inlines
//
inline UInt16 ByteOrder::flipBytes(UInt16 value)
{
return ((value >> 8) & 0x00FF) | ((value << 8) & 0xFF00);
}
inline Int16 ByteOrder::flipBytes(Int16 value)
{
return Int16(flipBytes(UInt16(value)));
}
inline UInt32 ByteOrder::flipBytes(UInt32 value)
{
return ((value >> 24) & 0x000000FF) | ((value >> 8) & 0x0000FF00)
| ((value << 8) & 0x00FF0000) | ((value << 24) & 0xFF000000);
}
inline Int32 ByteOrder::flipBytes(Int32 value)
{
return Int32(flipBytes(UInt32(value)));
}
#if defined(POCO_HAVE_INT64)
inline UInt64 ByteOrder::flipBytes(UInt64 value)
{
UInt32 hi = UInt32(value >> 32);
UInt32 lo = UInt32(value & 0xFFFFFFFF);
return UInt64(flipBytes(hi)) | (UInt64(flipBytes(lo)) << 32);
}
inline Int64 ByteOrder::flipBytes(Int64 value)
{
return Int64(flipBytes(UInt64(value)));
}
#endif // POCO_HAVE_INT64
//
// some macro trickery to automate the method implementation
//
#define POCO_IMPLEMENT_BYTEORDER_NOOP_(op, type) \
inline type ByteOrder::op(type value) \
{ \
return value; \
}
#define POCO_IMPLEMENT_BYTEORDER_FLIP_(op, type) \
inline type ByteOrder::op(type value) \
{ \
return flipBytes(value); \
}
#if defined(POCO_HAVE_INT64)
#define POCO_IMPLEMENT_BYTEORDER_NOOP(op) \
POCO_IMPLEMENT_BYTEORDER_NOOP_(op, Int16) \
POCO_IMPLEMENT_BYTEORDER_NOOP_(op, UInt16) \
POCO_IMPLEMENT_BYTEORDER_NOOP_(op, Int32) \
POCO_IMPLEMENT_BYTEORDER_NOOP_(op, UInt32) \
POCO_IMPLEMENT_BYTEORDER_NOOP_(op, Int64) \
POCO_IMPLEMENT_BYTEORDER_NOOP_(op, UInt64)
#define POCO_IMPLEMENT_BYTEORDER_FLIP(op) \
POCO_IMPLEMENT_BYTEORDER_FLIP_(op, Int16) \
POCO_IMPLEMENT_BYTEORDER_FLIP_(op, UInt16) \
POCO_IMPLEMENT_BYTEORDER_FLIP_(op, Int32) \
POCO_IMPLEMENT_BYTEORDER_FLIP_(op, UInt32) \
POCO_IMPLEMENT_BYTEORDER_FLIP_(op, Int64) \
POCO_IMPLEMENT_BYTEORDER_FLIP_(op, UInt64)
#else
#define POCO_IMPLEMENT_BYTEORDER_NOOP(op) \
POCO_IMPLEMENT_BYTEORDER_NOOP_(op, Int16) \
POCO_IMPLEMENT_BYTEORDER_NOOP_(op, UInt16) \
POCO_IMPLEMENT_BYTEORDER_NOOP_(op, Int32) \
POCO_IMPLEMENT_BYTEORDER_NOOP_(op, UInt32)
#define POCO_IMPLEMENT_BYTEORDER_FLIP(op) \
POCO_IMPLEMENT_BYTEORDER_FLIP_(op, Int16) \
POCO_IMPLEMENT_BYTEORDER_FLIP_(op, UInt16) \
POCO_IMPLEMENT_BYTEORDER_FLIP_(op, Int32) \
POCO_IMPLEMENT_BYTEORDER_FLIP_(op, UInt32)
#endif
#if defined(POCO_ARCH_BIG_ENDIAN)
#define POCO_IMPLEMENT_BYTEORDER_BIG POCO_IMPLEMENT_BYTEORDER_NOOP
#define POCO_IMPLEMENT_BYTEORDER_LIT POCO_IMPLEMENT_BYTEORDER_FLIP
#else
#define POCO_IMPLEMENT_BYTEORDER_BIG POCO_IMPLEMENT_BYTEORDER_FLIP
#define POCO_IMPLEMENT_BYTEORDER_LIT POCO_IMPLEMENT_BYTEORDER_NOOP
#endif
POCO_IMPLEMENT_BYTEORDER_BIG(toBigEndian)
POCO_IMPLEMENT_BYTEORDER_BIG(fromBigEndian)
POCO_IMPLEMENT_BYTEORDER_BIG(toNetwork)
POCO_IMPLEMENT_BYTEORDER_BIG(fromNetwork)
POCO_IMPLEMENT_BYTEORDER_LIT(toLittleEndian)
POCO_IMPLEMENT_BYTEORDER_LIT(fromLittleEndian)
Foundation_END
#endif // Foundation_ByteOrder_INCLUDED

View File

@ -0,0 +1,104 @@
//
// Channel.h
//
// $Id: //poco/1.1.0/Foundation/include/Foundation/Channel.h#2 $
//
// Library: Foundation
// Package: Logging
// Module: Channel
//
// Definition of the Channel class.
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#ifndef Foundation_Channel_INCLUDED
#define Foundation_Channel_INCLUDED
#ifndef Foundation_Foundation_INCLUDED
#include "Foundation/Foundation.h"
#endif
#ifndef Foundation_Configurable_INCLUDED
#include "Foundation/Configurable.h"
#endif
#ifndef Foundation_Mutex_INCLUDED
#include "Foundation/Mutex.h"
#endif
#ifndef Foundation_RefCountedObject_INCLUDED
#include "Foundation/RefCountedObject.h"
#endif
Foundation_BEGIN
class Message;
class Foundation_API Channel: public Configurable, public RefCountedObject
/// The base class for all Channel classes.
///
/// Supports reference counting based garbage
/// collection and provides trivial implementations
/// of getProperty() and setProperty().
{
public:
Channel();
/// Creates the channel and initializes
/// the reference count to one.
virtual void open();
/// Does whatever is necessary to open the channel.
/// The default implementation does nothing.
virtual void close();
/// Does whatever is necessary to close the channel.
/// The default implementation does nothing.
virtual void log(const Message& msg) = 0;
/// Logs the given message to the channel. Must be
/// overridden by subclasses.
///
/// If the channel has not been opened yet, the log()
/// method will open it.
void setProperty(const std::string& name, const std::string& value);
/// Throws a PropertyNotSupportedException.
std::string getProperty(const std::string& name) const;
/// Throws a PropertyNotSupportedException.
protected:
virtual ~Channel();
};
Foundation_END
#endif // Foundation_Channel_INCLUDED

View File

@ -0,0 +1,111 @@
//
// ClassLibrary.h
//
// $Id: //poco/1.1.0/Foundation/include/Foundation/ClassLibrary.h#2 $
//
// Library: Foundation
// Package: SharedLibrary
// Module: ClassLoader
//
// Definitions for class libraries.
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#ifndef Foundation_ClassLibrary_INCLUDED
#define Foundation_ClassLibrary_INCLUDED
#ifndef Foundation_Foundation_INCLUDED
#include "Foundation/Foundation.h"
#endif
#ifndef Foundation_Manifest_INCLUDED
#include "Foundation/Manifest.h"
#endif
#ifndef STD_TYPEINFO_INCLUDED
#include <typeinfo>
#define STD_TYPEINFO_INCLUDED
#endif
#if defined(_WIN32)
#define POCO_LIBRARY_API __declspec(dllexport)
#else
#define POCO_LIBRARY_API
#endif
//
// the entry point for every class library
//
extern "C"
{
bool POCO_LIBRARY_API pocoBuildManifest(Foundation::ManifestBase* pManifest);
void POCO_LIBRARY_API pocoInitializeLibrary();
void POCO_LIBRARY_API pocoUninitializeLibrary();
}
//
// Macros to automatically implement pocoBuildManifest
//
// usage:
//
// POCO_BEGIN_MANIFEST(MyBaseClass)
// POCO_EXPORT_CLASS(MyFirstClass)
// POCO_EXPORT_CLASS(MySecondClass)
// ...
// POCO_END_MANIFEST
//
#define POCO_BEGIN_MANIFEST(base) \
bool pocoBuildManifest(Foundation::ManifestBase* pManifest_) \
{ \
typedef base _Base; \
typedef Foundation::Manifest<_Base> _Manifest; \
std::string requiredType(typeid(_Manifest).name()); \
std::string actualType(pManifest_->className()); \
if (requiredType == actualType) \
{ \
Foundation::Manifest<_Base>* pManifest = static_cast<_Manifest*>(pManifest_);
#define POCO_END_MANIFEST \
return true; \
} \
else return false; \
}
#define POCO_EXPORT_CLASS(cls) \
pManifest->insert(new Foundation::MetaObject<cls, _Base>(#cls));
#define POCO_EXPORT_SINGLETON(cls) \
pManifest->insert(new Foundation::MetaSingleton<cls, _Base>(#cls));
#endif // Foundation_ClassLibrary_INCLUDED

View File

@ -0,0 +1,373 @@
//
// ClassLoader.h
//
// $Id: //poco/1.1.0/Foundation/include/Foundation/ClassLoader.h#2 $
//
// Library: Foundation
// Package: SharedLibrary
// Module: ClassLoader
//
// Definition of the ClassLoader class.
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#ifndef Foundation_ClassLoader_INCLUDED
#define Foundation_ClassLoader_INCLUDED
#ifndef Foundation_Foundation_INCLUDED
#include "Foundation/Foundation.h"
#endif
#ifndef Foundation_MetaObject_INCLUDED
#include "Foundation/MetaObject.h"
#endif
#ifndef Foundation_Manifest_INCLUDED
#include "Foundation/Manifest.h"
#endif
#ifndef Foundation_SharedLibrary_INCLUDED
#include "Foundation/SharedLibrary.h"
#endif
#ifndef Foundation_Mutex_INCLUDED
#include "Foundation/Mutex.h"
#endif
#ifndef Foundation_Exception_INCLUDED
#include "Foundation/Exception.h"
#endif
#ifndef STD_MAP_INCLUDED
#include <map>
#define STD_MAP_INCLUDED
#endif
Foundation_BEGIN
template <class Base>
class ClassLoader
/// The ClassLoader loads C++ classes from shared libraries
/// at runtime. It must be instantiated with a root class
/// of the loadable classes.
/// For a class to be loadable from a library, the library
/// must provide a Manifest of all the classes it contains.
/// The Manifest for a shared library can be easily built
/// with the help of the macros in the header file
/// "Foundation/ClassLibrary.h".
{
public:
typedef AbstractMetaObject<Base> Meta;
typedef Manifest<Base> Manif;
typedef void (*InitializeLibraryFunc)();
typedef void (*UninitializeLibraryFunc)();
typedef bool (*BuildManifestFunc)(ManifestBase*);
struct LibraryInfo
{
SharedLibrary* pLibrary;
const Manif* pManifest;
int refCount;
};
typedef std::map<std::string, LibraryInfo> LibraryMap;
class Iterator
/// The ClassLoader's very own iterator class.
{
public:
typedef std::pair<std::string, const Manif*> Pair;
Iterator(const typename LibraryMap::const_iterator& it)
{
_it = it;
}
Iterator(const Iterator& it)
{
_it = it._it;
}
~Iterator()
{
}
Iterator& operator = (const Iterator& it)
{
_it = it._it;
return *this;
}
inline bool operator == (const Iterator& it) const
{
return _it == it._it;
}
inline bool operator != (const Iterator& it) const
{
return _it != it._it;
}
Iterator& operator ++ () // prefix
{
++_it;
return *this;
}
Iterator operator ++ (int) // postfix
{
Iterator result(_it);
++_it;
return result;
}
inline const Pair* operator * () const
{
_pair.first = _it->first;
_pair.second = _it->second.pManifest;
return &_pair;
}
inline const Pair* operator -> () const
{
_pair.first = _it->first;
_pair.second = _it->second.pManifest;
return &_pair;
}
private:
typename LibraryMap::const_iterator _it;
mutable Pair _pair;
};
ClassLoader()
/// Creates the ClassLoader.
{
}
virtual ~ClassLoader()
/// Destroys the ClassLoader.
{
for (typename LibraryMap::const_iterator it = _map.begin(); it != _map.end(); ++it)
{
delete it->second.pLibrary;
delete it->second.pManifest;
}
}
void loadLibrary(const std::string& path)
/// Loads a library from the given path. Does nothing
/// if the library is already loaded.
/// Throws a LibraryLoadException if the library
/// cannot be loaded or does not have a Manifest.
/// If the library exports a function named "pocoInitializeLibrary",
/// this function is executed.
/// If called multiple times for the same library,
/// the number of calls to unloadLibrary() must be the same
/// for the library to become unloaded.
{
FastMutex::ScopedLock lock(_mutex);
typename LibraryMap::iterator it = _map.find(path);
if (it == _map.end())
{
LibraryInfo li;
li.pLibrary = new SharedLibrary(path);
li.pManifest = new Manif();
li.refCount = 1;
try
{
if (li.pLibrary->hasSymbol("pocoInitializeLibrary"))
{
InitializeLibraryFunc initializeLibrary = (InitializeLibraryFunc) li.pLibrary->getSymbol("pocoInitializeLibrary");
initializeLibrary();
}
if (li.pLibrary->hasSymbol("pocoBuildManifest"))
{
BuildManifestFunc buildManifest = (BuildManifestFunc) li.pLibrary->getSymbol("pocoBuildManifest");
if (buildManifest(const_cast<Manif*>(li.pManifest)))
_map[path] = li;
else
throw LibraryLoadException(std::string("Manifest class mismatch in ") + path);
}
else throw LibraryLoadException(std::string("No manifest in ") + path);
}
catch (...)
{
delete li.pLibrary;
delete li.pManifest;
throw;
}
}
else
{
++it->second.refCount;
}
}
void unloadLibrary(const std::string& path)
/// Unloads the given library.
/// Be extremely cautious when unloading shared libraries.
/// If objects from the library are still referenced somewhere,
/// a total crash is very likely.
/// If the library exports a function named "pocoUninitializeLibrary",
/// this function is executed before it is unloaded.
/// If loadLibrary() has been called multiple times for the same
/// library, the number of calls to unloadLibrary() must be the same
/// for the library to become unloaded.
{
FastMutex::ScopedLock lock(_mutex);
typename LibraryMap::iterator it = _map.find(path);
if (it != _map.end())
{
if (--it->second.refCount == 0)
{
if (it->second.pLibrary->hasSymbol("pocoUninitializeLibrary"))
{
UninitializeLibraryFunc uninitializeLibrary = (UninitializeLibraryFunc) it->second.pLibrary->getSymbol("pocoUninitializeLibrary");
uninitializeLibrary();
}
delete it->second.pManifest;
it->second.pLibrary->unload();
delete it->second.pLibrary;
_map.erase(it);
}
}
else throw NotFoundException(path);
}
const Meta* findClass(const std::string& className) const
/// Returns a pointer to the MetaObject for the given
/// class, or a null pointer if the class is not known.
{
FastMutex::ScopedLock lock(_mutex);
for (typename LibraryMap::const_iterator it = _map.begin(); it != _map.end(); ++it)
{
const Manif* pManif = it->second.pManifest;
typename Manif::Iterator itm = pManif->find(className);
if (itm != pManif->end())
return *itm;
}
return 0;
}
const Meta& classFor(const std::string& className) const
/// Returns a reference to the MetaObject for the given
/// class. Throws a NotFoundException if the class
/// is not known.
{
const Meta* pMeta = findClass(className);
if (pMeta)
return *pMeta;
else
throw NotFoundException(className);
}
Base* create(const std::string& className) const
/// Creates an instance of the given class.
/// Throws a NotFoundException if the class
/// is not known.
{
return classFor(className).create();
}
Base& instance(const std::string& className) const
/// Returns a reference to the sole instance of
/// the given class. The class must be a singleton,
/// otherwise an InvalidAccessException will be thrown.
/// Throws a NotFoundException if the class
/// is not known.
{
return classFor(className).instance();
}
bool canCreate(const std::string& className) const
/// Returns true if create() can create new instances
/// of the class.
{
return classFor(className).canCreate();
}
void destroy(const std::string& className, Base* pObject) const
/// Destroys the object pObject points to.
/// Does nothing if object is not found.
{
classFor(className).destroy(pObject);
}
bool isAutoDelete(const std::string& className, Base* pObject) const
/// Returns true if the object is automatically
/// deleted by its meta object.
{
return classFor(className).isAutoDelete(pObject);
}
const Manif* findManifest(const std::string& path) const
/// Returns a pointer to the Manifest for the given
/// library, or a null pointer if the library has not been loaded.
{
FastMutex::ScopedLock lock(_mutex);
typename LibraryMap::const_iterator it = _map.find(path);
if (it != _map.end())
return it->second.pManifest;
else
return 0;
}
const Manif& manifestFor(const std::string& path) const
/// Returns a reference to the Manifest for the given library
/// Throws a NotFoundException if the library has not been loaded.
{
const Manif* pManif = findManifest(path);
if (pManif)
return *pManif;
else
throw NotFoundException(path);
}
bool isLibraryLoaded(const std::string& path) const
/// Returns true if the library with the given name
/// has already been loaded.
{
return findManifest(path) != 0;
}
Iterator begin() const
{
FastMutex::ScopedLock lock(_mutex);
return Iterator(_map.begin());
}
Iterator end() const
{
FastMutex::ScopedLock lock(_mutex);
return Iterator(_map.end());
}
private:
LibraryMap _map;
mutable FastMutex _mutex;
};
Foundation_END
#endif // Foundation_ClassLoader_INCLUDED

View File

@ -0,0 +1,63 @@
//
// CompareFunctions.h
//
// $Id: //poco/1.1.0/Foundation/include/Foundation/CompareFunctions.h#2 $
//
// Library: Foundation
// Package: Events
// Module: CompareFunctions
//
// Compare operators for the NotificationStrategies.
//
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#ifndef Foundation_CompareFunctions_INCLUDED
#define Foundation_CompareFunctions_INCLUDED
#include "Foundation/Foundation.h"
#include <functional>
Foundation_BEGIN
template <class T>
struct p_less: std::binary_function<T, T, bool>
{
bool operator () (const T* const & x, const T* const & y) const
{
return *x < *y;
}
};
Foundation_END
#endif

View File

@ -0,0 +1,87 @@
//
// Configurable.h
//
// $Id: //poco/1.1.0/Foundation/include/Foundation/Configurable.h#2 $
//
// Library: Foundation
// Package: Logging
// Module: Configurable
//
// Definition of the Configurable class.
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#ifndef Foundation_Configurable_INCLUDED
#define Foundation_Configurable_INCLUDED
#ifndef Foundation_Foundation_INCLUDED
#include "Foundation/Foundation.h"
#endif
Foundation_BEGIN
class Foundation_API Configurable
/// A simple interface that defines
/// getProperty() and setProperty() methods.
///
/// This interface is implemented by Formatter and
/// Channel and is used to configure arbitrary
/// channels and formatters.
///
/// A property is basically a name-value pair. For
/// simplicity, both names and values are strings.
/// Every property controls a certain aspect of a
/// Formatter or Channel. For example, the PatternFormatter's
/// formatting pattern is set via a property.
{
public:
Configurable();
/// Creates the Configurable.
virtual ~Configurable();
/// Destroys the Configurable.
virtual void setProperty(const std::string& name, const std::string& value) = 0;
/// Sets the property with the given name to the given value.
/// If a property with the given name is not supported, a
/// PropertyNotSupportedException is thrown.
virtual std::string getProperty(const std::string& name) const = 0;
/// Returns the value of the property with the given name.
/// If a property with the given name is not supported, a
/// PropertyNotSupportedException is thrown.
};
Foundation_END
#endif // Foundation_Configurable_INCLUDED

View File

@ -0,0 +1,98 @@
//
// ConsoleChannel.h
//
// $Id: //poco/1.1.0/Foundation/include/Foundation/ConsoleChannel.h#2 $
//
// Library: Foundation
// Package: Logging
// Module: ConsoleChannel
//
// Definition of the ConsoleChannel class.
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#ifndef Foundation_ConsoleChannel_INCLUDED
#define Foundation_ConsoleChannel_INCLUDED
#ifndef Foundation_Foundation_INCLUDED
#include "Foundation/Foundation.h"
#endif
#ifndef Foundation_Channel_INCLUDED
#include "Foundation/Channel.h"
#endif
#ifndef Foundation_Mutex_INCLUDED
#include "Foundation/Mutex.h"
#endif
#ifndef STD_OSTREAM_INCLUDED
#include <ostream>
#define STD_OSTREAM_INCLUDED
#endif
Foundation_BEGIN
class Foundation_API ConsoleChannel: public Channel
/// A channel that writes to an ostream.
///
/// Only the message's text is written, followed
/// by a newline.
///
/// Chain this channel to a FormattingChannel with an
/// appropriate Formatter to control what is contained
/// in the text.
///
/// Similar to StreamChannel, except that a static
/// mutex is used to protect against multiple
/// console channels concurrently writing to the
/// same stream.
{
public:
ConsoleChannel();
/// Creates the channel and attached std::clog.
ConsoleChannel(std::ostream& str);
/// Creates the channel.
void log(const Message& msg);
/// Logs the given message to the channel's stream.
protected:
~ConsoleChannel();
private:
std::ostream& _str;
static FastMutex _mutex;
};
Foundation_END
#endif // Foundation_ConsoleChannel_INCLUDED

View File

@ -0,0 +1,251 @@
//
// CountingStream.h
//
// $Id: //poco/1.1.0/Foundation/include/Foundation/CountingStream.h#2 $
//
// Library: Foundation
// Package: Streams
// Module: CountingStream
//
// Definition of the CountingStreamBuf, CountingInputStream and CountingOutputStream classes.
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#ifndef Foundation_CountingStream_INCLUDED
#define Foundation_CountingStream_INCLUDED
#ifndef Foundation_Foundation_INCLUDED
#include "Foundation/Foundation.h"
#endif
#ifndef Foundation_UnbufferedStreamBuf_INCLUDED
#include "Foundation/UnbufferedStreamBuf.h"
#endif
#ifndef STD_ISTREAM_INCLUDED
#include <istream>
#define STD_ISTREAM_INCLUDED
#endif
#ifndef STD_OSTREAM_INCLUDED
#include <ostream>
#define STD_OSTREAM_INCLUDED
#endif
Foundation_BEGIN
class Foundation_API CountingStreamBuf: public UnbufferedStreamBuf
/// This stream buffer counts all characters and lines
/// going through it.
{
public:
CountingStreamBuf();
/// Creates an unconnected CountingStreamBuf.
CountingStreamBuf(std::istream& istr);
/// Creates the CountingStreamBuf and connects it
/// to the given input stream.
CountingStreamBuf(std::ostream& ostr);
/// Creates the CountingStreamBuf and connects it
/// to the given output stream.
~CountingStreamBuf();
/// Destroys the CountingStream.
int chars() const;
/// Returns the total number of characters.
int lines() const;
/// Returns the total number of lines.
int pos() const;
/// Returns the number of characters on the current line.
void reset();
/// Resets all counters.
void setCurrentLineNumber(int line);
/// Sets the current line number.
///
/// This is mainly useful when parsing C/C++
/// preprocessed source code containing #line directives.
int getCurrentLineNumber() const;
/// Returns the current line number (same as lines()).
protected:
int readFromDevice();
int writeToDevice(char c);
private:
std::istream* _pIstr;
std::ostream* _pOstr;
int _chars;
int _lines;
int _pos;
};
class Foundation_API CountingIOS: public virtual std::ios
/// The base class for CountingInputStream and CountingOutputStream.
///
/// This class is needed to ensure the correct initialization
/// order of the stream buffer and base classes.
{
public:
CountingIOS();
/// Creates the basic stream and leaves it unconnected.
CountingIOS(std::istream& istr);
/// Creates the basic stream and connects it
/// to the given input stream.
CountingIOS(std::ostream& ostr);
/// Creates the basic stream and connects it
/// to the given output stream.
~CountingIOS();
/// Destroys the stream.
int chars() const;
/// Returns the total number of characters.
int lines() const;
/// Returns the total number of lines.
int pos() const;
/// Returns the number of characters on the current line.
void reset();
/// Resets all counters.
void setCurrentLineNumber(int line);
/// Sets the current line number.
///
/// This is mainly useful when parsing C/C++
/// preprocessed source code containing #line directives.
int getCurrentLineNumber() const;
/// Returns the current line number (same as lines()).
CountingStreamBuf* rdbuf();
/// Returns a pointer to the underlying streambuf.
protected:
CountingStreamBuf _buf;
};
class Foundation_API CountingInputStream: public CountingIOS, public std::istream
/// This stream counts all characters and lines
/// going through it. This is useful for lexers and parsers
/// that need to determine the current position in the stream.
{
public:
CountingInputStream(std::istream& istr);
/// Creates the CountingInputStream and connects it
/// to the given input stream.
~CountingInputStream();
/// Destroys the stream.
};
class Foundation_API CountingOutputStream: public CountingIOS, public std::ostream
/// This stream counts all characters and lines
/// going through it.
{
public:
CountingOutputStream();
/// Creates an unconnected CountingOutputStream.
CountingOutputStream(std::ostream& ostr);
/// Creates the CountingOutputStream and connects it
/// to the given input stream.
~CountingOutputStream();
/// Destroys the CountingOutputStream.
};
//
// inlines
//
inline int CountingStreamBuf::chars() const
{
return _chars;
}
inline int CountingStreamBuf::lines() const
{
return _lines;
}
inline int CountingStreamBuf::pos() const
{
return _pos;
}
inline int CountingStreamBuf::getCurrentLineNumber() const
{
return _lines;
}
inline int CountingIOS::chars() const
{
return _buf.chars();
}
inline int CountingIOS::lines() const
{
return _buf.lines();
}
inline int CountingIOS::pos() const
{
return _buf.pos();
}
inline int CountingIOS::getCurrentLineNumber() const
{
return _buf.getCurrentLineNumber();
}
Foundation_END
#endif // Foundation_CountingStream_INCLUDED

View File

@ -0,0 +1,420 @@
//
// DateTime.h
//
// $Id: //poco/1.1.0/Foundation/include/Foundation/DateTime.h#2 $
//
// Library: Foundation
// Package: DateTime
// Module: DateTime
//
// Definition of the DateTime class.
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#ifndef Foundation_DateTime_INCLUDED
#define Foundation_DateTime_INCLUDED
#ifndef Foundation_Foundation_INCLUDED
#include "Foundation/Foundation.h"
#endif
#ifndef Foundation_Timestamp_INCLUDED
#include "Foundation/Timestamp.h"
#endif
#ifndef Foundation_Timespan_INCLUDED
#include "Foundation/Timespan.h"
#endif
Foundation_BEGIN
class Foundation_API DateTime
/// This class represents an instant in time, expressed
/// in years, months, days, hours, minutes, seconds
/// and milliseconds based on the Gregorian calendar.
/// The class is mainly useful for conversions between
/// UTC, Julian day and Gregorian calendar dates.
///
/// Conversion calculations are based on algorithms
/// collected and described by Peter Baum at
/// http://vsg.cape.com/~pbaum/date/date0.htm
///
/// Internally, this class stores a date/time in three
/// forms for performance reasons. Only use this
/// class for conversions between date/time representations.
/// Use the Timestamp class for everything else.
{
public:
enum Months
/// Symbolic names for month numbers (1 to 12).
{
JANUARY = 1,
FEBRUARY,
MARCH,
APRIL,
MAY,
JUNE,
JULY,
AUGUST,
SEPTEMBER,
OCTOBER,
NOVEMBER,
DECEMBER
};
enum DaysOfWeek
/// Symbolic names for week day numbers (0 to 6).
{
SUNDAY = 0,
MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
SATURDAY
};
DateTime();
/// Creates a DateTime for the current date and time.
DateTime(const Timestamp& timestamp);
/// Creates a DateTime for the date and time given in
/// a Timestamp.
DateTime(int year, int month, int day, int hour = 0, int minute = 0, int second = 0, int millisecond = 0, int microsecond = 0);
/// Creates a DateTime for the given Gregorian date and time.
/// * year is from 0 to 9999.
/// * month is from 1 to 12.
/// * day is from 1 to 31.
/// * hour is from 0 to 23.
/// * minute is from 0 to 59.
/// * second is from 0 to 59.
/// * millisecond is from 0 to 999.
/// * microsecond is from 0 to 999.
DateTime(double julianDay);
/// Creates a DateTime for the given Julian day.
DateTime(Timestamp::UtcTimeVal utcTime, Timestamp::TimeDiff diff);
/// Creates a DateTime from an UtcTimeVal and a TimeDiff.
///
/// Mainly used internally by DateTime and friends.
DateTime(const DateTime& dateTime);
/// Copy constructor. Creates the DateTime from another one.
~DateTime();
/// Destroys the DateTime.
DateTime& operator = (const DateTime& dateTime);
/// Assigns another DateTime.
DateTime& operator = (const Timestamp& timestamp);
/// Assigns a Timestamp.
DateTime& operator = (double julianDay);
/// Assigns a Julian day.
DateTime& assign(int year, int month, int day, int hour = 0, int minute = 0, int second = 0, int millisecond = 0, int microseconds = 0);
/// Assigns a Gregorian date and time.
/// * year is from 0 to 9999.
/// * month is from 1 to 12.
/// * day is from 1 to 31.
/// * hour is from 0 to 23.
/// * minute is from 0 to 59.
/// * second is from 0 to 59.
/// * millisecond is from 0 to 999.
/// * microsecond is from 0 to 999.
void swap(DateTime& dateTime);
/// Swaps the DateTime with another one.
int year() const;
/// Returns the year.
int month() const;
/// Returns the month (1 to 12).
int week(int firstDayOfWeek = MONDAY) const;
/// Returns the week number within the year.
/// FirstDayOfWeek should be either SUNDAY (0) or MONDAY (1).
/// The returned week number will be from 0 to 53. Week number 1 is the week
/// containing January 4. This is in accordance to ISO 8601.
///
/// The following example assumes that firstDayOfWeek is MONDAY. For 2005, which started
/// on a Saturday, week 1 will be the week starting on Monday, January 3.
/// January 1 and 2 will fall within week 0 (or the last week of the previous year).
///
/// For 2007, which starts on a Monday, week 1 will be the week startung on Monday, January 1.
/// There will be no week 0 in 2007.
int day() const;
/// Returns the day witin the month (1 to 31).
int dayOfWeek() const;
/// Returns the weekday (0 to 6, where
/// 0 = Sunday, 1 = Monday, ..., 6 = Saturday).
int dayOfYear() const;
/// Returns the number of the day in the year.
/// January 1 is 1, February 1 is 32, etc.
int hour() const;
/// Returns the hour (0 to 23).
int hourAMPM() const;
/// Returns the hour (0 to 12).
bool isAM() const;
/// Returns true if hour < 12;
bool isPM() const;
/// Returns true if hour >= 12.
int minute() const;
/// Returns the minute (0 to 59).
int second() const;
/// Returns the second (0 to 59).
int millisecond() const;
/// Returns the millisecond (0 to 999)
int microsecond() const;
/// Returns the microsecond (0 to 999)
double julianDay() const;
/// Returns the julian day for the date.
Timestamp timestamp() const;
/// Returns the date and time expressed as a Timestamp.
Timestamp::UtcTimeVal utcTime() const;
/// Returns the date and time expressed in UTC-based
/// time. UTC base time is midnight, October 15, 1582.
/// Resolution is 100 nanoseconds.
bool operator == (const DateTime& dateTime) const;
bool operator != (const DateTime& dateTime) const;
bool operator < (const DateTime& dateTime) const;
bool operator <= (const DateTime& dateTime) const;
bool operator > (const DateTime& dateTime) const;
bool operator >= (const DateTime& dateTime) const;
DateTime operator + (const Timespan& span) const;
DateTime operator - (const Timespan& span) const;
Timespan operator - (const DateTime& dateTime) const;
DateTime& operator += (const Timespan& span);
DateTime& operator -= (const Timespan& span);
static bool isLeapYear(int year);
/// Returns true if the given year is a leap year;
/// false otherwise.
static int daysOfMonth(int year, int month);
/// Returns the number of days in the given month
/// and year. Month is from 1 to 12.
protected:
static double toJulianDay(Timestamp::UtcTimeVal utcTime);
/// Computes the Julian day for an UTC time.
static double toJulianDay(int year, int month, int day, int hour, int minute, int second, int millisecond, int microsecond);
/// Computes the Julian day for a gregorian calendar date and time.
/// See <http://vsg.cape.com/~pbaum/date/jdimp.htm>, section 2.3.1 for the algorithm.
static Timestamp::UtcTimeVal toUtcTime(double julianDay);
/// Computes the UTC time for a Julian day.
void computeGregorian();
/// Computes the Gregorian date for the stored Julian day.
/// See <http://vsg.cape.com/~pbaum/date/injdimp.htm>, section 3.3.1 for the algorithm.
private:
void checkLimit(short& lower, short& higher, short limit);
void normalize();
///utility functions used to correct the overflow in computeGregorian
Timestamp::UtcTimeVal _utcTime;
double _julianDay;
short _year;
short _month;
short _day;
short _hour;
short _minute;
short _second;
short _millisecond;
short _microsecond;
};
//
// inlines
//
inline Timestamp DateTime::timestamp() const
{
return Timestamp::fromUtcTime(_utcTime);
}
inline Timestamp::UtcTimeVal DateTime::utcTime() const
{
return _utcTime;
}
inline int DateTime::year() const
{
return _year;
}
inline int DateTime::month() const
{
return _month;
}
inline int DateTime::day() const
{
return _day;
}
inline int DateTime::hour() const
{
return _hour;
}
inline int DateTime::hourAMPM() const
{
if (_hour < 1)
return 12;
else if (_hour > 12)
return _hour - 12;
else
return _hour;
}
inline bool DateTime::isAM() const
{
return _hour < 12;
}
inline bool DateTime::isPM() const
{
return _hour >= 12;
}
inline int DateTime::minute() const
{
return _minute;
}
inline int DateTime::second() const
{
return _second;
}
inline int DateTime::millisecond() const
{
return _millisecond;
}
inline int DateTime::microsecond() const
{
return _microsecond;
}
inline double DateTime::julianDay() const
{
return _julianDay;
}
inline bool DateTime::operator == (const DateTime& dateTime) const
{
return _utcTime == dateTime._utcTime;
}
inline bool DateTime::operator != (const DateTime& dateTime) const
{
return _utcTime != dateTime._utcTime;
}
inline bool DateTime::operator < (const DateTime& dateTime) const
{
return _utcTime < dateTime._utcTime;
}
inline bool DateTime::operator <= (const DateTime& dateTime) const
{
return _utcTime <= dateTime._utcTime;
}
inline bool DateTime::operator > (const DateTime& dateTime) const
{
return _utcTime > dateTime._utcTime;
}
inline bool DateTime::operator >= (const DateTime& dateTime) const
{
return _utcTime >= dateTime._utcTime;
}
inline bool DateTime::isLeapYear(int year)
{
return (year % 4) == 0 && ((year % 100) != 0 || (year % 400) == 0);
}
inline void swap(DateTime& d1, DateTime& d2)
{
d1.swap(d2);
}
Foundation_END
#endif // Foundation_DateTime_INCLUDED

View File

@ -0,0 +1,125 @@
//
// DateTimeFormat.h
//
// $Id: //poco/1.1.0/Foundation/include/Foundation/DateTimeFormat.h#2 $
//
// Library: Foundation
// Package: DateTime
// Module: DateTimeFormat
//
// Definition of the DateTimeFormat class.
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#ifndef Foundation_DateTimeFormat_INCLUDED
#define Foundation_DateTimeFormat_INCLUDED
#ifndef Foundation_Foundation_INCLUDED
#include "Foundation/Foundation.h"
#endif
Foundation_BEGIN
class Foundation_API DateTimeFormat
/// Definition of date/time formats and various
/// constants used by DateTimeFormatter and DateTimeParser.
{
public:
// predefined date formats
static const std::string ISO8601_FORMAT;
/// The date/time format defined in the ISO 8601 standard.
///
/// Examples:
/// 2005-01-01T12:00:00+01:00
/// 2005-01-01T11:00:00Z
static const std::string RFC822_FORMAT;
/// The date/time format defined in RFC 822 (obsoleted by RFC 1123).
///
/// Examples:
/// Sat, 1 Jan 05 12:00:00 +0100
/// Sat, 1 Jan 05 11:00:00 GMT
static const std::string RFC1123_FORMAT;
/// The date/time format defined in RFC 1123 (obsoletes RFC 822).
///
/// Examples:
/// Sat, 1 Jan 2005 12:00:00 +0100
/// Sat, 1 Jan 2005 11:00:00 GMT
static const std::string HTTP_FORMAT;
/// The date/time format defined in the HTTP specification (RFC 2616),
/// which is basically a variant of RFC 1036 with a zero-padded day field.
///
/// Examples:
/// Sat, 01 Jan 2005 12:00:00 +0100
/// Sat, 01 Jan 2005 11:00:00 GMT
static const std::string RFC850_FORMAT;
/// The date/time format defined in RFC 850 (obsoleted by RFC 1036).
///
/// Examples:
/// Saturday, 1-Jan-05 12:00:00 +0100
/// Saturday, 1-Jan-05 11:00:00 GMT
static const std::string RFC1036_FORMAT;
/// The date/time format defined in RFC 1036 (obsoletes RFC 850).
///
/// Examples:
/// Saturday, 1 Jan 05 12:00:00 +0100
/// Saturday, 1 Jan 05 11:00:00 GMT
static const std::string ASCTIME_FORMAT;
/// The date/time format produced by the ANSI C asctime() function.
///
/// Example:
/// Sat Jan 1 12:00:00 2005
static const std::string SORTABLE_FORMAT;
/// A simple, sortable date/time format.
///
/// Example:
/// 2005-01-01 12:00:00
// names used by formatter and parser
static const std::string WEEKDAY_NAMES[7];
/// English names of week days (Sunday, Monday, Tuesday, ...).
static const std::string MONTH_NAMES[12];
/// English names of months (January, February, ...).
};
Foundation_END
#endif // Foundation_DateTimeFormat_INCLUDED

View File

@ -0,0 +1,139 @@
//
// DateTimeFormatter.h
//
// $Id: //poco/1.1.0/Foundation/include/Foundation/DateTimeFormatter.h#2 $
//
// Library: Foundation
// Package: DateTime
// Module: DateTimeFormatter
//
// Definition of the DateTimeFormatter class.
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#ifndef Foundation_DateTimeFormatter_INCLUDED
#define Foundation_DateTimeFormatter_INCLUDED
#ifndef Foundation_Foundation_INCLUDED
#include "Foundation/Foundation.h"
#endif
Foundation_BEGIN
class DateTime;
class LocalDateTime;
class Timestamp;
class Timespan;
class Foundation_API DateTimeFormatter
/// This class converts dates and times into strings, supporting a
/// variety of standard and custom formats.
{
public:
enum
{
UTC = 0xFFFF /// Special value for timeZoneDifferential denoting UTC.
};
static std::string format(const Timestamp& timestamp, const std::string& fmt, int timeZoneDifferential = UTC);
/// Formats the given timestamp according to the given format.
/// The format string is used as a template to format the date and
/// is copied character by character except for the following special characters,
/// which are replaced by the corresponding value.
///
/// * %w - abbreviated weekday (Mon, Tue, ...)
/// * %W - full weekday (Monday, Tuesday, ...)
/// * %b - abbreviated month (Jan, Feb, ...)
/// * %B - full month (January, February, ...)
/// * %d - zero-padded day of month (01 .. 31)
/// * %e - day of month (1 .. 31)
/// * %f - space-padded day of month ( 1 .. 31)
/// * %m - zero-padded month (01 .. 12)
/// * %n - month (1 .. 12)
/// * %o - space-padded month ( 1 .. 12)
/// * %y - year without century (70)
/// * %Y - year with century (1970)
/// * %H - hour (00 .. 23)
/// * %h - hour (00 .. 12)
/// * %a - am/pm
/// * %A - AM/PM
/// * %M - minute (00 .. 59)
/// * %S - second (00 .. 59)
/// * %i - millisecond (000 .. 999)
/// * %c - centisecond (0 .. 9)
/// * %z - time zone differential in ISO 8601 format (Z or +NN.NN).
/// * %Z - time zone differential in RFC format (GMT or +NNNN)
/// * %% - percent sign
///
/// Class DateTimeFormat defines format strings for various standard date/time formats.
static std::string format(const DateTime& dateTime, const std::string& fmt, int timeZoneDifferential = UTC);
/// Formats the given date and time according to the given format.
/// See format(const Timestamp&, const std::string&, int) for more information.
static std::string format(const LocalDateTime& dateTime, const std::string& fmt);
/// Formats the given local date and time according to the given format.
/// See format(const Timestamp&, const std::string&, int) for more information.
static std::string format(const Timespan& timespan, const std::string& fmt = "%dd %H:%M:%S.%i");
/// Formats the given timespan according to the given format.
/// The format string is used as a template to format the date and
/// is copied character by character except for the following special characters,
/// which are replaced by the corresponding value.
///
/// * %d - days
/// * %H - hours (00 .. 23)
/// * %h - total hours (0 .. n)
/// * %M - minutes (00 .. 59)
/// * %m - total minutes (0 .. n)
/// * %S - seconds (00 .. 59)
/// * %s - total seconds (0 .. n)
/// * %i - milliseconds (000 .. 999)
/// * %c - centisecond (0 .. 9)
/// * %% - percent sign
static std::string tzdISO(int timeZoneDifferential);
/// Formats the given timezone differential in ISO format.
/// If timeZoneDifferential is UTC, "Z" is returned,
/// otherwise, +HH.MM (or -HH.MM) is returned.
static std::string tzdRFC(int timeZoneDifferential);
/// Formats the given timezone differential in RFC format.
/// If timeZoneDifferential is UTC, "GMT" is returned,
/// otherwise ++HHMM (or -HHMM) is returned.
};
Foundation_END
#endif // Foundation_DateTimeFormatter_INCLUDED

View File

@ -0,0 +1,123 @@
//
// DateTimeParser.h
//
// $Id: //poco/1.1.0/Foundation/include/Foundation/DateTimeParser.h#2 $
//
// Library: Foundation
// Package: DateTime
// Module: DateTimeParser
//
// Definition of the DateTimeParser class.
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#ifndef Foundation_DateTimeParser_INCLUDED
#define Foundation_DateTimeParser_INCLUDED
#ifndef Foundation_Foundation_INCLUDED
#include "Foundation/Foundation.h"
#endif
#ifndef Foundation_DateTime_INCLUDED
#include "Foundation/DateTime.h"
#endif
Foundation_BEGIN
class Foundation_API DateTimeParser
/// This class provides a method for parsing dates and times
/// from strings. All parsing methods do their best to
/// parse a meaningful result, even from malformed input
/// strings.
///
/// Note: When parsing a time in 12-hour (AM/PM) format, the hour
/// (%h) must be parsed before the AM/PM designator (%a, %A),
/// otherwise the AM/PM designator will be ignored.
{
public:
static void parse(const std::string& fmt, const std::string& str, DateTime& dateTime, int& timeZoneDifferential);
/// Parses a date and time in the given format from the given string.
/// Throws a SyntaxException if the string cannot be successfully parsed.
/// Please see DateTimeFormatter::format() for a description of the format string.
/// Class DateTimeFormat defines format strings for various standard date/time formats.
static DateTime parse(const std::string& fmt, const std::string& str, int& timeZoneDifferential);
/// Parses a date and time in the given format from the given string.
/// Throws a SyntaxException if the string cannot be successfully parsed.
/// Please see DateTimeFormatter::format() for a description of the format string.
/// Class DateTimeFormat defines format strings for various standard date/time formats.
static bool tryParse(const std::string& fmt, const std::string& str, DateTime& dateTime, int& timeZoneDifferential);
/// Parses a date and time in the given format from the given string.
/// Returns true if the string has been successfully parsed, false otherwise.
/// Please see DateTimeFormatter::format() for a description of the format string.
/// Class DateTimeFormat defines format strings for various standard date/time formats.
static void parse(const std::string& str, DateTime& dateTime, int& timeZoneDifferential);
/// Parses a date and time from the given dateTime string. Before parsing, the method
/// examines the dateTime string for a known date/time format.
/// Throws a SyntaxException if the string cannot be successfully parsed.
/// Please see DateTimeFormatter::format() for a description of the format string.
/// Class DateTimeFormat defines format strings for various standard date/time formats.
static DateTime parse(const std::string& str, int& timeZoneDifferential);
/// Parses a date and time from the given dateTime string. Before parsing, the method
/// examines the dateTime string for a known date/time format.
/// Please see DateTimeFormatter::format() for a description of the format string.
/// Class DateTimeFormat defines format strings for various standard date/time formats.
static bool tryParse(const std::string& str, DateTime& dateTime, int& timeZoneDifferential);
/// Parses a date and time from the given dateTime string. Before parsing, the method
/// examines the dateTime string for a known date/time format.
/// Please see DateTimeFormatter::format() for a description of the format string.
/// Class DateTimeFormat defines format strings for various standard date/time formats.
static int parseMonth(std::string::const_iterator& it, const std::string::const_iterator& end);
/// Tries to interpret the given range as a month name. The range must be at least
/// three characters long.
/// Returns the month number (1 .. 12) if the month name is valid. Otherwise throws
/// a SyntaxException.
static int parseDayOfWeek(std::string::const_iterator& it, const std::string::const_iterator& end);
/// Tries to interpret the given range as a weekday name. The range must be at least
/// three characters long.
/// Returns the weekday number (0 .. 6, where 0 = Synday, 1 = Monday, etc.) if the
/// weekday name is valid. Otherwise throws a SyntaxException.
protected:
static int parseTZD(std::string::const_iterator& it, const std::string::const_iterator& end);
static int parseAMPM(std::string::const_iterator& it, const std::string::const_iterator& end, int hour);
};
Foundation_END
#endif // Foundation_DateTimeParser_INCLUDED

View File

@ -0,0 +1,97 @@
//
// Debugger.h
//
// $Id: //poco/1.1.0/Foundation/include/Foundation/Debugger.h#2 $
//
// Library: Foundation
// Package: Core
// Module: Debugger
//
// Definition of the Debugger class.
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#ifndef Foundation_Debugger_INCLUDED
#define Foundation_Debugger_INCLUDED
#ifndef Foundation_Foundation_INCLUDED
#include "Foundation/Foundation.h"
#endif
Foundation_BEGIN
class Foundation_API Debugger
/// The Debugger class provides an interface to the debugger.
/// The presence of a debugger can be checked for,
/// messages can be written to the debugger's log window
/// and a break into the debugger can be enforced.
/// The methods only work if the program is compiled
/// in debug mode (the macro _DEBUG is defined).
{
public:
static bool isAvailable();
/// Returns true if a debugger is available, false otherwise.
/// On Windows, this function uses the IsDebuggerPresent()
/// function.
/// On Unix, this function returns true if the environment
/// variable POCO_ENABLE_DEBUGGER is set.
/// On OpenVMS, this function always returns true in debug,
/// mode, false otherwise.
static void message(const std::string& msg);
/// Writes a message to the debugger log, if available, otherwise to
/// standard error output.
static void message(const std::string& msg, const char* file, int line);
/// Writes a message to the debugger log, if available, otherwise to
/// standard error output.
static void enter();
/// Breaks into the debugger, if it is available.
/// On Windows, this is done using the DebugBreak() function.
/// On Unix, the SIGINT signal is raised.
/// On OpenVMS, the SS$_DEBUG signal is raised.
static void enter(const std::string& msg);
/// Writes a debug message to the debugger log and breaks into it.
static void enter(const std::string& msg, const char* file, int line);
/// Writes a debug message to the debugger log and breaks into it.
static void enter(const char* file, int line);
/// Writes a debug message to the debugger log and breaks into it.
};
Foundation_END
#endif // Foundation_Debugger_INCLUDED

View File

@ -0,0 +1,154 @@
//
// DefaultStrategy.h
//
// $Id: //poco/1.1.0/Foundation/include/Foundation/DefaultStrategy.h#2 $
//
// Library: Foundation
// Package: Events
// Module: DefaultStrategy
//
// Implementation of the DefaultStrategy template.
//
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#ifndef Foundation_DefaultStrategy_INCLUDED
#define Foundation_DefaultStrategy_INCLUDED
#include "Foundation/NotificationStrategy.h"
#include <memory>
#include <set>
#include <vector>
Foundation_BEGIN
template <class TArgs, class TDelegate, class TCompare>
class DefaultStrategy: public NotificationStrategy<TArgs, TDelegate>
/// Default notification strategy. Allows one observer
/// to register exactly once. The observer must provide an
/// < (less-than) operator.
{
public:
typedef std::set<TDelegate*, TCompare> Delegates;
typedef typename Delegates::iterator Iterator;
typedef typename Delegates::const_iterator ConstIterator;
public:
DefaultStrategy()
{
}
DefaultStrategy(const DefaultStrategy& s)
{
operator = (s);
}
~DefaultStrategy()
{
clear();
}
void notify(const void* sender, TArgs& arguments)
{
std::vector<Iterator> delMe;
for (Iterator it = _observers.begin(); it != _observers.end(); it++)
{
if (!(*it)->notify(sender, arguments))
{
// schedule for deletion
delMe.push_back(it);
}
}
while (!delMe.empty())
{
typename std::vector<Iterator>::iterator vit = delMe.end();
--vit;
delete **vit;
_observers.erase(*vit);
delMe.pop_back();
}
}
void add(const TDelegate& delegate)
{
Iterator it = _observers.find(const_cast<TDelegate*>(&delegate));
if (it != _observers.end())
{
delete *it;
_observers.erase(it);
}
std::auto_ptr<TDelegate> pDelegate(delegate.clone());
bool tmp = _observers.insert(pDelegate.get()).second;
poco_assert (tmp);
pDelegate.release();
}
void remove(const TDelegate& delegate)
{
Iterator it = _observers.find(const_cast<TDelegate*>(&delegate));
if (it != _observers.end())
{
delete *it;
_observers.erase(it);
}
}
DefaultStrategy& operator = (const DefaultStrategy& s)
{
if (this != &s)
{
for (ConstIterator it = s._observers.begin(); it != s._observers.end(); ++it)
{
add(**it);
}
}
return *this;
}
void clear()
{
for (Iterator it = _observers.begin(); it != _observers.end(); ++it)
{
delete *it;
}
_observers.clear();
}
protected:
Delegates _observers;
};
Foundation_END
#endif

View File

@ -0,0 +1,153 @@
//
// DeflatingStream.h
//
// $Id: //poco/1.1.0/Foundation/include/Foundation/DeflatingStream.h#2 $
//
// Library: Foundation
// Package: Streams
// Module: ZLibStream
//
// Definition of the DeflatingStream class.
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#ifndef Foundation_DeflatingStream_INCLUDED
#define Foundation_DeflatingStream_INCLUDED
#ifndef Foundation_Foundation_INCLUDED
#include "Foundation/Foundation.h"
#endif
#ifndef Foundation_BufferedStreamBuf_INCLUDED
#include "Foundation/BufferedStreamBuf.h"
#endif
#ifndef STD_ISTREAM_INCLUDED
#include <istream>
#define STD_ISTREAM_INCLUDED
#endif
#ifndef STD_OSTREAM_INCLUDED
#include <ostream>
#define STD_OSTREAM_INCLUDED
#endif
#ifndef ZLIB_H
#include "Foundation/zlib.h"
#endif
Foundation_BEGIN
class Foundation_API DeflatingStreamBuf: public BufferedStreamBuf
/// This is the streambuf class used by DeflatingInputStream and DeflatingOutputStream.
/// The actual work is delegated to zlib 1.2.1 (see http://www.gzip.org).
/// Both zlib (deflate) streams and gzip streams are supported.
/// Output streams should always call close() to ensure
/// proper completion of compression.
/// A compression level (0 to 9) can be specified in the constructor.
{
public:
enum StreamType
{
STREAM_ZLIB,
STREAM_GZIP
};
DeflatingStreamBuf(std::istream& istr, StreamType type, int level);
DeflatingStreamBuf(std::ostream& ostr, StreamType type, int level);
~DeflatingStreamBuf();
int close();
protected:
int readFromDevice(char* buffer, std::streamsize length);
int writeToDevice(const char* buffer, std::streamsize length);
private:
enum
{
STREAM_BUFFER_SIZE = 1024,
DEFLATE_BUFFER_SIZE = 32768
};
std::istream* _pIstr;
std::ostream* _pOstr;
char* _buffer;
z_stream _zstr;
bool _eof;
};
class Foundation_API DeflatingIOS: public virtual std::ios
/// The base class for DeflatingOutputStream and DeflatingInputStream.
///
/// This class is needed to ensure the correct initialization
/// order of the stream buffer and base classes.
{
public:
DeflatingIOS(std::ostream& ostr, DeflatingStreamBuf::StreamType type = DeflatingStreamBuf::STREAM_ZLIB, int level = Z_DEFAULT_COMPRESSION);
DeflatingIOS(std::istream& istr, DeflatingStreamBuf::StreamType type = DeflatingStreamBuf::STREAM_ZLIB, int level = Z_DEFAULT_COMPRESSION);
~DeflatingIOS();
DeflatingStreamBuf* rdbuf();
protected:
DeflatingStreamBuf _buf;
};
class Foundation_API DeflatingOutputStream: public DeflatingIOS, public std::ostream
/// This stream compresses all data passing through it
/// using zlib's deflate algorithm.
/// After all data has been written to the stream, close()
/// must be called to ensure completion of compression.
/// Example:
/// std::ofstream ostr("data.gz", std::ios::binary);
/// DeflatingOutputStream deflater(ostr, DeflatingStreamBuf::STREAM_GZIP);
/// deflater << "Hello, world!" << std::endl;
/// deflater.close();
/// ostr.close();
{
public:
DeflatingOutputStream(std::ostream& ostr, DeflatingStreamBuf::StreamType type = DeflatingStreamBuf::STREAM_ZLIB, int level = Z_DEFAULT_COMPRESSION);
~DeflatingOutputStream();
int close();
};
class Foundation_API DeflatingInputStream: public DeflatingIOS, public std::istream
/// This stream compresses all data passing through it
/// using zlib's deflate algorithm.
{
public:
DeflatingInputStream(std::istream& istr, DeflatingStreamBuf::StreamType type = DeflatingStreamBuf::STREAM_ZLIB, int level = Z_DEFAULT_COMPRESSION);
~DeflatingInputStream();
};
Foundation_END
#endif // Foundation_DeflatingStream_INCLUDED

View File

@ -0,0 +1,120 @@
//
// Delegate.h
//
// $Id: //poco/1.1.0/Foundation/include/Foundation/Delegate.h#2 $
//
// Library: Foundation
// Package: Events
// Module: Delegate
//
// Implementation of the Delegate template.
//
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#ifndef Foundation_Delegate_INCLUDED
#define Foundation_Delegate_INCLUDED
#include "Foundation/Foundation.h"
#include "Foundation/AbstractDelegate.h"
#include "Foundation/Expire.h"
Foundation_BEGIN
template <class TObj, class TArgs>
class Delegate: public AbstractDelegate<TArgs>
{
public:
typedef void (TObj::*NotifyMethod)(const void*, TArgs&);
Delegate(TObj* obj, NotifyMethod method):
_receiverObject(obj),
_receiverMethod(method)
{
}
Delegate(const Delegate& delegate):
_receiverObject(delegate._receiverObject),
_receiverMethod(delegate._receiverMethod)
{
}
~Delegate()
{
}
Delegate& operator = (const Delegate& delegate)
{
if (&delegate != this)
{
_receiverObject = delegate._receiverObject;
_receiverMethod = delegate._receiverMethod;
}
return *this;
}
bool notify(const void* sender, TArgs& arguments)
{
(_receiverObject->*_receiverMethod)(sender, arguments);
return true; // a "standard" delegate never expires
}
AbstractDelegate<TArgs>* clone() const
{
return new Delegate(*this);
}
bool operator < (const AbstractDelegate<TArgs>& other) const
{
const Delegate<TObj, TArgs>* pOther = dynamic_cast<const Delegate<TObj, TArgs>*>(&other);
if (pOther == 0)
{
const Expire<TArgs>* pExpire = dynamic_cast<const Expire<TArgs>*>(&other);
poco_check_ptr(pExpire);
return this->operator < (pExpire->getDelegate());
}
return _receiverObject < pOther->_receiverObject;
}
protected:
TObj* _receiverObject;
NotifyMethod _receiverMethod;
private:
Delegate();
};
Foundation_END
#endif

View File

@ -0,0 +1,130 @@
//
// DigestEngine.h
//
// $Id: //poco/1.1.0/Foundation/include/Foundation/DigestEngine.h#2 $
//
// Library: Foundation
// Package: Crypt
// Module: DigestEngine
//
// Definition of class DigestEngine.
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#ifndef Foundation_DigestEngine_INCLUDED
#define Foundation_DigestEngine_INCLUDED
#ifndef Foundation_Foundation_INCLUDED
#include "Foundation/Foundation.h"
#endif
#ifndef STD_VECTOR_INCLUDED
#include <vector>
#define STD_VECTOR_INCLUDED
#endif
Foundation_BEGIN
class Foundation_API DigestEngine
/// This class is an abstract base class
/// for all classes implementing a message
/// digest algorithm, like MD5Engine
/// and SHA1Engine.
/// Call update() repeatedly with data to
/// compute the digest from. When done,
/// call digest() to obtain the message
/// digest.
{
public:
typedef std::vector<unsigned char> Digest;
DigestEngine();
virtual ~DigestEngine();
void update(const void* data, unsigned length);
void update(char data);
void update(const std::string& data);
/// Updates the digest with the given data.
virtual unsigned digestLength() const = 0;
/// Returns the length of the digest in bytes.
virtual void reset() = 0;
/// Resets the engine so that a new
/// digest can be computed.
virtual const Digest& digest() = 0;
/// Finishes the computation of the digest and
/// returns the message digest. Resets the engine
/// and can thus only be called once for every digest.
/// The returned reference is valid until the next
/// time digest() is called, or the engine object is destroyed.
static std::string digestToHex(const Digest& bytes);
/// Converts a message digest into a string of hexadecimal numbers.
protected:
virtual void updateImpl(const void* data, unsigned length) = 0;
/// Updates the digest with the given data. Must be implemented
/// by subclasses.
private:
DigestEngine(const DigestEngine&);
DigestEngine& operator = (const DigestEngine&);
};
//
// inlines
//
inline void DigestEngine::update(const void* data, unsigned length)
{
updateImpl(data, length);
}
inline void DigestEngine::update(char data)
{
updateImpl(&data, 1);
}
inline void DigestEngine::update(const std::string& data)
{
updateImpl(data.data(), (unsigned) data.size());
}
Foundation_END
#endif // Foundation_DigestEngine_INCLUDED

View File

@ -0,0 +1,134 @@
//
// DigestStream.h
//
// $Id: //poco/1.1.0/Foundation/include/Foundation/DigestStream.h#2 $
//
// Library: Foundation
// Package: Crypt
// Module: DigestStream
//
// Definition of classes DigestInputStream and DigestOutputStream.
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#ifndef Foundation_DigestStream_INCLUDED
#define Foundation_DigestStream_INCLUDED
#ifndef Foundation_Foundation_INCLUDED
#include "Foundation/Foundation.h"
#endif
#ifndef Foundation_BufferedStreamBuf_INCLUDED
#include "Foundation/BufferedStreamBuf.h"
#endif
#ifndef Foundation_DigestEngine_INCLUDED
#include "Foundation/DigestEngine.h"
#endif
#ifndef STD_ISTREAM_INCLUDED
#include <istream>
#define STD_ISTREAM_INCLUDED
#endif
#ifndef STD_OSTREAM_INCLUDED
#include <ostream>
#define STD_OSTREAM_INCLUDED
#endif
Foundation_BEGIN
class Foundation_API DigestBuf: public BufferedStreamBuf
/// This streambuf computes a digest of all data going
/// through it.
{
public:
DigestBuf(DigestEngine& eng);
DigestBuf(DigestEngine& eng, std::istream& istr);
DigestBuf(DigestEngine& eng, std::ostream& ostr);
~DigestBuf();
int readFromDevice(char* buffer, std::streamsize length);
int writeToDevice(const char* buffer, std::streamsize length);
void close();
private:
DigestEngine& _eng;
std::istream* _pIstr;
std::ostream* _pOstr;
static const int BUFFER_SIZE;
};
class Foundation_API DigestIOS: public virtual std::ios
/// The base class for DigestInputStream and DigestOutputStream.
///
/// This class is needed to ensure the correct initialization
/// order of the stream buffer and base classes.
{
public:
DigestIOS(DigestEngine& eng);
DigestIOS(DigestEngine& eng, std::istream& istr);
DigestIOS(DigestEngine& eng, std::ostream& ostr);
~DigestIOS();
DigestBuf* rdbuf();
protected:
DigestBuf _buf;
};
class Foundation_API DigestInputStream: public DigestIOS, public std::istream
/// This istream computes a digest of
/// all the data passing through it,
/// using a DigestEngine.
{
public:
DigestInputStream(DigestEngine& eng, std::istream& istr);
~DigestInputStream();
};
class Foundation_API DigestOutputStream: public DigestIOS, public std::ostream
/// This ostream computes a digest of
/// all the data passing through it,
/// using a DigestEngine.
/// To ensure that all data has been incorporated
/// into the digest, call close() or flush() before
/// you obtain the digest from the digest engine.
{
public:
DigestOutputStream(DigestEngine& eng);
DigestOutputStream(DigestEngine& eng, std::ostream& ostr);
~DigestOutputStream();
void close();
};
Foundation_END
#endif // Foundation_DigestStream_INCLUDED

Some files were not shown because too many files have changed in this diff Show More