submitted 1.2.0

This commit is contained in:
Guenter Obiltschnig
2006-08-29 07:10:35 +00:00
parent f476bd6b32
commit 2d4078f392
1428 changed files with 25715 additions and 12456 deletions

View File

@@ -0,0 +1,68 @@
//
// ASCIIEncoding.h
//
// $Id: //poco/1.2/Foundation/include/Poco/ASCIIEncoding.h#1 $
//
// 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
#include "Poco/Foundation.h"
#include "Poco/TextEncoding.h"
namespace Poco {
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;
};
} // namespace Poco
#endif // Foundation_ASCIIEncoding_INCLUDED

View File

@@ -0,0 +1,257 @@
//
// AbstractCache.h
//
// $Id: //poco/1.2/Foundation/include/Poco/AbstractCache.h#1 $
//
// 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 "Poco/KeyValueArgs.h"
#include "Poco/ValidArgs.h"
#include "Poco/Mutex.h"
#include "Poco/Exception.h"
#include "Poco/BasicEvent.h"
#include "Poco/EventArgs.h"
#include "Poco/Delegate.h"
#include "Poco/SharedPtr.h"
#include <map>
#include <set>
namespace Poco {
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 != endIt; ++it)
{
doRemove(*it);
}
}
TStrategy _strategy;
mutable DataHolder _data;
mutable FastMutex _mutex;
private:
AbstractCache(const AbstractCache& aCache);
AbstractCache& operator = (const AbstractCache& aCache);
};
} // namespace Poco
#endif

View File

@@ -0,0 +1,79 @@
//
// AbstractDelegate.h
//
// $Id: //poco/1.2/Foundation/include/Poco/AbstractDelegate.h#1 $
//
// 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 "Poco/Foundation.h"
namespace Poco {
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.
};
} // namespace Poco
#endif

View File

@@ -0,0 +1,300 @@
//
// AbstractEvent.h
//
// $Id: //poco/1.2/Foundation/include/Poco/AbstractEvent.h#1 $
//
// 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 "Poco/Foundation.h"
#include "Poco/SingletonHolder.h"
#include "Poco/SharedPtr.h"
#include "Poco/ActiveResult.h"
#include "Poco/ActiveMethod.h"
#include "Poco/Mutex.h"
namespace Poco {
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:
/// Poco::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():
_executeAsync(this, &AbstractEvent::executeAsyncImpl),
_enabled(true)
{
}
AbstractEvent(const TStrategy& strat):
_executeAsync(this, &AbstractEvent::executeAsyncImpl),
_strategy(strat),
_enabled(true)
{
}
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.
{
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);
}
}
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 = SharedPtr<TStrategy>(new TStrategy(_strategy));
params.pSender = pSender;
params.args = args;
params.enabled = _enabled;
}
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
{
SharedPtr<TStrategy> ptrStrat;
const void* pSender;
TArgs args;
bool enabled;
};
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 FastMutex _mutex;
private:
AbstractEvent(const AbstractEvent& other);
AbstractEvent& operator = (const AbstractEvent& other);
};
} // namespace Poco
#endif

View File

@@ -0,0 +1,79 @@
//
// AbstractPriorityDelegate.h
//
// $Id: //poco/1.2/Foundation/include/Poco/AbstractPriorityDelegate.h#1 $
//
// 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 "Poco/Foundation.h"
namespace Poco {
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.
};
} // namespace Poco
#endif

View File

@@ -0,0 +1,91 @@
//
// AbstractStrategy.h
//
// $Id: //poco/1.2/Foundation/include/Poco/AbstractStrategy.h#1 $
//
// 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 "Poco/KeyValueArgs.h"
#include "Poco/ValidArgs.h"
#include "Poco/EventArgs.h"
namespace Poco {
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.
};
} // namespace Poco
#endif

View File

@@ -0,0 +1,137 @@
//
// ActiveDispatcher.h
//
// $Id: //poco/1.2/Foundation/include/Poco/ActiveDispatcher.h#1 $
//
// Library: Foundation
// Package: Threading
// Module: ActiveObjects
//
// Definition of the ActiveDispatcher 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_ActiveDispatcher_INCLUDED
#define Foundation_ActiveDispatcher_INCLUDED
#include "Poco/Foundation.h"
#include "Poco/Runnable.h"
#include "Poco/Thread.h"
#include "Poco/ActiveStarter.h"
#include "Poco/NotificationQueue.h"
namespace Poco {
class Foundation_API ActiveDispatcher: protected Runnable
/// This class is used to implement an active object
/// with strictly serialized method execution.
///
/// An active object, with is an ordinary object
/// containing ActiveMethod members, executes all
/// active methods in their own thread.
/// This behavior does not fit the "classic"
/// definition of an active object, which serializes
/// the execution of active methods (in other words,
/// only one active method can be running at any given
/// time).
///
/// Using this class as a base class, the serializing
/// behavior for active objects can be implemented.
///
/// The following example shows how this is done:
///
/// class ActiveObject: public ActiveDispatcher
/// {
/// public:
/// ActiveObject():
/// exampleActiveMethod(this, &ActiveObject::exampleActiveMethodImpl)
/// {
/// }
///
/// ActiveMethod<std::string, std::string, ActiveObject, ActiveStarter<ActiveDispatcher> > exampleActiveMethod;
///
/// protected:
/// std::string exampleActiveMethodImpl(const std::string& arg)
/// {
/// ...
/// }
/// };
///
/// The only things different from the example in
/// ActiveMethod is that the ActiveObject in this case
/// inherits from ActiveDispatcher, and that the ActiveMethod
/// template for exampleActiveMethod has an additional parameter,
/// specifying the specialized ActiveStarter for ActiveDispatcher.
{
public:
ActiveDispatcher();
/// Creates the ActiveDispatcher.
ActiveDispatcher(Thread::Priority prio);
/// Creates the ActiveDispatcher and sets
/// the priority of its thread.
virtual ~ActiveDispatcher();
/// Destroys the ActiveDispatcher.
void start(Runnable* pRunnable);
/// Adds the Runnable to the dispatch queue.
void cancel();
/// Cancels all queued methods.
protected:
void run();
void stop();
private:
Thread _thread;
NotificationQueue _queue;
};
template <>
class ActiveStarter<ActiveDispatcher>
/// A specialization of ActiveStarter
/// for ActiveDispatcher.
{
public:
static void start(ActiveDispatcher* pOwner, Runnable* pRunnable)
{
pOwner->start(pRunnable);
}
};
} // namespace Poco
#endif // Foundation_ActiveDispatcher_INCLUDED

View File

@@ -0,0 +1,130 @@
//
// ActiveMethod.h
//
// $Id: //poco/1.2/Foundation/include/Poco/ActiveMethod.h#1 $
//
// 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
#include "Poco/Foundation.h"
#include "Poco/ActiveResult.h"
#include "Poco/ActiveRunnable.h"
#include "Poco/ActiveStarter.h"
namespace Poco {
template <class ResultType, class ArgType, class OwnerType, class StarterType = ActiveStarter<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;
///
/// The way an ActiveMethod is started can be changed by passing a StarterType
/// template argument with a corresponding class. The default ActiveStarter
/// starts the method in its own thread, obtained from a thread pool.
///
/// For an alternative implementation of StarterType, see ActiveDispatcher.
///
/// For methods that do not require an argument or a return value, the Void
/// class can be used.
{
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);
StarterType::start(_pOwner, pRunnable);
return result;
}
private:
ActiveMethod();
ActiveMethod(const ActiveMethod&);
ActiveMethod& operator = (const ActiveMethod&);
OwnerType* _pOwner;
Callback _method;
};
} // namespace Poco
#endif // Foundation_ActiveMethod_INCLUDED

View File

@@ -0,0 +1,289 @@
//
// ActiveResult.h
//
// $Id: //poco/1.2/Foundation/include/Poco/ActiveResult.h#1 $
//
// 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
#include "Poco/Foundation.h"
#include "Poco/Mutex.h"
#include "Poco/Event.h"
#include "Poco/RefCountedObject.h"
#include "Poco/Exception.h"
namespace Poco {
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():
_pExc(0),
_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 _pExc != 0;
}
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.
{
if (_pExc)
return _pExc->message();
else
return std::string();
}
Exception* exception() const
/// If the active method threw an exception, a clone of the exception
/// object is returned, otherwise null.
{
return _pExc;
}
void error(const Exception& exc)
/// Sets the exception.
{
delete _pExc;
_pExc = exc.clone();
}
void error(const std::string& msg)
/// Sets the exception.
{
delete _pExc;
_pExc = new UnhandledException(msg);
}
protected:
~ActiveResultHolder()
{
delete _pExc;
}
private:
ResultType _data;
Exception* _pExc;
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();
}
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();
}
Exception* exception() const
/// If the active method threw an exception, a clone of the exception
/// object is returned, otherwise null.
{
return _pHolder->exception();
}
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);
}
void error(const Exception& exc)
/// Sets the failed flag and the exception message.
{
_pHolder->error(exc);
}
private:
ActiveResult();
ActiveResultHolderType* _pHolder;
};
} // namespace Poco
#endif // Foundation_ActiveResult_INCLUDED

View File

@@ -0,0 +1,103 @@
//
// ActiveRunnable.h
//
// $Id: //poco/1.2/Foundation/include/Poco/ActiveRunnable.h#1 $
//
// Library: Foundation
// Package: Threading
// Module: ActiveObjects
//
// Definition of the ActiveRunnable 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_ActiveRunnable_INCLUDED
#define Foundation_ActiveRunnable_INCLUDED
#include "Poco/Foundation.h"
#include "Poco/ActiveResult.h"
#include "Poco/Runnable.h"
#include "Poco/Exception.h"
namespace Poco {
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);
}
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;
};
} // namespace Poco
#endif // Foundation_ActiveRunnable_INCLUDED

View File

@@ -0,0 +1,71 @@
//
// ActiveStarter.h
//
// $Id: //poco/1.2/Foundation/include/Poco/ActiveStarter.h#1 $
//
// Library: Foundation
// Package: Threading
// Module: ActiveObjects
//
// Definition of the ActiveStarter 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_ActiveStarter_INCLUDED
#define Foundation_ActiveStarter_INCLUDED
#include "Poco/Foundation.h"
#include "Poco/ThreadPool.h"
namespace Poco {
class Runnable;
template <class OwnerType>
class ActiveStarter
/// The default implementation of the StarterType
/// policy for ActiveMethod. It starts the method
/// in its own thread, obtained from the default
/// thread pool.
{
public:
static void start(OwnerType* pOwner, Runnable* pRunnable)
{
ThreadPool::defaultPool().start(*pRunnable);
}
};
} // namespace Poco
#endif // Foundation_ActiveStarter_INCLUDED

View File

@@ -0,0 +1,218 @@
//
// Activity.h
//
// $Id: //poco/1.2/Foundation/include/Poco/Activity.h#1 $
//
// 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
#include "Poco/Foundation.h"
#include "Poco/RunnableAdapter.h"
#include "Poco/ThreadPool.h"
#include "Poco/Event.h"
#include "Poco/Mutex.h"
namespace Poco {
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;
};
} // namespace Poco
#endif // Foundation_Activity_INCLUDED

View File

@@ -0,0 +1,286 @@
//
// Any.h
//
// $Id: //poco/1.2/Foundation/include/Poco/Any.h#1 $
//
// Library: Foundation
// Package: Core
// Module: Any
//
// Copyright Kevlin Henney, 2000, 2001, 2002. All rights reserved.
// Extracted from Boost 1.33.1 lib and adapted for poco: Peter Schojer/AppliedInformatics 2006-02-02
//
// 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_Any_INCLUDED
#define Foundation_Any_INCLUDED
#include "Poco/Exception.h"
#include <algorithm>
#include <typeinfo>
namespace Poco {
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.
{
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 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 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));
}
} // namespace Poco
#endif

View File

@@ -0,0 +1,129 @@
//
// ArchiveStrategy.h
//
// $Id: //poco/1.2/Foundation/include/Poco/ArchiveStrategy.h#1 $
//
// 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
#include "Poco/Foundation.h"
#include "Poco/LogFile.h"
#include "Poco/File.h"
#include "Poco/DateTimeFormatter.h"
namespace Poco {
class ArchiveCompressor;
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;
ArchiveCompressor* _pCompressor;
};
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);
}
};
} // namespace Poco
#endif // Foundation_ArchiveStrategy_INCLUDED

View File

@@ -0,0 +1,110 @@
//
// AsyncChannel.h
//
// $Id: //poco/1.2/Foundation/include/Poco/AsyncChannel.h#1 $
//
// 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
#include "Poco/Foundation.h"
#include "Poco/Channel.h"
#include "Poco/Thread.h"
#include "Poco/Mutex.h"
#include "Poco/Runnable.h"
#include "Poco/NotificationQueue.h"
namespace Poco {
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;
};
} // namespace Poco
#endif // Foundation_AsyncChannel_INCLUDED

View File

@@ -0,0 +1,331 @@
//
// AutoPtr.h
//
// $Id: //poco/1.2/Foundation/include/Poco/AutoPtr.h#1 $
//
// 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
#include "Poco/Foundation.h"
#include "Poco/Exception.h"
#include <algorithm>
namespace Poco {
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
/// object.
///
/// 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.
/// Note that AutoPtr allows casting of its encapsulated data types.
{
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;
}
template <class Other>
AutoPtr < Other > cast()
/// Casts the AutoPtr via a dynamic cast to the given type.
/// Returns an AutoPtr containing NULL if the cast fails.
/// Example: (assume class Sub: public Super)
/// AutoPtr < Super > super(new Sub());
/// AutoPtr < Sub > sub = super.cast<Sub>();
/// poco_assert (sub.get());
{
Other* pOther = dynamic_cast <Other*>(_ptr);
if (pOther)
pOther->duplicate();
return AutoPtr < Other > (pOther);
}
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);
}
} // namespace Poco
#endif // Foundation_AutoPtr_INCLUDED

View File

@@ -0,0 +1,108 @@
//
// AutoReleasePool.h
//
// $Id: //poco/1.2/Foundation/include/Poco/AutoReleasePool.h#1 $
//
// 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
#include "Poco/Foundation.h"
#include <list>
namespace Poco {
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;
};
} // namespace Poco
#endif // Foundation_AutoReleasePool_INCLUDED

View File

@@ -0,0 +1,102 @@
//
// Base64Decoder.h
//
// $Id: //poco/1.2/Foundation/include/Poco/Base64Decoder.h#1 $
//
// 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
#include "Poco/Foundation.h"
#include "Poco/UnbufferedStreamBuf.h"
#include <istream>
namespace Poco {
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();
};
} // namespace Poco
#endif // Foundation_Base64Decoder_INCLUDED

View File

@@ -0,0 +1,112 @@
//
// Base64Encoder.h
//
// $Id: //poco/1.2/Foundation/include/Poco/Base64Encoder.h#1 $
//
// 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
#include "Poco/Foundation.h"
#include "Poco/UnbufferedStreamBuf.h"
#include <ostream>
namespace Poco {
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();
};
} // namespace Poco
#endif // Foundation_Base64Encoder_INCLUDED

View File

@@ -0,0 +1,88 @@
//
// BasicEvent.h
//
// $Id: //poco/1.2/Foundation/include/Poco/BasicEvent.h#1 $
//
// 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 "Poco/AbstractEvent.h"
#include "Poco/DefaultStrategy.h"
#include "Poco/AbstractDelegate.h"
#include "Poco/CompareFunctions.h"
namespace Poco {
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);
};
} // namespace Poco
#endif

View File

@@ -0,0 +1,187 @@
//
// BinaryReader.h
//
// $Id: //poco/1.2/Foundation/include/Poco/BinaryReader.h#1 $
//
// 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
#include "Poco/Foundation.h"
#include <istream>
namespace Poco {
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
}
} // namespace Poco
#endif // Foundation_BinaryReader_INCLUDED

View File

@@ -0,0 +1,199 @@
//
// BinaryWriter.h
//
// $Id: //poco/1.2/Foundation/include/Poco/BinaryWriter.h#1 $
//
// 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
#include "Poco/Foundation.h"
#include <ostream>
namespace Poco {
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
}
} // namespace Poco
#endif // Foundation_BinaryWriter_INCLUDED

View File

@@ -0,0 +1,129 @@
//
// Buffer.h
//
// $Id: //poco/1.2/Foundation/include/Poco/Buffer.h#1 $
//
// 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
#include "Poco/Foundation.h"
namespace Poco {
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;
};
} // namespace Poco
#endif // Foundation_Buffer_INCLUDED

View File

@@ -0,0 +1,73 @@
//
// BufferAllocator.h
//
// $Id: //poco/1.2/Foundation/include/Poco/BufferAllocator.h#1 $
//
// 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
#include "Poco/Foundation.h"
#include <ios>
namespace Poco {
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;
}
};
} // namespace Poco
#endif // Foundation_BufferAllocator_INCLUDED

View File

@@ -0,0 +1,177 @@
//
// BufferedBidirectionalStreamBuf.h
//
// $Id: //poco/1.2/Foundation/include/Poco/BufferedBidirectionalStreamBuf.h#1 $
//
// 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
#include "Poco/Foundation.h"
#include "Poco/BufferAllocator.h"
#include "Poco/StreamUtil.h"
#include <streambuf>
#include <iosfwd>
#include <ios>
namespace Poco {
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;
} // namespace Poco
#endif // Foundation_BufferedBidirectionalStreamBuf_INCLUDED

View File

@@ -0,0 +1,174 @@
//
// BufferedStreamBuf.h
//
// $Id: //poco/1.2/Foundation/include/Poco/BufferedStreamBuf.h#1 $
//
// 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
#include "Poco/Foundation.h"
#include "Poco/BufferAllocator.h"
#include "Poco/StreamUtil.h"
#include <streambuf>
#include <iosfwd>
#include <ios>
namespace Poco {
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;
} // namespace Poco
#endif // Foundation_BufferedStreamBuf_INCLUDED

View File

@@ -0,0 +1,126 @@
//
// Bugcheck.h
//
// $Id: //poco/1.2/Foundation/include/Poco/Bugcheck.h#1 $
//
// 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
#include "Poco/Foundation.h"
#include <string>
namespace Poco {
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)) Poco::Bugcheck::assertion(#cond, __FILE__, __LINE__); else (void) 0
#else
#define poco_assert_dbg(cond)
#endif
#define poco_assert(cond) \
if (!(cond)) Poco::Bugcheck::assertion(#cond, __FILE__, __LINE__); else (void) 0
#define poco_check_ptr(ptr) \
if (!(ptr)) Poco::Bugcheck::nullPointer(#ptr, __FILE__, __LINE__); else (void) 0
#define poco_bugcheck() \
Poco::Bugcheck::bugcheck(__FILE__, __LINE__)
#define poco_bugcheck_msg(msg) \
Poco::Bugcheck::bugcheck(msg, __FILE__, __LINE__)
#define poco_debugger() \
Poco::Bugcheck::debugger(__FILE__, __LINE__)
#define poco_debugger_msg(msg) \
Poco::Bugcheck::debugger(msg, __FILE__, __LINE__)
} // namespace Poco
#endif // Foundation_Bugcheck_INCLUDED

View File

@@ -0,0 +1,227 @@
//
// ByteOrder.h
//
// $Id: //poco/1.2/Foundation/include/Poco/ByteOrder.h#1 $
//
// 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
#include "Poco/Foundation.h"
#include "Poco/Types.h"
namespace Poco {
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)
} // namespace Poco
#endif // Foundation_ByteOrder_INCLUDED

View File

@@ -0,0 +1,96 @@
//
// Channel.h
//
// $Id: //poco/1.2/Foundation/include/Poco/Channel.h#1 $
//
// 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
#include "Poco/Foundation.h"
#include "Poco/Configurable.h"
#include "Poco/Mutex.h"
#include "Poco/RefCountedObject.h"
namespace Poco {
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();
};
} // namespace Poco
#endif // Foundation_Channel_INCLUDED

View File

@@ -0,0 +1,104 @@
//
// ClassLibrary.h
//
// $Id: //poco/1.2/Foundation/include/Poco/ClassLibrary.h#1 $
//
// 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
#include "Poco/Foundation.h"
#include "Poco/Manifest.h"
#include <typeinfo>
#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(Poco::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(Poco::ManifestBase* pManifest_) \
{ \
typedef base _Base; \
typedef Poco::Manifest<_Base> _Manifest; \
std::string requiredType(typeid(_Manifest).name()); \
std::string actualType(pManifest_->className()); \
if (requiredType == actualType) \
{ \
Poco::Manifest<_Base>* pManifest = static_cast<_Manifest*>(pManifest_);
#define POCO_END_MANIFEST \
return true; \
} \
else return false; \
}
#define POCO_EXPORT_CLASS(cls) \
pManifest->insert(new Poco::MetaObject<cls, _Base>(#cls));
#define POCO_EXPORT_SINGLETON(cls) \
pManifest->insert(new Poco::MetaSingleton<cls, _Base>(#cls));
#endif // Foundation_ClassLibrary_INCLUDED

View File

@@ -0,0 +1,358 @@
//
// ClassLoader.h
//
// $Id: //poco/1.2/Foundation/include/Poco/ClassLoader.h#1 $
//
// 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
#include "Poco/Foundation.h"
#include "Poco/MetaObject.h"
#include "Poco/Manifest.h"
#include "Poco/SharedLibrary.h"
#include "Poco/Mutex.h"
#include "Poco/Exception.h"
#include <map>
namespace Poco {
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;
};
} // namespace Poco
#endif // Foundation_ClassLoader_INCLUDED

View File

@@ -0,0 +1,63 @@
//
// CompareFunctions.h
//
// $Id: //poco/1.2/Foundation/include/Poco/CompareFunctions.h#1 $
//
// 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 "Poco/Foundation.h"
#include <functional>
namespace Poco {
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;
}
};
} // namespace Poco
#endif

View File

@@ -0,0 +1,55 @@
//
// Config.h
//
// $Id: //poco/1.2/Foundation/include/Poco/Config.h#1 $
//
// Library: Foundation
// Package: Core
// Module: Foundation
//
// Feature configuration for the POCO libraries.
//
// 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_Config_INCLUDED
#define Foundation_Config_INCLUDED
// Define to enable Windows Unicode (UTF-8) support.
#undef POCO_WIN32_UTF8
// Define to disable FPEnvironment support
#undef POCO_NO_FPENVIRONMENT
// Define if std::wstring is not available
#undef POCO_NO_WSTRING
#endif // Foundation_Config_INCLUDED

View File

@@ -0,0 +1,85 @@
//
// Configurable.h
//
// $Id: //poco/1.2/Foundation/include/Poco/Configurable.h#1 $
//
// 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
#include "Poco/Foundation.h"
namespace Poco {
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.
};
} // namespace Poco
#endif // Foundation_Configurable_INCLUDED

View File

@@ -0,0 +1,89 @@
//
// ConsoleChannel.h
//
// $Id: //poco/1.2/Foundation/include/Poco/ConsoleChannel.h#1 $
//
// 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
#include "Poco/Foundation.h"
#include "Poco/Channel.h"
#include "Poco/Mutex.h"
#include <ostream>
namespace Poco {
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;
};
} // namespace Poco
#endif // Foundation_ConsoleChannel_INCLUDED

View File

@@ -0,0 +1,241 @@
//
// CountingStream.h
//
// $Id: //poco/1.2/Foundation/include/Poco/CountingStream.h#1 $
//
// 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
#include "Poco/Foundation.h"
#include "Poco/UnbufferedStreamBuf.h"
#include <istream>
#include <ostream>
namespace Poco {
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();
}
} // namespace Poco
#endif // Foundation_CountingStream_INCLUDED

View File

@@ -0,0 +1,427 @@
//
// DateTime.h
//
// $Id: //poco/1.2/Foundation/include/Poco/DateTime.h#1 $
//
// 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
#include "Poco/Foundation.h"
#include "Poco/Timestamp.h"
#include "Poco/Timespan.h"
namespace Poco {
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 two
/// forms (UTC and broken down) for performance reasons. Only use
/// this class for conversions between date/time representations.
/// Use the Timestamp class for everything else.
///
/// Notes:
/// * Zero is a valid year (in accordance with ISO 8601 and astronomical year numbering)
/// * Year zero (0) is a leap year
/// * Negative years (years preceding 1 BC) are not supported
///
/// For more information, please see:
/// * http://en.wikipedia.org/wiki/Gregorian_Calendar
/// * http://en.wikipedia.org/wiki/Julian_day
/// * http://en.wikipedia.org/wiki/UTC
/// * http://en.wikipedia.org/wiki/ISO_8601
{
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 and time.
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.
static bool isValid(int year, int month, int day, int hour = 0, int minute = 0, int second = 0, int millisecond = 0, int microsecond = 0);
/// Checks if the given date and time is valid
/// (all arguments are within a proper range).
///
/// Returns true if all arguments are valid, false otherwise.
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 = 0, int minute = 0, int second = 0, int millisecond = 0, int microsecond = 0);
/// 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(double julianDay);
/// Computes the Gregorian date for the given Julian day.
/// See <http://vsg.cape.com/~pbaum/date/injdimp.htm>, section 3.3.1 for the algorithm.
void computeDaytime();
/// Extracts the daytime (hours, minutes, seconds, etc.) from the stored utcTime.
private:
void checkLimit(short& lower, short& higher, short limit);
void normalize();
///utility functions used to correct the overflow in computeGregorian
Timestamp::UtcTimeVal _utcTime;
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 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);
}
} // namespace Poco
#endif // Foundation_DateTime_INCLUDED

View File

@@ -0,0 +1,123 @@
//
// DateTimeFormat.h
//
// $Id: //poco/1.2/Foundation/include/Poco/DateTimeFormat.h#1 $
//
// 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
#include "Poco/Foundation.h"
namespace Poco {
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, ...).
};
} // namespace Poco
#endif // Foundation_DateTimeFormat_INCLUDED

View File

@@ -0,0 +1,137 @@
//
// DateTimeFormatter.h
//
// $Id: //poco/1.2/Foundation/include/Poco/DateTimeFormatter.h#1 $
//
// 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
#include "Poco/Foundation.h"
namespace Poco {
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.
};
} // namespace Poco
#endif // Foundation_DateTimeFormatter_INCLUDED

View File

@@ -0,0 +1,119 @@
//
// DateTimeParser.h
//
// $Id: //poco/1.2/Foundation/include/Poco/DateTimeParser.h#1 $
//
// 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
#include "Poco/Foundation.h"
#include "Poco/DateTime.h"
namespace Poco {
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);
};
} // namespace Poco
#endif // Foundation_DateTimeParser_INCLUDED

View File

@@ -0,0 +1,95 @@
//
// Debugger.h
//
// $Id: //poco/1.2/Foundation/include/Poco/Debugger.h#1 $
//
// 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
#include "Poco/Foundation.h"
namespace Poco {
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.
};
} // namespace Poco
#endif // Foundation_Debugger_INCLUDED

View File

@@ -0,0 +1,154 @@
//
// DefaultStrategy.h
//
// $Id: //poco/1.2/Foundation/include/Poco/DefaultStrategy.h#1 $
//
// 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 "Poco/NotificationStrategy.h"
#include <memory>
#include <set>
#include <vector>
namespace Poco {
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;
};
} // namespace Poco
#endif

View File

@@ -0,0 +1,141 @@
//
// DeflatingStream.h
//
// $Id: //poco/1.2/Foundation/include/Poco/DeflatingStream.h#1 $
//
// 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
#include "Poco/Foundation.h"
#include "Poco/BufferedStreamBuf.h"
#include <istream>
#include <ostream>
#include "Poco/zlib.h"
namespace Poco {
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();
};
} // namespace Poco
#endif // Foundation_DeflatingStream_INCLUDED

View File

@@ -0,0 +1,120 @@
//
// Delegate.h
//
// $Id: //poco/1.2/Foundation/include/Poco/Delegate.h#1 $
//
// 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 "Poco/Foundation.h"
#include "Poco/AbstractDelegate.h"
#include "Poco/Expire.h"
namespace Poco {
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();
};
} // namespace Poco
#endif

View File

@@ -0,0 +1,125 @@
//
// DigestEngine.h
//
// $Id: //poco/1.2/Foundation/include/Poco/DigestEngine.h#1 $
//
// 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
#include "Poco/Foundation.h"
#include <vector>
namespace Poco {
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());
}
} // namespace Poco
#endif // Foundation_DigestEngine_INCLUDED

View File

@@ -0,0 +1,122 @@
//
// DigestStream.h
//
// $Id: //poco/1.2/Foundation/include/Poco/DigestStream.h#1 $
//
// 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
#include "Poco/Foundation.h"
#include "Poco/BufferedStreamBuf.h"
#include "Poco/DigestEngine.h"
#include <istream>
#include <ostream>
namespace Poco {
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();
};
} // namespace Poco
#endif // Foundation_DigestStream_INCLUDED

View File

@@ -0,0 +1,158 @@
//
// DirectoryIterator.h
//
// $Id: //poco/1.2/Foundation/include/Poco/DirectoryIterator.h#1 $
//
// Library: Foundation
// Package: Filesystem
// Module: DirectoryIterator
//
// Definition of the DirectoryIterator 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_DirectoryIterator_INCLUDED
#define Foundation_DirectoryIterator_INCLUDED
#include "Poco/Foundation.h"
#include "Poco/File.h"
#include "Poco/Path.h"
namespace Poco {
class DirectoryIteratorImpl;
class Foundation_API DirectoryIterator
/// The DirectoryIterator class is used to enumerate
/// all files in a directory.
{
public:
DirectoryIterator();
/// Creates the end iterator.
DirectoryIterator(const std::string& path);
/// Creates a directory iterator for the given path.
DirectoryIterator(const DirectoryIterator& iterator);
/// Creates a directory iterator for the given path.
DirectoryIterator(const File& file);
/// Creates a directory iterator for the given file.
DirectoryIterator(const Path& path);
/// Creates a directory iterator for the given path.
~DirectoryIterator();
/// Destroys the DirectoryIterator.
const std::string& name() const;
/// Returns the current filename.
const Path& path() const;
/// Returns the current path.
DirectoryIterator& operator = (const DirectoryIterator& it);
DirectoryIterator& operator = (const File& file);
DirectoryIterator& operator = (const Path& path);
DirectoryIterator& operator = (const std::string& path);
DirectoryIterator& operator ++ (); // prefix
DirectoryIterator operator ++ (int); // postfix
const File& operator * () const;
File& operator * ();
const File* operator -> () const;
File* operator -> ();
bool operator == (const DirectoryIterator& iterator) const;
bool operator != (const DirectoryIterator& iterator) const;
private:
Path _path;
File _file;
DirectoryIteratorImpl* _pImpl;
};
//
// inlines
//
inline const std::string& DirectoryIterator::name() const
{
return _path.getFileName();
}
inline const Path& DirectoryIterator::path() const
{
return _path;
}
inline const File& DirectoryIterator::operator * () const
{
return _file;
}
inline File& DirectoryIterator::operator * ()
{
return _file;
}
inline const File* DirectoryIterator::operator -> () const
{
return &_file;
}
inline File* DirectoryIterator::operator -> ()
{
return &_file;
}
inline bool DirectoryIterator::operator == (const DirectoryIterator& iterator) const
{
return name() == iterator.name();
}
inline bool DirectoryIterator::operator != (const DirectoryIterator& iterator) const
{
return name() != iterator.name();
}
} // namespace Poco
#endif // Foundation_DirectoryIterator_INCLUDED

View File

@@ -0,0 +1,94 @@
//
// DirectoryIterator_UNIX.h
//
// $Id: //poco/1.2/Foundation/include/Poco/DirectoryIterator_UNIX.h#1 $
//
// Library: Foundation
// Package: Filesystem
// Module: DirectoryIterator
//
// Definition of the DirectoryIteratorImpl class for UNIX.
//
// 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_DirectoryIterator_UNIX_INCLUDED
#define Foundation_DirectoryIterator_UNIX_INCLUDED
#include "Poco/Foundation.h"
#include <dirent.h>
namespace Poco {
class Foundation_API DirectoryIteratorImpl
{
public:
DirectoryIteratorImpl(const std::string& path);
~DirectoryIteratorImpl();
void duplicate();
void release();
const std::string& get() const;
const std::string& next();
private:
DIR* _pDir;
std::string _current;
int _rc;
};
//
// inlines
//
const std::string& DirectoryIteratorImpl::get() const
{
return _current;
}
inline void DirectoryIteratorImpl::duplicate()
{
++_rc;
}
inline void DirectoryIteratorImpl::release()
{
if (--_rc == 0)
delete this;
}
} // namespace Poco
#endif // Foundation_DirectoryIterator_UNIX_INCLUDED

View File

@@ -0,0 +1,97 @@
//
// DirectoryIterator_VMS.h
//
// $Id: //poco/1.2/Foundation/include/Poco/DirectoryIterator_VMS.h#1 $
//
// Library: Foundation
// Package: Filesystem
// Module: DirectoryIterator
//
// Definition of the DirectoryIteratorImpl class for OpenVMS.
//
// 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_DirectoryIterator_VMS_INCLUDED
#define Foundation_DirectoryIterator_VMS_INCLUDED
#include "Poco/Foundation.h"
#include <rms.h>
namespace Poco {
class Foundation_API DirectoryIteratorImpl
{
public:
DirectoryIteratorImpl(const std::string& path);
~DirectoryIteratorImpl();
void duplicate();
void release();
const std::string& get() const;
const std::string& next();
private:
struct FAB _fab;
struct NAM _nam;
std::string _search;
char _spec[255];
std::string _current;
int _rc;
};
//
// inlines
//
const std::string& DirectoryIteratorImpl::get() const
{
return _current;
}
inline void DirectoryIteratorImpl::duplicate()
{
++_rc;
}
inline void DirectoryIteratorImpl::release()
{
if (--_rc == 0)
delete this;
}
} // namespace Poco
#endif // Foundation_DirectoryIterator_VMS_INCLUDED

View File

@@ -0,0 +1,95 @@
//
// DirectoryIterator_WIN32.h
//
// $Id: //poco/1.2/Foundation/include/Poco/DirectoryIterator_WIN32.h#1 $
//
// Library: Foundation
// Package: Filesystem
// Module: DirectoryIterator
//
// Definition of the DirectoryIteratorImpl class for WIN32.
//
// 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_DirectoryIterator_WIN32_INCLUDED
#define Foundation_DirectoryIterator_WIN32_INCLUDED
#include "Poco/Foundation.h"
#include <windows.h>
namespace Poco {
class Foundation_API DirectoryIteratorImpl
{
public:
DirectoryIteratorImpl(const std::string& path);
~DirectoryIteratorImpl();
void duplicate();
void release();
const std::string& get() const;
const std::string& next();
private:
HANDLE _fh;
WIN32_FIND_DATA _fd;
std::string _current;
int _rc;
};
//
// inlines
//
const std::string& DirectoryIteratorImpl::get() const
{
return _current;
}
inline void DirectoryIteratorImpl::duplicate()
{
++_rc;
}
inline void DirectoryIteratorImpl::release()
{
if (--_rc == 0)
delete this;
}
} // namespace Poco
#endif // Foundation_DirectoryIterator_WIN32_INCLUDED

View File

@@ -0,0 +1,95 @@
//
// DirectoryIterator_WIN32U.h
//
// $Id: //poco/1.2/Foundation/include/Poco/DirectoryIterator_WIN32U.h#1 $
//
// Library: Foundation
// Package: Filesystem
// Module: DirectoryIterator
//
// Definition of the DirectoryIteratorImpl class for WIN32.
//
// 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_DirectoryIterator_WIN32U_INCLUDED
#define Foundation_DirectoryIterator_WIN32U_INCLUDED
#include "Poco/Foundation.h"
#include <windows.h>
namespace Poco {
class Foundation_API DirectoryIteratorImpl
{
public:
DirectoryIteratorImpl(const std::string& path);
~DirectoryIteratorImpl();
void duplicate();
void release();
const std::string& get() const;
const std::string& next();
private:
HANDLE _fh;
WIN32_FIND_DATAW _fd;
std::string _current;
int _rc;
};
//
// inlines
//
const std::string& DirectoryIteratorImpl::get() const
{
return _current;
}
inline void DirectoryIteratorImpl::duplicate()
{
++_rc;
}
inline void DirectoryIteratorImpl::release()
{
if (--_rc == 0)
delete this;
}
} // namespace Poco
#endif // Foundation_DirectoryIterator_WIN32U_INCLUDED

View File

@@ -0,0 +1,158 @@
//
// DynamicFactory.h
//
// $Id: //poco/1.2/Foundation/include/Poco/DynamicFactory.h#1 $
//
// Library: Foundation
// Package: Core
// Module: DynamicFactory
//
// Definition of the DynamicFactory 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_DynamicFactory_INCLUDED
#define Foundation_DynamicFactory_INCLUDED
#include "Poco/Foundation.h"
#include "Poco/Instantiator.h"
#include "Poco/Exception.h"
#include "Poco/Mutex.h"
#include <map>
#include <memory>
namespace Poco {
template <class Base>
class DynamicFactory
/// A factory that creates objects by class name.
{
public:
typedef AbstractInstantiator<Base> AbstractFactory;
DynamicFactory()
/// Creates the DynamicFactory.
{
}
~DynamicFactory()
/// Destroys the DynamicFactory and deletes the instantiators for
/// all registered classes.
{
for (typename FactoryMap::iterator it = _map.begin(); it != _map.end(); ++it)
{
delete it->second;
}
}
Base* createInstance(const std::string& className) const
/// Creates a new instance of the class with the given name.
/// The class must have been registered with registerClass.
/// If the class name is unknown, a NotFoundException is thrown.
{
FastMutex::ScopedLock lock(_mutex);
typename FactoryMap::const_iterator it = _map.find(className);
if (it != _map.end())
return it->second->createInstance();
else
throw NotFoundException(className);
}
template <class C>
void registerClass(const std::string& className)
/// Registers the instantiator for the given class with the DynamicFactory.
/// The DynamicFactory takes ownership of the instantiator and deletes
/// it when it's no longer used.
/// If the class has already been registered, an ExistsException is thrown
/// and the instantiator is deleted.
{
registerClass(className, new Instantiator<C, Base>);
}
void registerClass(const std::string& className, AbstractFactory* pAbstractFactory)
/// Registers the instantiator for the given class with the DynamicFactory.
/// The DynamicFactory takes ownership of the instantiator and deletes
/// it when it's no longer used.
/// If the class has already been registered, an ExistsException is thrown
/// and the instantiator is deleted.
{
poco_check_ptr (pAbstractFactory);
FastMutex::ScopedLock lock(_mutex);
std::auto_ptr<AbstractFactory> ptr(pAbstractFactory);
typename FactoryMap::iterator it = _map.find(className);
if (it == _map.end())
_map[className] = ptr.release();
else
throw ExistsException(className);
}
void unregisterClass(const std::string& className)
/// Unregisters the given class and deletes the instantiator
/// for the class.
/// Throws a NotFoundException if the class has not been registered.
{
FastMutex::ScopedLock lock(_mutex);
typename FactoryMap::iterator it = _map.find(className);
if (it != _map.end())
{
delete it->second;
_map.erase(it);
}
else throw NotFoundException(className);
}
bool isClass(const std::string& className) const
/// Returns true iff the given class has been registered.
{
FastMutex::ScopedLock lock(_mutex);
return _map.find(className) != _map.end();
}
private:
DynamicFactory(const DynamicFactory&);
DynamicFactory& operator = (const DynamicFactory&);
typedef std::map<std::string, AbstractFactory*> FactoryMap;
FactoryMap _map;
mutable FastMutex _mutex;
};
} // namespace Poco
#endif // Foundation_DynamicFactory_INCLUDED

View File

@@ -0,0 +1,84 @@
//
// Environment.h
//
// $Id: //poco/1.2/Foundation/include/Poco/Environment.h#1 $
//
// Library: Foundation
// Package: Core
// Module: Environment
//
// Definition of the Environment 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_Environment_INCLUDED
#define Foundation_Environment_INCLUDED
#include "Poco/Foundation.h"
namespace Poco {
class Foundation_API Environment
/// This class provides access to environment variables
/// and some general system information.
{
public:
static std::string get(const std::string& name);
/// Returns the value of the environment variable
/// with the given name. Throws a NotFoundException
/// if the variable does not exist.
static bool has(const std::string& name);
/// Returns true iff an environment variable
/// with the given name is defined.
static void set(const std::string& name, const std::string& value);
/// Sets the environment variable with the given name
/// to the given value.
static std::string osName();
/// Returns the operating system name.
static std::string osVersion();
/// Returns the operating system version.
static std::string osArchitecture();
/// Returns the operating system architecture.
static std::string nodeName();
/// Returns the node (or host) name.
};
} // namespace Poco
#endif // Foundation_Environment_INCLUDED

View File

@@ -0,0 +1,73 @@
//
// Environment_UNIX.h
//
// $Id: //poco/1.2/Foundation/include/Poco/Environment_UNIX.h#1 $
//
// Library: Foundation
// Package: Core
// Module: Environment
//
// Definition of the EnvironmentImpl class for Unix.
//
// 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_Environment_UNIX_INCLUDED
#define Foundation_Environment_UNIX_INCLUDED
#include "Poco/Foundation.h"
#include "Poco/Mutex.h"
#include <map>
namespace Poco {
class Foundation_API EnvironmentImpl
{
public:
static std::string getImpl(const std::string& name);
static bool hasImpl(const std::string& name);
static void setImpl(const std::string& name, const std::string& value);
static std::string osNameImpl();
static std::string osVersionImpl();
static std::string osArchitectureImpl();
static std::string nodeNameImpl();
private:
typedef std::map<std::string, std::string> StringMap;
static StringMap _map;
static FastMutex _mutex;
};
} // namespace Poco
#endif // Foundation_Environment_UNIX_INCLUDED

View File

@@ -0,0 +1,74 @@
//
// Environment_VMS.h
//
// $Id: //poco/1.2/Foundation/include/Poco/Environment_VMS.h#1 $
//
// Library: Foundation
// Package: Core
// Module: Environment
//
// Definition of the EnvironmentImpl class for OpenVMS.
//
// 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_Environment_VMS_INCLUDED
#define Foundation_Environment_VMS_INCLUDED
#include "Poco/Foundation.h"
#include "Poco/Mutex.h"
namespace Poco {
class Foundation_API EnvironmentImpl
{
public:
static std::string getImpl(const std::string& name);
static bool hasImpl(const std::string& name);
static void setImpl(const std::string& name, const std::string& value);
static std::string osNameImpl();
static std::string osVersionImpl();
static std::string osArchitectureImpl();
static std::string nodeNameImpl();
static std::string getsyi(unsigned short code);
/// a wrapper for $GETSYIW
static std::string trnlnm(const std::string& name);
private:
static FastMutex _mutex;
};
} // namespace Poco
#endif // Foundation_Environment_VMS_INCLUDED

View File

@@ -0,0 +1,65 @@
//
// Environment_WIN32.h
//
// $Id: //poco/1.2/Foundation/include/Poco/Environment_WIN32.h#1 $
//
// Library: Foundation
// Package: Core
// Module: Environment
//
// Definition of the EnvironmentImpl class for WIN32.
//
// 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_Environment_WIN32_INCLUDED
#define Foundation_Environment_WIN32_INCLUDED
#include "Poco/Foundation.h"
namespace Poco {
class Foundation_API EnvironmentImpl
{
public:
static std::string getImpl(const std::string& name);
static bool hasImpl(const std::string& name);
static void setImpl(const std::string& name, const std::string& value);
static std::string osNameImpl();
static std::string osVersionImpl();
static std::string osArchitectureImpl();
static std::string nodeNameImpl();
};
} // namespace Poco
#endif // Foundation_Environment_WIN32_INCLUDED

View File

@@ -0,0 +1,65 @@
//
// Environment_WIN32U.h
//
// $Id: //poco/1.2/Foundation/include/Poco/Environment_WIN32U.h#1 $
//
// Library: Foundation
// Package: Core
// Module: Environment
//
// Definition of the EnvironmentImpl class for WIN32.
//
// 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_Environment_WIN32U_INCLUDED
#define Foundation_Environment_WIN32U_INCLUDED
#include "Poco/Foundation.h"
namespace Poco {
class Foundation_API EnvironmentImpl
{
public:
static std::string getImpl(const std::string& name);
static bool hasImpl(const std::string& name);
static void setImpl(const std::string& name, const std::string& value);
static std::string osNameImpl();
static std::string osVersionImpl();
static std::string osArchitectureImpl();
static std::string nodeNameImpl();
};
} // namespace Poco
#endif // Foundation_Environment_WIN32U_INCLUDED

View File

@@ -0,0 +1,142 @@
//
// ErrorHandler.h
//
// $Id: //poco/1.2/Foundation/include/Poco/ErrorHandler.h#1 $
//
// Library: Foundation
// Package: Threading
// Module: ErrorHandler
//
// Definition of the ErrorHandler 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_ErrorHandler_INCLUDED
#define Foundation_ErrorHandler_INCLUDED
#include "Poco/Foundation.h"
#include "Poco/Exception.h"
#include "Poco/Mutex.h"
namespace Poco {
class Foundation_API ErrorHandler
/// This is the base class for thread error handlers.
///
/// An unhandled exception that causes a thread to terminate is usually
/// silently ignored, since the class library cannot do anything meaningful
/// about it.
///
/// The Thread class provides the possibility to register a
/// global ErrorHandler that is invoked whenever a thread has
/// been terminated by an unhandled exception.
/// The ErrorHandler must be derived from this class and can
/// provide implementations of all three handleException() overloads.
///
/// The ErrorHandler is always invoked within the context of
/// the offending thread.
{
public:
ErrorHandler();
/// Creates the ErrorHandler.
virtual ~ErrorHandler();
/// Destroys the ErrorHandler.
virtual void exception(const Exception& exc);
/// Called when a Poco::Exception (or a subclass)
/// caused the thread to terminate.
///
/// This method should not throw any exception - it would
/// be silently ignored.
///
/// The default implementation just breaks into the debugger.
virtual void exception(const std::exception& exc);
/// Called when a std::exception (or a subclass)
/// caused the thread to terminate.
///
/// This method should not throw any exception - it would
/// be silently ignored.
///
/// The default implementation just breaks into the debugger.
virtual void exception();
/// Called when an exception that is neither a
/// Poco::Exception nor a std::exception caused
/// the thread to terminate.
///
/// This method should not throw any exception - it would
/// be silently ignored.
///
/// The default implementation just breaks into the debugger.
static void handle(const Exception& exc);
/// Invokes the currently registered ErrorHandler.
static void handle(const std::exception& exc);
/// Invokes the currently registered ErrorHandler.
static void handle();
/// Invokes the currently registered ErrorHandler.
static ErrorHandler* set(ErrorHandler* pHandler);
/// Registers the given handler as the current error handler.
///
/// Returns the previously registered handler.
static ErrorHandler* get();
/// Returns a pointer to the currently registered
/// ErrorHandler.
protected:
static ErrorHandler* defaultHandler();
/// Returns the default ErrorHandler.
private:
static ErrorHandler* _pHandler;
static FastMutex _mutex;
};
//
// inlines
//
inline ErrorHandler* ErrorHandler::get()
{
return _pHandler;
}
} // namespace Poco
#endif // Foundation_ErrorHandler_INCLUDED

View File

@@ -0,0 +1,143 @@
//
// Event.h
//
// $Id: //poco/1.2/Foundation/include/Poco/Event.h#1 $
//
// Library: Foundation
// Package: Threading
// Module: Event
//
// Definition of the Event 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_Event_INCLUDED
#define Foundation_Event_INCLUDED
#include "Poco/Foundation.h"
#include "Poco/Exception.h"
#if defined(POCO_OS_FAMILY_WINDOWS)
#include "Poco/Event_WIN32.h"
#else
#include "Poco/Event_POSIX.h"
#endif
namespace Poco {
class Foundation_API Event: private EventImpl
/// An Event is a synchronization object that
/// allows one thread to signal one or more
/// other threads that a certain event
/// has happened.
/// Usually, one thread signals an event,
/// while one or more other threads wait
/// for an event to become signalled.
{
public:
Event(bool autoReset = true);
/// Creates the event. If autoReset is true,
/// the event is automatically reset after
/// a wait() successfully returns.
~Event();
/// Destroys the event.
void set();
/// Signals the event. If autoReset is true,
/// only one thread waiting for the event
/// can resume execution.
/// If autoReset is false, all waiting threads
/// can resume execution.
void wait();
/// Waits for the event to become signalled.
void wait(long milliseconds);
/// Waits for the event to become signalled.
/// Throws a TimeOutException if the event
/// does not become signalled within the specified
/// time interval.
bool tryWait(long milliseconds);
/// Waits for the event to become signalled.
/// Returns true if the event
/// became signalled within the specified
/// time interval, false otherwise.
void reset();
/// Resets the event to unsignalled state.
private:
Event(const Event&);
Event& operator = (const Event&);
};
//
// inlines
//
inline void Event::set()
{
setImpl();
}
inline void Event::wait()
{
waitImpl();
}
inline void Event::wait(long milliseconds)
{
if (!waitImpl(milliseconds))
throw TimeoutException();
}
inline bool Event::tryWait(long milliseconds)
{
return waitImpl(milliseconds);
}
inline void Event::reset()
{
resetImpl();
}
} // namespace Poco
#endif // Foundation_Event_INCLUDED

View File

@@ -0,0 +1,66 @@
//
// EventArgs.h
//
// $Id: //poco/1.2/Foundation/include/Poco/EventArgs.h#1 $
//
// Library: Foundation
// Package: Events
// Module: EventArgs
//
// Definition of EventArgs.
//
// 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_EventArgs_INCLUDED
#define Foundation_EventArgs_INCLUDED
#include "Poco/Foundation.h"
namespace Poco {
class Foundation_API EventArgs
/// The purpose of the EventArgs class is to be used as parameter
/// when one doesn't want to send any data.
/// One can use EventArgs as a super-class for one's own event arguments
/// but with the arguments being a template parameter this is not
/// necessary.
{
public:
EventArgs();
virtual ~EventArgs();
};
} // namespace Poco
#endif

View File

@@ -0,0 +1,125 @@
//
// EventLogChannel.h
//
// $Id: //poco/1.2/Foundation/include/Poco/EventLogChannel.h#1 $
//
// Library: Foundation
// Package: Logging
// Module: EventLogChannel
//
// Definition of the EventLogChannel class specific to WIN32.
//
// 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_EventLogChannel_INCLUDED
#define Foundation_EventLogChannel_INCLUDED
#include "Poco/Foundation.h"
#include "Poco/Channel.h"
#include <windows.h>
namespace Poco {
class Foundation_API EventLogChannel: public Channel
/// This Windows-only channel works with the Windows NT Event Log
/// service.
///
/// To work properly, the EventLogChannel class requires that either
/// the PocoFoundation.dll or the PocoMsg.dll Dynamic Link Library
/// containing the message definition resources can be found in $PATH.
{
public:
EventLogChannel();
/// Creates the EventLogChannel.
/// The name of the current application (or more correctly,
/// the name of its executable) is taken as event source name.
EventLogChannel(const std::string& name);
/// Creates the EventLogChannel with the given event source name.
EventLogChannel(const std::string& name, const std::string& host);
/// Creates an EventLogChannel with the given event source
/// name that routes messages to the given host.
void open();
/// Opens the EventLogChannel. If necessary, the
/// required registry entries to register a
/// message resource DLL are made.
void close();
/// Closes the EventLogChannel.
void log(const Message& msg);
/// Logs the given message to the Windows Event Log.
///
/// The message type and priority are mapped to
/// appropriate values for Event Log type and category.
void setProperty(const std::string& name, const std::string& value);
/// Sets or changes a configuration property.
///
/// The following properties are supported:
///
/// * name: The name of the event source.
/// * host: The name of the host where the Event Log service is running.
/// The default is "localhost".
/// * logFile: The name of the log file. The default is "Application".
std::string getProperty(const std::string& name) const;
/// Returns the value of the given property.
static const std::string PROP_NAME;
static const std::string PROP_HOST;
static const std::string PROP_LOGFILE;
protected:
~EventLogChannel();
static int getType(const Message& msg);
static int getCategory(const Message& msg);
void setUpRegistry() const;
#if defined(POCO_WIN32_UTF8)
static std::wstring findLibrary(const wchar_t* name);
#else
static std::string findLibrary(const char* name);
#endif
private:
std::string _name;
std::string _host;
std::string _logFile;
HANDLE _h;
};
} // namespace Poco
#endif // Foundation_EventLogChannel_INCLUDED

View File

@@ -0,0 +1,99 @@
//
// Event_POSIX.h
//
// $Id: //poco/1.2/Foundation/include/Poco/Event_POSIX.h#1 $
//
// Library: Foundation
// Package: Threading
// Module: Event
//
// Definition of the EventImpl class for POSIX Threads.
//
// 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_Event_POSIX_INCLUDED
#define Foundation_Event_POSIX_INCLUDED
#include "Poco/Foundation.h"
#include "Poco/Exception.h"
#include <pthread.h>
#include <errno.h>
namespace Poco {
class Foundation_API EventImpl
{
protected:
EventImpl(bool autoReset);
~EventImpl();
void setImpl();
void waitImpl();
bool waitImpl(long milliseconds);
void resetImpl();
private:
bool _auto;
volatile bool _state;
pthread_mutex_t _mutex;
pthread_cond_t _cond;
};
//
// inlines
//
inline void EventImpl::setImpl()
{
if (pthread_mutex_lock(&_mutex))
throw SystemException("cannot signal event (lock)");
_state = true;
if (pthread_cond_broadcast(&_cond))
{
pthread_mutex_unlock(&_mutex);
throw SystemException("cannot signal event");
}
pthread_mutex_unlock(&_mutex);
}
inline void EventImpl::resetImpl()
{
if (pthread_mutex_lock(&_mutex))
throw SystemException("cannot reset event");
_state = false;
pthread_mutex_unlock(&_mutex);
}
} // namespace Poco
#endif // Foundation_Event_POSIX_INCLUDED

View File

@@ -0,0 +1,90 @@
//
// Event_WIN32.h
//
// $Id: //poco/1.2/Foundation/include/Poco/Event_WIN32.h#1 $
//
// Library: Foundation
// Package: Threading
// Module: Event
//
// Definition of the EventImpl class for WIN32.
//
// 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_Event_WIN32_INCLUDED
#define Foundation_Event_WIN32_INCLUDED
#include "Poco/Foundation.h"
#include "Poco/Exception.h"
#include <windows.h>
namespace Poco {
class Foundation_API EventImpl
{
protected:
EventImpl(bool autoReset = false);
~EventImpl();
void setImpl();
void waitImpl();
bool waitImpl(long milliseconds);
void resetImpl();
private:
HANDLE _event;
};
//
// inlines
//
inline void EventImpl::setImpl()
{
if (!SetEvent(_event))
{
throw SystemException("cannot signal event");
}
}
inline void EventImpl::resetImpl()
{
if (!ResetEvent(_event))
{
throw SystemException("cannot reset event");
}
}
} // namespace Poco
#endif // Foundation_Event_WIN32_INCLUDED

View File

@@ -0,0 +1,252 @@
//
// Exception.h
//
// $Id: //poco/1.2/Foundation/include/Poco/Exception.h#1 $
//
// Library: Foundation
// Package: Core
// Module: Exception
//
// Definition of various Poco exception 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_Exception_INCLUDED
#define Foundation_Exception_INCLUDED
#include "Poco/Foundation.h"
#include <stdexcept>
namespace Poco {
class Foundation_API Exception: public std::exception
/// This is the base class for all exceptions defined
/// in the Poco class library.
{
public:
Exception(const std::string& msg);
/// Creates an exception.
Exception(const std::string& msg, const std::string& arg);
/// Creates an exception.
Exception(const std::string& msg, const Exception& nested);
/// Creates an exception and stores a clone
/// of the nested exception.
Exception(const Exception& exc);
/// Copy constructor.
~Exception() throw();
/// Destroys the exception and deletes the nested exception.
Exception& operator = (const Exception& exc);
/// Assignment operator.
virtual const char* name() const throw();
/// Returns a static string describing the exception.
virtual const char* className() const throw();
/// Returns the name of the exception class.
virtual const char* what() const throw();
/// Returns the message text as a C string.
const Exception* nested() const;
/// Returns a pointer to the nested exception, or
/// null if no nested exception exists.
const std::string& message() const;
/// Returns the message text.
std::string displayText() const;
/// Returns a string consisting of the
/// message name and the message text.
virtual Exception* clone() const;
/// Creates an exact copy of the exception.
///
/// The copy can later be thrown again by
/// invoking rethrow() on it.
virtual void rethrow() const;
/// (Re)Throws the exception.
///
/// This is useful for temporarily storing a
/// copy of an exception (see clone()), then
/// throwing it again.
protected:
Exception();
/// Standard constructor.
private:
std::string _msg;
Exception* _pNested;
};
//
// inlines
//
inline const Exception* Exception::nested() const
{
return _pNested;
}
inline const std::string& Exception::message() const
{
return _msg;
}
//
// Macros for quickly declaring and implementing exception classes.
// Unfortunately, we cannot use a template here because character
// pointers (which we need for specifying the exception name)
// are not allowed as template arguments.
//
#define POCO_DECLARE_EXCEPTION(API, CLS, BASE) \
class API CLS: public BASE \
{ \
public: \
CLS(); \
CLS(const std::string& msg); \
CLS(const std::string& msg, const std::string& arg); \
CLS(const std::string& msg, const Poco::Exception& exc); \
CLS(const CLS& exc); \
~CLS() throw(); \
CLS& operator = (const CLS& exc); \
const char* name() const throw(); \
const char* className() const throw(); \
Poco::Exception* clone() const; \
void rethrow() const; \
};
#define POCO_IMPLEMENT_EXCEPTION(CLS, BASE, NAME) \
CLS::CLS() \
{ \
} \
CLS::CLS(const std::string& msg): BASE(msg) \
{ \
} \
CLS::CLS(const std::string& msg, const std::string& arg): BASE(msg, arg) \
{ \
} \
CLS::CLS(const std::string& msg, const Poco::Exception& exc): BASE(msg, exc) \
{ \
} \
CLS::CLS(const CLS& exc): BASE(exc) \
{ \
} \
CLS::~CLS() throw() \
{ \
} \
CLS& CLS::operator = (const CLS& exc) \
{ \
BASE::operator = (exc); \
return *this; \
} \
const char* CLS::name() const throw() \
{ \
return NAME; \
} \
const char* CLS::className() const throw() \
{ \
return typeid(*this).name(); \
} \
Poco::Exception* CLS::clone() const \
{ \
return new CLS(*this); \
} \
void CLS::rethrow() const \
{ \
throw *this; \
}
//
// Standard exception classes
//
POCO_DECLARE_EXCEPTION(Foundation_API, LogicException, Exception)
POCO_DECLARE_EXCEPTION(Foundation_API, AssertionViolationException, LogicException)
POCO_DECLARE_EXCEPTION(Foundation_API, NullPointerException, LogicException)
POCO_DECLARE_EXCEPTION(Foundation_API, BugcheckException, LogicException)
POCO_DECLARE_EXCEPTION(Foundation_API, InvalidArgumentException, LogicException)
POCO_DECLARE_EXCEPTION(Foundation_API, NotImplementedException, LogicException)
POCO_DECLARE_EXCEPTION(Foundation_API, RangeException, LogicException)
POCO_DECLARE_EXCEPTION(Foundation_API, IllegalStateException, LogicException)
POCO_DECLARE_EXCEPTION(Foundation_API, InvalidAccessException, LogicException)
POCO_DECLARE_EXCEPTION(Foundation_API, SignalException, LogicException)
POCO_DECLARE_EXCEPTION(Foundation_API, UnhandledException, LogicException)
POCO_DECLARE_EXCEPTION(Foundation_API, RuntimeException, Exception)
POCO_DECLARE_EXCEPTION(Foundation_API, NotFoundException, RuntimeException)
POCO_DECLARE_EXCEPTION(Foundation_API, ExistsException, RuntimeException)
POCO_DECLARE_EXCEPTION(Foundation_API, TimeoutException, RuntimeException)
POCO_DECLARE_EXCEPTION(Foundation_API, SystemException, RuntimeException)
POCO_DECLARE_EXCEPTION(Foundation_API, RegularExpressionException, RuntimeException)
POCO_DECLARE_EXCEPTION(Foundation_API, LibraryLoadException, RuntimeException)
POCO_DECLARE_EXCEPTION(Foundation_API, LibraryAlreadyLoadedException, RuntimeException)
POCO_DECLARE_EXCEPTION(Foundation_API, NoThreadAvailableException, RuntimeException)
POCO_DECLARE_EXCEPTION(Foundation_API, PropertyNotSupportedException, RuntimeException)
POCO_DECLARE_EXCEPTION(Foundation_API, PoolOverflowException, RuntimeException)
POCO_DECLARE_EXCEPTION(Foundation_API, NoPermissionException, RuntimeException)
POCO_DECLARE_EXCEPTION(Foundation_API, OutOfMemoryException, RuntimeException)
POCO_DECLARE_EXCEPTION(Foundation_API, DataException, RuntimeException)
POCO_DECLARE_EXCEPTION(Foundation_API, DataFormatException, DataException)
POCO_DECLARE_EXCEPTION(Foundation_API, SyntaxException, DataException)
POCO_DECLARE_EXCEPTION(Foundation_API, CircularReferenceException, DataException)
POCO_DECLARE_EXCEPTION(Foundation_API, PathSyntaxException, SyntaxException)
POCO_DECLARE_EXCEPTION(Foundation_API, IOException, RuntimeException)
POCO_DECLARE_EXCEPTION(Foundation_API, FileException, IOException)
POCO_DECLARE_EXCEPTION(Foundation_API, FileExistsException, FileException)
POCO_DECLARE_EXCEPTION(Foundation_API, FileNotFoundException, FileException)
POCO_DECLARE_EXCEPTION(Foundation_API, PathNotFoundException, FileException)
POCO_DECLARE_EXCEPTION(Foundation_API, FileReadOnlyException, FileException)
POCO_DECLARE_EXCEPTION(Foundation_API, FileAccessDeniedException, FileException)
POCO_DECLARE_EXCEPTION(Foundation_API, CreateFileException, FileException)
POCO_DECLARE_EXCEPTION(Foundation_API, OpenFileException, FileException)
POCO_DECLARE_EXCEPTION(Foundation_API, WriteFileException, FileException)
POCO_DECLARE_EXCEPTION(Foundation_API, ReadFileException, FileException)
POCO_DECLARE_EXCEPTION(Foundation_API, UnknownURISchemeException, RuntimeException)
POCO_DECLARE_EXCEPTION(Foundation_API, ApplicationException, Exception)
POCO_DECLARE_EXCEPTION(Foundation_API, BadCastException, RuntimeException)
} // namespace Poco
#endif // Foundation_Exception_INCLUDED

View File

@@ -0,0 +1,145 @@
//
// Expire.h
//
// $Id: //poco/1.2/Foundation/include/Poco/Expire.h#1 $
//
// Library: Foundation
// Package: Events
// Module: Expire
//
// Implementation of the Expire 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_Expire_INCLUDED
#define Foundation_Expire_INCLUDED
#include "Poco/Foundation.h"
#include "Poco/AbstractDelegate.h"
#include "Poco/Timestamp.h"
namespace Poco {
template <class TArgs>
class Expire: public AbstractDelegate<TArgs>
/// Decorator for AbstractDelegate adding automatic
/// expiring of registrations to AbstractDelegates.
{
public:
Expire(const AbstractDelegate<TArgs>& p, Timestamp::TimeDiff expireMillisecs):
_pDelegate(p.clone()),
_expire(expireMillisecs*1000)
{
}
Expire(const Expire& expire):
_pDelegate(expire._pDelegate->clone()),
_expire(expire._expire),
_creationTime(expire._creationTime)
{
}
~Expire()
{
destroy();
}
Expire& operator = (const Expire& expire)
{
if (&expire != this)
{
delete _pDelegate;
_pDelegate = expire._pDelegate->clone();
_expire = expire._expire;
_creationTime = expire._creationTime;
}
return *this;
}
bool notify(const void* sender, TArgs& arguments)
{
if (!expired())
return _pDelegate->notify(sender, arguments);
else
return false;
}
AbstractDelegate<TArgs>* clone() const
{
return new Expire(*this);
}
bool operator < (const AbstractDelegate<TArgs>& other) const
{
const Expire* pOther = dynamic_cast<const Expire*>(&other);
if (pOther)
return _pDelegate->operator < (*pOther->_pDelegate);
else
return _pDelegate->operator < (other);
}
void destroy()
{
delete _pDelegate;
_pDelegate = 0;
}
const AbstractDelegate<TArgs>& getDelegate() const
{
return *_pDelegate;
}
protected:
Expire(AbstractDelegate<TArgs>* p, Timestamp::TimeDiff expireMillisecs):
_pDelegate(p),
_expire(expireMillisecs*1000)
{
}
bool expired() const
{
return _creationTime.isElapsed(_expire);
}
AbstractDelegate<TArgs>* _pDelegate;
Timestamp::TimeDiff _expire;
Timestamp _creationTime;
private:
Expire();
};
} // namespace Poco
#endif

View File

@@ -0,0 +1,78 @@
//
// ExpireCache.h
//
// $Id: //poco/1.2/Foundation/include/Poco/ExpireCache.h#1 $
//
// Library: Foundation
// Package: Cache
// Module: ExpireCache
//
// Definition of the ExpireCache 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_ExpireCache_INCLUDED
#define Foundation_ExpireCache_INCLUDED
#include "Poco/AbstractCache.h"
#include "Poco/ExpireStrategy.h"
namespace Poco {
template <class TKey, class TValue>
class ExpireCache: public AbstractCache<TKey, TValue, ExpireStrategy<TKey, TValue > >
/// An ExpireCache caches entries for a fixed time period (per default 10 minutes)
/// Be careful when using an ExpireCache. A cache is often used
/// like cache.has(x) followed by cache.get x). Note that it could happen
/// that the "has" call works, then the current execution thread gets descheduled, time passes,
/// the entry gets invalid, thus leading to an empty SharedPtr being returned
/// when "get" is invoked.
{
public:
ExpireCache(Timestamp::TimeDiff expire = 600000):
AbstractCache<TKey, TValue, ExpireStrategy<TKey, TValue> >(ExpireStrategy<TKey, TValue>(expire))
{
}
~ExpireCache()
{
}
private:
ExpireCache(const ExpireCache& aCache);
ExpireCache& operator = (const ExpireCache& aCache);
};
} // namespace Poco
#endif

View File

@@ -0,0 +1,82 @@
//
// ExpireLRUCache.h
//
// $Id: //poco/1.2/Foundation/include/Poco/ExpireLRUCache.h#1 $
//
// Library: Foundation
// Package: Cache
// Module: ExpireLRUCache
//
// Definition of the ExpireLRUCache 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_ExpireLRUCache_INCLUDED
#define Foundation_ExpireLRUCache_INCLUDED
#include "Poco/AbstractCache.h"
#include "Poco/StrategyCollection.h"
#include "Poco/ExpireStrategy.h"
#include "Poco/LRUStrategy.h"
namespace Poco {
template <
class TKey,
class TValue
>
class ExpireLRUCache: public AbstractCache<TKey, TValue, StrategyCollection<TKey, TValue> >
/// An ExpireLRUCache combines LUR caching and time based expire caching.
/// It cache entries for a fixed time period (per default 10 minutes)
/// but also limits the size of the cache (per default: 1024).
{
public:
ExpireLRUCache(long cacheSize = 1024, Timestamp::TimeDiff expire = 600000):
AbstractCache<TKey, TValue, StrategyCollection<TKey, TValue> >(StrategyCollection<TKey, TValue>())
{
this->_strategy.pushBack(new LRUStrategy<TKey, TValue>(cacheSize));
this->_strategy.pushBack(new ExpireStrategy<TKey, TValue>(expire));
}
virtual ~ExpireLRUCache()
{
}
private:
ExpireLRUCache(const ExpireLRUCache& aCache);
ExpireLRUCache& operator = (const ExpireLRUCache& aCache);
};
} // namespace Poco
#endif

View File

@@ -0,0 +1,150 @@
//
// ExpireStrategy.h
//
// $Id: //poco/1.2/Foundation/include/Poco/ExpireStrategy.h#1 $
//
// Library: Foundation
// Package: Cache
// Module: ExpireStrategy
//
// Definition of the ExpireStrategy 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_ExpireStrategy_INCLUDED
#define Foundation_ExpireStrategy_INCLUDED
#include "Poco/KeyValueArgs.h"
#include "Poco/ValidArgs.h"
#include "Poco/AbstractStrategy.h"
#include "Poco/Bugcheck.h"
#include "Poco/Timestamp.h"
#include "Poco/EventArgs.h"
#include <set>
#include <map>
namespace Poco {
template <
class TKey,
class TValue
>
class ExpireStrategy: public AbstractStrategy<TKey, TValue>
/// An ExpireStrategy implements time based ecpiration of cache entries
{
public:
typedef std::multimap<Timestamp, TKey> TimeIndex;
typedef typename TimeIndex::iterator IndexIterator;
typedef typename TimeIndex::const_iterator ConstIndexIterator;
typedef std::map<TKey, IndexIterator> Keys;
typedef typename Keys::iterator Iterator;
public:
ExpireStrategy(Timestamp::TimeDiff expireTimeInMilliSec): _expireTime(expireTimeInMilliSec * 1000)
/// Create an expire strategy. Note that the smallest allowed caching time is 25ms.
/// Anything lower than that is not useful with current operating systems.
{
if (_expireTime < 25000) throw InvalidArgumentException("expireTime must be at least 25 ms");
}
virtual ~ExpireStrategy()
{
}
void onAdd(const void*, const KeyValueArgs <TKey, TValue>& args)
{
Timestamp now;
IndexIterator it = _keyIndex.insert(std::make_pair(now, args.key()));
std::pair < Iterator, bool > stat = _keys.insert(std::make_pair(args.key(), it));
if (!stat.second)
{
_keyIndex.erase(stat.first->second);
stat.first->second = it;
}
}
void onRemove(const void*, const TKey& key)
{
Iterator it = _keys.find(key);
if (it != _keys.end ())
{
_keyIndex.erase(it->second);
_keys.erase(it);
}
}
void onGet(const void*, const TKey& key)
{
// get triggers no changes in an expire
}
void onClear(const void*, const EventArgs& args)
{
_keys.clear();
_keyIndex.clear();
}
void onIsValid(const void*, ValidArgs<TKey>& args)
{
Iterator it = _keys.find(args.key());
if (it != _keys.end ())
{
if (it->second->first.isElapsed(_expireTime))
{
args.invalidate();
}
}
}
void onReplace(const void*, std::set<TKey>& elemsToRemove)
{
// Note: replace only informs the cache which elements
// it would like to remove!
// it does not remove them on its own!
IndexIterator it = _keyIndex.begin();
while (it != _keyIndex.end() && it->first.isElapsed(_expireTime))
{
elemsToRemove.insert(it->second);
++it;
}
}
protected:
Timestamp::TimeDiff _expireTime;
Keys _keys; /// For faster replacement of keys, the iterator points to the _keyIndex map
TimeIndex _keyIndex; /// Maps time to key value
};
} // namespace Poco
#endif

View File

@@ -0,0 +1,90 @@
//
// FIFOEvent.h
//
// $Id: //poco/1.2/Foundation/include/Poco/FIFOEvent.h#1 $
//
// Library: Foundation
// Package: Events
// Module: FIFOEvent
//
// Implementation of the FIFOEvent 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_FIFOEvent_INCLUDED
#define Foundation_FIFOEvent_INCLUDED
#include "Poco/AbstractEvent.h"
#include "Poco/FIFOStrategy.h"
#include "Poco/AbstractDelegate.h"
#include "Poco/CompareFunctions.h"
namespace Poco {
template <class TArgs>
class FIFOEvent: public AbstractEvent <
TArgs,
FIFOStrategy<TArgs, AbstractDelegate<TArgs>, p_less<AbstractDelegate< TArgs> > >,
AbstractDelegate<TArgs>
>
/// A FIFOEvent uses internally a FIFOStrategy which guarantees
/// that delegates are invoked in the order they were added to
/// the event.
///
/// Note that one object can only register one method to a FIFOEvent.
/// Subsequent registrations will overwrite the existing delegate.
/// For example:
/// FIFOEvent<int> tmp;
/// MyClass myObject;
/// tmp += Delegate<MyClass, int>(&myObject, &MyClass::myMethod1);
/// tmp += Delegate<MyClass, int>(&myObject, &MyClass::myMethod2);
///
/// The second registration will overwrite the first one.
{
public:
FIFOEvent()
{
}
~FIFOEvent()
{
}
private:
FIFOEvent(const FIFOEvent& e);
FIFOEvent& operator = (const FIFOEvent& e);
};
} // namespace Poco
#endif

View File

@@ -0,0 +1,160 @@
//
// FIFOStrategy.h
//
// $Id: //poco/1.2/Foundation/include/Poco/FIFOStrategy.h#1 $
//
// Library: Foundation
// Package: Events
// Module: FIFOStragegy
//
// Implementation of the FIFOStrategy 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_FIFOStrategy_INCLUDED
#define Foundation_FIFOStrategy_INCLUDED
#include "Poco/NotificationStrategy.h"
#include <map>
#include <list>
namespace Poco {
template <class TArgs, class TDelegate, class TCompare>
class FIFOStrategy: public NotificationStrategy<TArgs, TDelegate>
{
public:
typedef std::list<TDelegate*> Delegates;
typedef typename Delegates::iterator Iterator;
typedef typename Delegates::const_iterator ConstIterator;
typedef std::map<TDelegate*, Iterator, TCompare> DelegateIndex;
typedef typename DelegateIndex::iterator IndexIterator;
typedef typename DelegateIndex::const_iterator ConstIndexIterator;
FIFOStrategy()
{
}
FIFOStrategy(const FIFOStrategy& s)
{
operator = (s);
}
~FIFOStrategy()
{
clear();
}
void notify(const void* sender, TArgs& arguments)
{
std::vector<Iterator> delMe;
Iterator it = _observers.begin();
Iterator itEnd = _observers.end();
for (; it != itEnd; ++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)
{
IndexIterator it = _observerIndex.find(const_cast<TDelegate*>(&delegate));
if (it != _observerIndex.end())
{
delete *it->second;
_observers.erase(it->second);
_observerIndex.erase(it);
}
std::auto_ptr<TDelegate> pDelegate(delegate.clone());
_observers.push_back(pDelegate.get());
bool tmp = _observerIndex.insert(make_pair(pDelegate.get(), --_observers.end())).second;
poco_assert (tmp);
pDelegate.release();
}
void remove(const TDelegate& delegate)
{
IndexIterator it = _observerIndex.find(const_cast<TDelegate*>(&delegate));
if (it != _observerIndex.end())
{
delete *it->second;
_observers.erase(it->second);
_observerIndex.erase(it);
}
}
FIFOStrategy& operator = (const FIFOStrategy& 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();
_observerIndex.clear();
}
protected:
Delegates _observers; /// Stores the delegates in the order they were added.
DelegateIndex _observerIndex; /// For faster lookup when add/remove is used.
};
} // namespace Poco
#endif

View File

@@ -0,0 +1,227 @@
//
// FPEnvironment.h
//
// $Id: //poco/1.2/Foundation/include/Poco/FPEnvironment.h#1 $
//
// Library: Foundation
// Package: Core
// Module: FPEnvironment
//
// Definitions of class FPEnvironment.
//
// 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_FPEnvironment_INCLUDED
#define Foundation_FPEnvironment_INCLUDED
#include "Poco/Foundation.h"
#if defined(POCO_NO_FPENVIRONMENT)
#include "Poco/FPEnvironment_DUMMY.h"
#elif defined(__osf__) || defined(__VMS)
#include "Poco/FPEnvironment_DEC.h"
#elif defined(sun) || defined(__sun)
#include "Poco/FPEnvironment_SUN.h"
#elif defined(POCO_OS_FAMILY_UNIX)
#include "Poco/FPEnvironment_C99.h"
#elif defined(POCO_OS_FAMILY_WINDOWS)
#include "Poco/FPEnvironment_WIN32.h"
#else
#include "Poco/FPEnvironment_DUMMY.h"
#endif
namespace Poco {
class Foundation_API FPEnvironment: private FPEnvironmentImpl
/// Instances of this class can be used to save
/// and later restore the current floating
/// point environment (consisting of rounding
/// mode and floating-point flags).
/// The class also provides various static
/// methods to query certain properties
/// of a floating-point number.
{
public:
enum RoundingMode
{
FP_ROUND_DOWNWARD = FP_ROUND_DOWNWARD_IMPL,
FP_ROUND_UPWARD = FP_ROUND_UPWARD_IMPL,
FP_ROUND_TONEAREST = FP_ROUND_TONEAREST_IMPL,
FP_ROUND_TOWARDZERO = FP_ROUND_TOWARDZERO_IMPL
};
enum Flag
{
FP_DIVIDE_BY_ZERO = FP_DIVIDE_BY_ZERO_IMPL,
FP_INEXACT = FP_INEXACT_IMPL,
FP_OVERFLOW = FP_OVERFLOW_IMPL,
FP_UNDERFLOW = FP_UNDERFLOW_IMPL,
FP_INVALID = FP_INVALID_IMPL
};
FPEnvironment();
/// Standard constructor.
/// Remembers the current environment.
FPEnvironment(RoundingMode mode);
/// Remembers the current environment and
/// sets the given rounding mode.
FPEnvironment(const FPEnvironment& env);
/// Copy constructor.
~FPEnvironment();
/// Restores the previous environment (unless
/// keepCurrent() has been called previously)
FPEnvironment& operator = (const FPEnvironment& env);
/// Assignment operator
void keepCurrent();
/// Keep the current environment even after
/// destroying the FPEnvironment object.
static void clearFlags();
/// Resets all flags.
static bool isFlag(Flag flag);
/// Returns true iff the given flag is set.
static void setRoundingMode(RoundingMode mode);
/// Sets the rounding mode.
static RoundingMode getRoundingMode();
/// Returns the current rounding mode.
static bool isInfinite(float value);
static bool isInfinite(double value);
static bool isInfinite(long double value);
/// Returns true iff the given number is infinite.
static bool isNaN(float value);
static bool isNaN(double value);
static bool isNaN(long double value);
/// Returns true iff the given number is NaN.
static float copySign(float target, float source);
static double copySign(double target, double source);
static long double copySign(long double target, long double source);
/// Copies the sign from source to target.
};
//
// For convenience, we provide a shorter name for
// the FPEnvironment class.
//
typedef FPEnvironment FPE;
//
// inline's
//
inline bool FPEnvironment::isFlag(Flag flag)
{
return isFlagImpl(FlagImpl(flag));
}
inline void FPEnvironment::setRoundingMode(RoundingMode mode)
{
setRoundingModeImpl(RoundingModeImpl(mode));
}
inline FPEnvironment::RoundingMode FPEnvironment::getRoundingMode()
{
return RoundingMode(getRoundingModeImpl());
}
inline bool FPEnvironment::isInfinite(float value)
{
return isInfiniteImpl(value);
}
inline bool FPEnvironment::isInfinite(double value)
{
return isInfiniteImpl(value);
}
inline bool FPEnvironment::isInfinite(long double value)
{
return isInfiniteImpl(value);
}
inline bool FPEnvironment::isNaN(float value)
{
return isNaNImpl(value);
}
inline bool FPEnvironment::isNaN(double value)
{
return isNaNImpl(value);
}
inline bool FPEnvironment::isNaN(long double value)
{
return isNaNImpl(value);
}
inline float FPEnvironment::copySign(float target, float source)
{
return copySignImpl(target, source);
}
inline double FPEnvironment::copySign(double target, double source)
{
return copySignImpl(target, source);
}
inline long double FPEnvironment::copySign(long double target, long double source)
{
return copySignImpl(target, source);
}
} // namespace Poco
#endif // Foundation_FPEnvironment_INCLUDED

View File

@@ -0,0 +1,147 @@
//
// FPEnvironment_C99.h
//
// $Id: //poco/1.2/Foundation/include/Poco/FPEnvironment_C99.h#1 $
//
// Library: Foundation
// Package: Core
// Module: FPEnvironment
//
// Definitions of class FPEnvironmentImpl for C99.
//
// 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_FPEnvironment_C99_INCLUDED
#define Foundation_FPEnvironment_C99_INCLUDED
#include "Poco/Foundation.h"
#include <fenv.h>
#include <math.h>
namespace Poco {
class FPEnvironmentImpl
{
protected:
enum RoundingModeImpl
{
FP_ROUND_DOWNWARD_IMPL = FE_DOWNWARD,
FP_ROUND_UPWARD_IMPL = FE_UPWARD,
FP_ROUND_TONEAREST_IMPL = FE_TONEAREST,
FP_ROUND_TOWARDZERO_IMPL = FE_TOWARDZERO
};
enum FlagImpl
{
FP_DIVIDE_BY_ZERO_IMPL = FE_DIVBYZERO,
FP_INEXACT_IMPL = FE_INEXACT,
FP_OVERFLOW_IMPL = FE_OVERFLOW,
FP_UNDERFLOW_IMPL = FE_UNDERFLOW,
FP_INVALID_IMPL = FE_INVALID
};
FPEnvironmentImpl();
FPEnvironmentImpl(const FPEnvironmentImpl& env);
~FPEnvironmentImpl();
FPEnvironmentImpl& operator = (const FPEnvironmentImpl& env);
void keepCurrentImpl();
static void clearFlagsImpl();
static bool isFlagImpl(FlagImpl flag);
static void setRoundingModeImpl(RoundingModeImpl mode);
static RoundingModeImpl getRoundingModeImpl();
static bool isInfiniteImpl(float value);
static bool isInfiniteImpl(double value);
static bool isInfiniteImpl(long double value);
static bool isNaNImpl(float value);
static bool isNaNImpl(double value);
static bool isNaNImpl(long double value);
static float copySignImpl(float target, float source);
static double copySignImpl(double target, double source);
static long double copySignImpl(long double target, long double source);
private:
fenv_t _env;
};
//
// inlines
//
inline bool FPEnvironmentImpl::isInfiniteImpl(float value)
{
return isinf(value) != 0;
}
inline bool FPEnvironmentImpl::isInfiniteImpl(double value)
{
return isinf(value) != 0;
}
inline bool FPEnvironmentImpl::isInfiniteImpl(long double value)
{
return isinf((double) value) != 0;
}
inline bool FPEnvironmentImpl::isNaNImpl(float value)
{
return isnan(value) != 0;
}
inline bool FPEnvironmentImpl::isNaNImpl(double value)
{
return isnan(value) != 0;
}
inline bool FPEnvironmentImpl::isNaNImpl(long double value)
{
return isnan((double) value) != 0;
}
inline float FPEnvironmentImpl::copySignImpl(float target, float source)
{
return copysignf(target, source);
}
inline double FPEnvironmentImpl::copySignImpl(double target, double source)
{
return copysign(target, source);
}
} // namespace Poco
#endif // Foundation_FPEnvironment_C99_INCLUDED

View File

@@ -0,0 +1,111 @@
//
// FPEnvironment_DEC.h
//
// $Id: //poco/1.2/Foundation/include/Poco/FPEnvironment_DEC.h#1 $
//
// Library: Foundation
// Package: Core
// Module: FPEnvironment
//
// Definitions of class FPEnvironmentImpl for Tru64 and OpenVMS Alpha.
//
// 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_FPEnvironment_DEC_INCLUDED
#define Foundation_FPEnvironment_DEC_INCLUDED
#include "Poco/Foundation.h"
#if defined(__VMS)
#include <ieeedef.h>
#else
#include <machine/fpu.h>
#endif
namespace Poco {
class FPEnvironmentImpl
{
protected:
enum RoundingModeImpl
{
FP_ROUND_DOWNWARD_IMPL = 0,
FP_ROUND_UPWARD_IMPL = 0,
FP_ROUND_TONEAREST_IMPL = 0,
FP_ROUND_TOWARDZERO_IMPL = 0
};
enum FlagImpl
{
#if defined(__VMS)
FP_DIVIDE_BY_ZERO_IMPL = IEEE$M_STATUS_DZE,
FP_INEXACT_IMPL = IEEE$M_STATUS_INE,
FP_OVERFLOW_IMPL = IEEE$M_STATUS_OVF,
FP_UNDERFLOW_IMPL = IEEE$M_STATUS_UNF,
FP_INVALID_IMPL = IEEE$M_STATUS_INV
#else
FP_DIVIDE_BY_ZERO_IMPL = IEEE_STATUS_DZE,
FP_INEXACT_IMPL = IEEE_STATUS_INE,
FP_OVERFLOW_IMPL = IEEE_STATUS_OVF,
FP_UNDERFLOW_IMPL = IEEE_STATUS_UNF,
FP_INVALID_IMPL = IEEE_STATUS_INV
#endif
};
FPEnvironmentImpl();
FPEnvironmentImpl(const FPEnvironmentImpl& env);
~FPEnvironmentImpl();
FPEnvironmentImpl& operator = (const FPEnvironmentImpl& env);
void keepCurrentImpl();
static void clearFlagsImpl();
static bool isFlagImpl(FlagImpl flag);
static void setRoundingModeImpl(RoundingModeImpl mode);
static RoundingModeImpl getRoundingModeImpl();
static bool isInfiniteImpl(float value);
static bool isInfiniteImpl(double value);
static bool isInfiniteImpl(long double value);
static bool isNaNImpl(float value);
static bool isNaNImpl(double value);
static bool isNaNImpl(long double value);
static float copySignImpl(float target, float source);
static double copySignImpl(double target, double source);
static long double copySignImpl(long double target, long double source);
private:
#if defined(__VMS)
struct _ieee _env;
#else
unsigned long _env;
#endif
};
} // namespace Poco
#endif // Foundation_FPEnvironment_DEC_INCLUDED

View File

@@ -0,0 +1,147 @@
//
// FPEnvironment_DUMMY.h
//
// $Id: //poco/1.2/Foundation/include/Poco/FPEnvironment_DUMMY.h#1 $
//
// Library: Foundation
// Package: Core
// Module: FPEnvironment
//
// Definition of class FPEnvironmentImpl for platforms that do not
// support IEEE 754 extensions.
//
// 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_FPEnvironment_DUMMY_INCLUDED
#define Foundation_FPEnvironment_DUMMY_INCLUDED
#include "Poco/Foundation.h"
#include <math.h>
namespace Poco {
class Foundation_API FPEnvironmentImpl
{
protected:
enum RoundingModeImpl
{
FP_ROUND_DOWNWARD_IMPL,
FP_ROUND_UPWARD_IMPL,
FP_ROUND_TONEAREST_IMPL,
FP_ROUND_TOWARDZERO_IMPL
};
enum FlagImpl
{
FP_DIVIDE_BY_ZERO_IMPL,
FP_INEXACT_IMPL,
FP_OVERFLOW_IMPL,
FP_UNDERFLOW_IMPL,
FP_INVALID_IMPL
};
FPEnvironmentImpl();
FPEnvironmentImpl(const FPEnvironmentImpl& env);
~FPEnvironmentImpl();
FPEnvironmentImpl& operator = (const FPEnvironmentImpl& env);
void keepCurrentImpl();
static void clearFlagsImpl();
static bool isFlagImpl(FlagImpl flag);
static void setRoundingModeImpl(RoundingModeImpl mode);
static RoundingModeImpl getRoundingModeImpl();
static bool isInfiniteImpl(float value);
static bool isInfiniteImpl(double value);
static bool isInfiniteImpl(long double value);
static bool isNaNImpl(float value);
static bool isNaNImpl(double value);
static bool isNaNImpl(long double value);
static float copySignImpl(float target, float source);
static double copySignImpl(double target, double source);
static long double copySignImpl(long double target, long double source);
private:
static RoundingModeImpl _roundingMode;
};
//
// inlines
//
inline bool FPEnvironmentImpl::isInfiniteImpl(float value)
{
return isinf(value) != 0;
}
inline bool FPEnvironmentImpl::isInfiniteImpl(double value)
{
return isinf(value) != 0;
}
inline bool FPEnvironmentImpl::isInfiniteImpl(long double value)
{
return isinf((double) value) != 0;
}
inline bool FPEnvironmentImpl::isNaNImpl(float value)
{
return isnan(value) != 0;
}
inline bool FPEnvironmentImpl::isNaNImpl(double value)
{
return isnan(value) != 0;
}
inline bool FPEnvironmentImpl::isNaNImpl(long double value)
{
return isnan((double) value) != 0;
}
inline float FPEnvironmentImpl::copySignImpl(float target, float source)
{
return copysignf(target, source);
}
inline double FPEnvironmentImpl::copySignImpl(double target, double source)
{
return copysign(target, source);
}
} // namespace Poco
#endif // Foundation_FPEnvironment_DUMMY_INCLUDED

View File

@@ -0,0 +1,96 @@
//
// FPEnvironment_SUN.h
//
// $Id: //poco/1.2/Foundation/include/Poco/FPEnvironment_SUN.h#1 $
//
// Library: Foundation
// Package: Core
// Module: FPEnvironment
//
// Definitions of class FPEnvironmentImpl for Solaris.
//
// 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_FPEnvironment_SUN_INCLUDED
#define Foundation_FPEnvironment_SUN_INCLUDED
#include "Poco/Foundation.h"
#include <ieeefp.h>
namespace Poco {
class FPEnvironmentImpl
{
protected:
enum RoundingModeImpl
{
FP_ROUND_DOWNWARD_IMPL = FP_RM,
FP_ROUND_UPWARD_IMPL = FP_RP,
FP_ROUND_TONEAREST_IMPL = FP_RN,
FP_ROUND_TOWARDZERO_IMPL = FP_RZ
};
enum FlagImpl
{
FP_DIVIDE_BY_ZERO_IMPL = FP_X_DZ,
FP_INEXACT_IMPL = FP_X_IMP,
FP_OVERFLOW_IMPL = FP_X_OFL,
FP_UNDERFLOW_IMPL = FP_X_UFL,
FP_INVALID_IMPL = FP_X_INV
};
FPEnvironmentImpl();
FPEnvironmentImpl(const FPEnvironmentImpl& env);
~FPEnvironmentImpl();
FPEnvironmentImpl& operator = (const FPEnvironmentImpl& env);
void keepCurrentImpl();
static void clearFlagsImpl();
static bool isFlagImpl(FlagImpl flag);
static void setRoundingModeImpl(RoundingModeImpl mode);
static RoundingModeImpl getRoundingModeImpl();
static bool isInfiniteImpl(float value);
static bool isInfiniteImpl(double value);
static bool isInfiniteImpl(long double value);
static bool isNaNImpl(float value);
static bool isNaNImpl(double value);
static bool isNaNImpl(long double value);
static float copySignImpl(float target, float source);
static double copySignImpl(double target, double source);
static long double copySignImpl(long double target, long double source);
private:
fp_rnd _rnd;
fp_except _exc;
};
} // namespace Poco
#endif // Foundation_FPEnvironment_SUN_INCLUDED

View File

@@ -0,0 +1,153 @@
//
// FPEnvironment_WIN32.h
//
// $Id: //poco/1.2/Foundation/include/Poco/FPEnvironment_WIN32.h#1 $
//
// Library: Foundation
// Package: Core
// Module: FPEnvironment
//
// Definitions of class FPEnvironmentImpl for WIN32.
//
// 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_FPEnvironment_WIN32_INCLUDED
#define Foundation_FPEnvironment_WIN32_INCLUDED
#include "Poco/Foundation.h"
#include <float.h>
#include <math.h>
namespace Poco {
class Foundation_API FPEnvironmentImpl
{
protected:
enum RoundingModeImpl
{
FP_ROUND_DOWNWARD_IMPL = RC_DOWN,
FP_ROUND_UPWARD_IMPL = RC_UP,
FP_ROUND_TONEAREST_IMPL = RC_NEAR,
FP_ROUND_TOWARDZERO_IMPL = RC_CHOP
};
enum FlagImpl
{
FP_DIVIDE_BY_ZERO_IMPL = SW_ZERODIVIDE,
FP_INEXACT_IMPL = SW_INEXACT,
FP_OVERFLOW_IMPL = SW_OVERFLOW,
FP_UNDERFLOW_IMPL = SW_UNDERFLOW,
FP_INVALID_IMPL = SW_INVALID
};
FPEnvironmentImpl();
FPEnvironmentImpl(const FPEnvironmentImpl& env);
~FPEnvironmentImpl();
FPEnvironmentImpl& operator = (const FPEnvironmentImpl& env);
void keepCurrentImpl();
static void clearFlagsImpl();
static bool isFlagImpl(FlagImpl flag);
static void setRoundingModeImpl(RoundingModeImpl mode);
static RoundingModeImpl getRoundingModeImpl();
static bool isInfiniteImpl(float value);
static bool isInfiniteImpl(double value);
static bool isInfiniteImpl(long double value);
static bool isNaNImpl(float value);
static bool isNaNImpl(double value);
static bool isNaNImpl(long double value);
static float copySignImpl(float target, float source);
static double copySignImpl(double target, double source);
static long double copySignImpl(long double target, long double source);
private:
unsigned _env;
};
//
// inlines
//
inline bool FPEnvironmentImpl::isInfiniteImpl(float value)
{
return _finite(value) == 0;
}
inline bool FPEnvironmentImpl::isInfiniteImpl(double value)
{
return _finite(value) == 0;
}
inline bool FPEnvironmentImpl::isInfiniteImpl(long double value)
{
return _finite(value) == 0;
}
inline bool FPEnvironmentImpl::isNaNImpl(float value)
{
return _isnan(value) != 0;
}
inline bool FPEnvironmentImpl::isNaNImpl(double value)
{
return _isnan(value) != 0;
}
inline bool FPEnvironmentImpl::isNaNImpl(long double value)
{
return _isnan(value) != 0;
}
inline float FPEnvironmentImpl::copySignImpl(float target, float source)
{
return float(_copysign(target, source));
}
inline double FPEnvironmentImpl::copySignImpl(double target, double source)
{
return _copysign(target, source);
}
inline long double FPEnvironmentImpl::copySignImpl(long double target, long double source)
{
return (source > 0 && target > 0) || (source < 0 && target < 0) ? target : -target;
}
} // namespace Poco
#endif // Foundation_FPEnvironment_WIN32_INCLUDED

View File

@@ -0,0 +1,253 @@
//
// File.h
//
// $Id: //poco/1.2/Foundation/include/Poco/File.h#1 $
//
// Library: Foundation
// Package: Filesystem
// Module: File
//
// Definition of the File 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_File_INCLUDED
#define Foundation_File_INCLUDED
#include "Poco/Foundation.h"
#include "Poco/Timestamp.h"
#include <vector>
#if defined(POCO_OS_FAMILY_WINDOWS) && defined(POCO_WIN32_UTF8)
#include "Poco/File_WIN32U.h"
#elif defined(POCO_OS_FAMILY_WINDOWS)
#include "Poco/File_WIN32.h"
#elif defined(POCO_OS_FAMILY_UNIX)
#include "Poco/File_UNIX.h"
#else
#include "Poco/File_VMS.h"
#endif
namespace Poco {
class Path;
class Foundation_API File: private FileImpl
/// The File class provides methods for working with a file.
{
public:
typedef FileSizeImpl FileSize;
File();
/// Creates the file.
File(const std::string& path);
/// Creates the file.
File(const char* path);
/// Creates the file.
File(const Path& path);
/// Creates the file.
File(const File& file);
/// Copy constructor.
virtual ~File();
/// Destroys the file.
File& operator = (const File& file);
/// Assignment operator.
File& operator = (const std::string& path);
/// Assignment operator.
File& operator = (const char* path);
/// Assignment operator.
File& operator = (const Path& path);
/// Assignment operator.
void swap(File& file);
/// Swaps the file with another one.
const std::string& path() const;
/// Returns the path.
bool exists() const;
/// Returns true iff the file exists.
bool canRead() const;
/// Returns true iff the file is readable.
bool canWrite() const;
/// Returns true iff the file is writeable.
bool isFile() const;
/// Returns true iff the file is a regular file.
bool isLink() const;
/// Returns true iff the file is a symbolic link.
bool isDirectory() const;
/// Returns true iff the file is a directory.
Timestamp created() const;
/// Returns the creation date of the file.
Timestamp getLastModified() const;
/// Returns the modification date of the file.
void setLastModified(const Timestamp& ts);
/// Sets the modification date of the file.
FileSize getSize() const;
/// Returns the size of the file in bytes.
void setSize(FileSize size);
/// Sets the size of the file in bytes. Can be used
/// to truncate a file.
void setWriteable(bool flag = true);
/// Makes the file writeable (if flag is true), or
/// non-writeable (if flag is false) by setting the
/// file's flags in the filesystem accordingly.
void setReadOnly(bool flag = true);
/// Makes the file non-writeable (if flag is true), or
/// writeable (if flag is false) by setting the
/// file's flags in the filesystem accordingly.
void copyTo(const std::string& path) const;
/// Copies the file to the given path. The target path
/// can be a directory.
void moveTo(const std::string& path);
/// Copies the file to the given path and removes the
/// original file. The target path can be a directory.
void renameTo(const std::string& path);
/// Renames the file to the new name.
void remove(bool recursive = false);
/// Deletes the file. If recursive is true and the
/// file is a directory, recursively deletes all
/// files in the directory.
bool createFile();
/// Creates a new, empty file in an atomic operation.
/// Returns true if the file has been created and false
/// if the file already exists. Throws an exception if
/// an error occurs.
bool createDirectory();
/// Creates a directory. Returns true if the directory
/// has been created and false if it already exists.
/// Throws an exception if an error occurs.
void createDirectories();
/// Creates a directory (and all parent directories
/// if necessary).
void list(std::vector<std::string>& files) const;
/// Fills the vector with the names of all
/// files in the directory.
void list(std::vector<File>& files) const;
/// Fills the vector with the names of all
/// files in the directory.
bool operator == (const File& file) const;
bool operator != (const File& file) const;
bool operator < (const File& file) const;
bool operator <= (const File& file) const;
bool operator > (const File& file) const;
bool operator >= (const File& file) const;
};
//
// inlines
//
inline const std::string& File::path() const
{
return getPathImpl();
}
inline bool File::operator == (const File& file) const
{
return getPathImpl() == file.getPathImpl();
}
inline bool File::operator != (const File& file) const
{
return getPathImpl() != file.getPathImpl();
}
inline bool File::operator < (const File& file) const
{
return getPathImpl() < file.getPathImpl();
}
inline bool File::operator <= (const File& file) const
{
return getPathImpl() <= file.getPathImpl();
}
inline bool File::operator > (const File& file) const
{
return getPathImpl() > file.getPathImpl();
}
inline bool File::operator >= (const File& file) const
{
return getPathImpl() >= file.getPathImpl();
}
inline void swap(File& f1, File& f2)
{
f1.swap(f2);
}
} // namespace Poco
#endif // Foundation_File_INCLUDED

View File

@@ -0,0 +1,248 @@
//
// FileChannel.h
//
// $Id: //poco/1.2/Foundation/include/Poco/FileChannel.h#1 $
//
// Library: Foundation
// Package: Logging
// Module: FileChannel
//
// Definition of the FileChannel 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_FileChannel_INCLUDED
#define Foundation_FileChannel_INCLUDED
#include "Poco/Foundation.h"
#include "Poco/Channel.h"
#include "Poco/Timestamp.h"
#include "Poco/Mutex.h"
namespace Poco {
class LogFile;
class RotateStrategy;
class ArchiveStrategy;
class PurgeStrategy;
class Foundation_API FileChannel: public Channel
/// A Channel that writes to a file. This class supports
/// flexible log file rotation and archiving, as well
/// as automatic purging of archived log files.
///
/// 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 in the text.
///
/// The FileChannel support log file rotation based
/// on log file size or time intervals.
/// Archived log files can be compressed in gzip format.
/// Older archived files can be automatically deleted
/// (purged).
///
/// The rotation strategy can be specified with the
/// "rotation" property, which can take one of the
/// follwing values:
///
/// * never: no log rotation
/// * [day,][hh]:mm: the file is rotated on specified day/time
/// day - day is specified as long or short day name (Monday|Mon, Tuesday|Tue, ... );
/// day can be omitted, in which case log is rotated every day
/// hh - valid hour range is 00-23;
/// hour can be omitted, in which case log is rotated every hour
/// mm - valid minute range is 00-59;
/// minute must be specified
/// * daily: the file is rotated daily
/// * weekly: the file is rotated every seven days
/// * monthly: the file is rotated every 30 days
/// * <n> hours: the file is rotated every <n> hours, where
/// <n> is an integer greater than zero.
/// * <n> days: the file is rotated every <n> days, where
/// <n> is an integer greater than zero.
/// * <n> weeks: the file is rotated every <n> weeks, where
/// <n> is an integer greater than zero.
/// * <n> months: the file is rotated every <n> months, where
/// <n> is an integer greater than zero and
/// a month has 30 days.
/// * <n>: the file is rotated when its size exceeds
/// <n> bytes.
/// * <n> K: the file is rotated when its size exceeds
/// <n> Kilobytes.
/// * <n> M: the file is rotated when its size exceeds
/// <n> Megabytes.
///
/// Using the "archive" property it is possible to specify
/// how archived log files are named. The following values
/// for the "archive" property are supported:
///
/// * number: A number, starting with 0, is appended to
/// the name of archived log files. The newest
/// archived log file always has the number 0.
/// For example, if the log file is named
/// "access.log", and it fulfils the criteria
/// for rotation, the file is renamed to
/// "access.log.0". If a file named "access.log.0"
/// already exists, it is renamed to "access.log.1",
/// and so on.
/// * timestamp: A timestamp is appended to the log file name.
/// For example, if the log file is named
/// "access.log", and it fulfils the criteria
/// for rotation, the file is renamed to
/// "access.log.20050802110300".
///
/// Using the "times" property it is possible to specify
/// time mode for the day/time based rotation. The following values
/// for the "times" property are supported:
///
/// * utc: Rotation strategy is based on UTC time (default).
/// * local: Rotation strategy is based on local time.
///
/// Archived log files can be compressed using the gzip compression
/// method. Compressing can be controlled with the "compression"
/// property. The following values for the "compress" property
/// are supported:
///
/// * true: Compress archived log files.
/// * false: Do not compress archived log files.
///
/// Archived log files can be automatically purged, either if
/// they reach a certain age, or if the number of archived
/// log files reaches a given maximum number. This is
/// controlled by the purgeAge and purgeCount properties.
///
/// The purgeAge property can have the following values:
///
/// * <n> [seconds] the maximum age is <n> seconds.
/// * <n> minutes: the maximum age is <n> minutes.
/// * <n> hours: the maximum age is <n> hours.
/// * <n> days: the maximum age is <n> days.
/// * <n> weeks: the maximum age is <n> weeks.
/// * <n> months: the maximum age is <n> months, where a month has 30 days.
///
/// The purgeCount property has an integer value that
/// specifies the maximum number of archived log files.
/// If the number is exceeded, archived log files are
/// deleted, starting with the oldest.
///
/// For a more lightweight file channel class, see SimpleFileChannel.
{
public:
FileChannel();
/// Creates the FileChannel.
FileChannel(const std::string& path);
/// Creates the FileChannel for a file with the given path.
void open();
/// Opens the FileChannel and creates the log file if necessary.
void close();
/// Closes the FileChannel.
void log(const Message& msg);
/// Logs the given message to the file.
void setProperty(const std::string& name, const std::string& value);
/// Sets the property with the given name.
///
/// The following properties are supported:
/// * path: The log file's path.
/// * rotation: The log file's rotation mode. See the
/// FileChannel class for details.
/// * archive: The log file's archive mode. See the
/// FileChannel class for details.
/// * times: The log file's time mode. See the
/// FileChannel class for details.
/// * compress: Enable or disable compression of
/// archived files. See the FileChannel class
/// for details.
/// * purgeAge: Maximum age of an archived log file before
/// it is purged. See the FileChannel class for
/// details.
/// * purgeCount: Maximum number of archived log files before
/// files are purged. See the FileChannel class
/// for details.
std::string getProperty(const std::string& name) const;
/// Returns the value of the property with the given name.
/// See setProperty() for a description of the supported
/// properties.
Timestamp creationDate() const;
/// Returns the log file's creation date.
UInt64 size() const;
/// Returns the log file's current size in bytes.
const std::string& path() const;
/// Returns the log file's path.
static const std::string PROP_PATH;
static const std::string PROP_ROTATION;
static const std::string PROP_ARCHIVE;
static const std::string PROP_TIMES;
static const std::string PROP_COMPRESS;
static const std::string PROP_PURGEAGE;
static const std::string PROP_PURGECOUNT;
protected:
~FileChannel();
void setRotation(const std::string& rotation);
void setArchive(const std::string& archive);
void setCompress(const std::string& compress);
void setPurgeAge(const std::string& age);
void setPurgeCount(const std::string& count);
void purge();
private:
std::string _path;
std::string _times;
std::string _rotation;
std::string _archive;
bool _compress;
std::string _purgeAge;
std::string _purgeCount;
LogFile* _pFile;
RotateStrategy* _pRotateStrategy;
ArchiveStrategy* _pArchiveStrategy;
PurgeStrategy* _pPurgeStrategy;
FastMutex _mutex;
};
} // namespace Poco
#endif // Foundation_FileChannel_INCLUDED

View File

@@ -0,0 +1,83 @@
//
// FileStreamFactory.h
//
// $Id: //poco/1.2/Foundation/include/Poco/FileStreamFactory.h#1 $
//
// Library: Foundation
// Package: URI
// Module: FileStreamFactory
//
// Definition of the FileStreamFactory 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_FileStreamFactory_INCLUDED
#define Foundation_FileStreamFactory_INCLUDED
#include "Poco/Foundation.h"
#include "Poco/URIStreamFactory.h"
namespace Poco {
class Path;
class Foundation_API FileStreamFactory: public URIStreamFactory
/// An implementation of the URIStreamFactory interface
/// that handles file URIs.
{
public:
FileStreamFactory();
/// Creates the FileStreamFactory.
~FileStreamFactory();
/// Destroys the FileStreamFactory.
std::istream* open(const URI& uri);
/// Creates and opens a file stream in binary mode for the given URI.
/// The URI must be either a file URI or a relative URI reference
/// containing a path to a local file.
///
/// Throws an FileNotFound exception if the file cannot
/// be opened.
std::istream* open(const Path& path);
/// Creates and opens a file stream in binary mode for the given path.
///
/// Throws an FileNotFound exception if the file cannot
/// be opened.
};
} // namespace Poco
#endif // Foundation_FileStreamFactory_INCLUDED

View File

@@ -0,0 +1,98 @@
//
// File_UNIX.h
//
// $Id: //poco/1.2/Foundation/include/Poco/File_UNIX.h#1 $
//
// Library: Foundation
// Package: Filesystem
// Module: File
//
// Definition of the FileImpl class for Unix.
//
// 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_File_UNIX_INCLUDED
#define Foundation_File_UNIX_INCLUDED
#include "Poco/Foundation.h"
namespace Poco {
class FileImpl
{
protected:
typedef UInt64 FileSizeImpl;
FileImpl();
FileImpl(const std::string& path);
virtual ~FileImpl();
void swapImpl(FileImpl& file);
void setPathImpl(const std::string& path);
const std::string& getPathImpl() const;
bool existsImpl() const;
bool canReadImpl() const;
bool canWriteImpl() const;
bool isFileImpl() const;
bool isDirectoryImpl() const;
bool isLinkImpl() const;
Timestamp createdImpl() const;
Timestamp getLastModifiedImpl() const;
void setLastModifiedImpl(const Timestamp& ts);
FileSizeImpl getSizeImpl() const;
void setSizeImpl(FileSizeImpl size);
void setWriteableImpl(bool flag = true);
void copyToImpl(const std::string& path) const;
void renameToImpl(const std::string& path);
void removeImpl();
bool createFileImpl();
bool createDirectoryImpl();
static void handleError(const std::string& path);
private:
std::string _path;
friend class DirectoryIteratorImpl;
};
//
// inlines
//
inline const std::string& FileImpl::getPathImpl() const
{
return _path;
}
} // namespace Poco
#endif // Foundation_File_UNIX_INCLUDED

View File

@@ -0,0 +1,97 @@
//
// File_VMS.h
//
// $Id: //poco/1.2/Foundation/include/Poco/File_VMS.h#1 $
//
// Library: Foundation
// Package: Filesystem
// Module: File
//
// Definition of the FileImpl class for OpenVMS.
//
// 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_File_VMS_INCLUDED
#define Foundation_File_VMS_INCLUDED
#include "Poco/Foundation.h"
namespace Poco {
class FileImpl
{
protected:
typedef UInt64 FileSizeImpl;
FileImpl();
FileImpl(const std::string& path);
virtual ~FileImpl();
void setPath(const std::string& path);
void swapImpl(FileImpl& file);
void setPathImpl(const std::string& path);
const std::string& getPathImpl() const;
bool existsImpl() const;
bool canReadImpl() const;
bool canWriteImpl() const;
bool isFileImpl() const;
bool isDirectoryImpl() const;
bool isLinkImpl() const;
Timestamp createdImpl() const;
Timestamp getLastModifiedImpl() const;
void setLastModifiedImpl(const Timestamp& ts);
FileSizeImpl getSizeImpl() const;
void setSizeImpl(FileSizeImpl size);
void setWriteableImpl(bool flag = true);
void copyToImpl(const std::string& path) const;
void renameToImpl(const std::string& path);
void removeImpl();
bool createFileImpl();
bool createDirectoryImpl();
static void handleError(const std::string& path);
private:
std::string _path;
};
//
// inlines
//
inline const std::string& FileImpl::getPathImpl() const
{
return _path;
}
} // namespace Poco
#endif // Foundation_File_VMS_INCLUDED

View File

@@ -0,0 +1,100 @@
//
// File_WIN32.h
//
// $Id: //poco/1.2/Foundation/include/Poco/File_WIN32.h#1 $
//
// Library: Foundation
// Package: Filesystem
// Module: File
//
// Definition of the FileImpl class for WIN32.
//
// 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_File_WIN32_INCLUDED
#define Foundation_File_WIN32_INCLUDED
#include "Poco/Foundation.h"
#include "Poco/Timestamp.h"
namespace Poco {
class Foundation_API FileImpl
{
protected:
typedef UInt64 FileSizeImpl;
FileImpl();
FileImpl(const std::string& path);
virtual ~FileImpl();
void swapImpl(FileImpl& file);
void setPathImpl(const std::string& path);
const std::string& getPathImpl() const;
bool existsImpl() const;
bool canReadImpl() const;
bool canWriteImpl() const;
bool isFileImpl() const;
bool isDirectoryImpl() const;
bool isLinkImpl() const;
Timestamp createdImpl() const;
Timestamp getLastModifiedImpl() const;
void setLastModifiedImpl(const Timestamp& ts);
FileSizeImpl getSizeImpl() const;
void setSizeImpl(FileSizeImpl size);
void setWriteableImpl(bool flag = true);
void copyToImpl(const std::string& path) const;
void renameToImpl(const std::string& path);
void removeImpl();
bool createFileImpl();
bool createDirectoryImpl();
static void handleError(const std::string& path);
private:
std::string _path;
friend class FileHandle;
friend class DirectoryIteratorImpl;
};
//
// inlines
//
inline const std::string& FileImpl::getPathImpl() const
{
return _path;
}
} // namespace Poco
#endif // Foundation_File_WIN32_INCLUDED

View File

@@ -0,0 +1,101 @@
//
// File_WIN32U.h
//
// $Id: //poco/1.2/Foundation/include/Poco/File_WIN32U.h#1 $
//
// Library: Foundation
// Package: Filesystem
// Module: File
//
// Definition of the Unicode FileImpl class for WIN32.
//
// 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_File_WIN32U_INCLUDED
#define Foundation_File_WIN32U_INCLUDED
#include "Poco/Foundation.h"
#include "Poco/Timestamp.h"
namespace Poco {
class Foundation_API FileImpl
{
protected:
typedef UInt64 FileSizeImpl;
FileImpl();
FileImpl(const std::string& path);
virtual ~FileImpl();
void swapImpl(FileImpl& file);
void setPathImpl(const std::string& path);
const std::string& getPathImpl() const;
bool existsImpl() const;
bool canReadImpl() const;
bool canWriteImpl() const;
bool isFileImpl() const;
bool isDirectoryImpl() const;
bool isLinkImpl() const;
Timestamp createdImpl() const;
Timestamp getLastModifiedImpl() const;
void setLastModifiedImpl(const Timestamp& ts);
FileSizeImpl getSizeImpl() const;
void setSizeImpl(FileSizeImpl size);
void setWriteableImpl(bool flag = true);
void copyToImpl(const std::string& path) const;
void renameToImpl(const std::string& path);
void removeImpl();
bool createFileImpl();
bool createDirectoryImpl();
static void handleError(const std::string& path);
private:
std::string _path;
std::wstring _upath;
friend class FileHandle;
friend class DirectoryIteratorImpl;
};
//
// inlines
//
inline const std::string& FileImpl::getPathImpl() const
{
return _path;
}
} // namespace Poco
#endif // Foundation_File_WIN32U_INCLUDED

View File

@@ -0,0 +1,154 @@
//
// Format.h
//
// $Id: //poco/1.2/Foundation/include/Poco/Format.h#1 $
//
// Library: Foundation
// Package: Core
// Module: Format
//
// Definition of the format freestanding function.
//
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// 3. Redistributions in any form must be accompanied by information on
// how to obtain complete source code for this software and any
// accompanying software that uses this software. The source code
// must either be included in the distribution or be available for no
// more than the cost of distribution plus a nominal fee, and must be
// freely redistributable under reasonable conditions. For an
// executable file, complete source code means the source code for all
// modules it contains. It does not include source code for modules or
// files that typically accompany the major components of the operating
// system on which the executable file runs.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
#ifndef Foundation_Format_INCLUDED
#define Foundation_Format_INCLUDED
#include "Poco/Foundation.h"
#include "Poco/Any.h"
#include <vector>
namespace Poco {
std::string Foundation_API format(const std::string& fmt, const Any& value);
/// This function implements sprintf-style formatting in a typesafe way.
/// Various variants of the function are available, supporting a
/// different number of arguments (up to six).
///
/// The formatting is controlled by the format string in fmt.
/// Format strings are quite similar to those of the printf() function, but
/// there are some minor differences.
///
/// The format string can consist of any sequence of characters; certain
/// characters have a special meaning. Characters without a special meaning
/// are copied verbatim to the result. A percent sign (%) marks the beginning
/// of a format specification. Format specifications have the following syntax:
///
/// %[<flags>][<width>][.<precision>][<modifier>]<type>
///
/// Flags, width, precision and prefix are optional. The only required part of
/// the format specification, apart from the percent sign, is the type.
///
/// Following are valid type specifications and their meaning:
///
/// * c character
/// * d signed decimal integer
/// * i signed decimal integer
/// * o unsigned octal integer
/// * u unsigned decimal integer
/// * x unsigned hexadecimal integer (lower case)
/// * X unsigned hexadecimal integer (upper case)
/// * e signed floating-point value in the form [-]d.dddde[<sign>]dd[d]
/// * E signed floating-point value in the form [-]d.ddddE[<sign>]dd[d]
/// * f signed floating-point value in the form [-]dddd.dddd
/// * s std::string
///
/// The following flags are supported:
///
/// * - left align the result within the given field width
/// * + prefix the output value with a sign (+ or <20>) if the output value is of a signed type
/// * 0 if width is prefixed with 0, zeros are added until the minimum width is reached
/// * # For o, x, X, the # flag prefixes any nonzero output value with 0, 0x, or 0X, respectively;
/// for e, E, f, the # flag forces the output value to contain a decimal point in all cases.
///
/// The following modifiers are supported:
///
/// * (none) argument is char (c), int (d, i), unsigned (o, u, x, X) double (e, E, f, g, G) or string (s)
/// * l argument is long (d, i), unsigned long (o, u, x, X) or long double (e, E, f, g, G)
/// * L argument is long long (d, i), unsigned long long (o, u, x, X)
/// * h argument is short (d, i), unsigned short (o, u, x, X) or float (e, E, f, g, G)
///
/// The width argument is a nonnegative decimal integer controlling the minimum number of characters printed.
/// If the number of characters in the output value is less than the specified width, blanks or
/// leading zeros are added, according to the specified flags (-, +, 0).
///
/// Precision is a nonnegative decimal integer, preceded by a period (.), which specifies the number of characters
/// to be printed, the number of decimal places, or the number of significant digits.
///
/// Throws a BadCastException if an argument does not correspond to the type of its format specification.
///
/// If there are more format specifiers than values, the format specifiers without a corresponding value
/// are copied verbatim to output.
///
/// If there are more values than format specifiers, the superfluous values are ignored.
///
/// Usage Example:
/// std::string s = format("The answer to life, the universe, and everything is %d", 42);
std::string Foundation_API format(const std::string& fmt, const Any& value1, const Any& value2);
std::string Foundation_API format(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3);
std::string Foundation_API format(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4);
std::string Foundation_API format(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5);
std::string Foundation_API format(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5, const Any& value6);
void Foundation_API format(std::string& result, const std::string& fmt, const Any& value);
/// Appends the formatted string to result.
void Foundation_API format(std::string& result, const std::string& fmt, const Any& value1, const Any& value2);
void Foundation_API format(std::string& result, const std::string& fmt, const Any& value1, const Any& value2, const Any& value3);
void Foundation_API format(std::string& result, const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4);
void Foundation_API format(std::string& result, const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5);
void Foundation_API format(std::string& result, const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5, const Any& value6);
void Foundation_API format(std::string& result, const std::string& fmt, const std::vector<Any>& values);
/// Supports a variable number of arguments and is used by
/// all other variants of format().
} // namespace Poco
#endif // Foundation_Format_INCLUDED

View File

@@ -0,0 +1,96 @@
//
// Formatter.h
//
// $Id: //poco/1.2/Foundation/include/Poco/Formatter.h#1 $
//
// Library: Foundation
// Package: Logging
// Module: Formatter
//
// Definition of the Formatter 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_Formatter_INCLUDED
#define Foundation_Formatter_INCLUDED
#include "Poco/Foundation.h"
#include "Poco/Configurable.h"
#include "Poco/RefCountedObject.h"
namespace Poco {
class Message;
class Foundation_API Formatter: public Configurable, public RefCountedObject
/// The base class for all Formatter classes.
///
/// A formatter basically takes a Message object
/// and formats it into a string. How the formatting
/// is exactly done is up to the implementation of
/// Formatter. For example, a very simple implementation
/// might simply take the message's Text (see Message::getText()).
/// A useful implementation should at least take the Message's
/// Time, Priority and Text fields and put them into a string.
///
/// The Formatter class supports the Configurable
/// interface, so the behaviour of certain formatters
/// is configurable.
///
/// Trivial implementations of of getProperty() and
/// setProperty() are provided.
///
/// Subclasses must at least provide a format() method.
{
public:
Formatter();
/// Creates the formatter.
virtual ~Formatter();
/// Destroys the formatter.
virtual void format(const Message& msg, std::string& text) = 0;
/// Formats the message and places the result in text.
/// Subclasses must override this method.
void setProperty(const std::string& name, const std::string& value);
/// Throws a PropertyNotSupportedException.
std::string getProperty(const std::string& name) const;
/// Throws a PropertyNotSupportedException.
};
} // namespace Poco
#endif // Foundation_Formatter_INCLUDED

View File

@@ -0,0 +1,116 @@
//
// FormattingChannel.h
//
// $Id: //poco/1.2/Foundation/include/Poco/FormattingChannel.h#1 $
//
// Library: Foundation
// Package: Logging
// Module: Formatter
//
// Definition of the FormattingChannel 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_FormattingChannel_INCLUDED
#define Foundation_FormattingChannel_INCLUDED
#include "Poco/Foundation.h"
#include "Poco/Channel.h"
namespace Poco {
class Formatter;
class Foundation_API FormattingChannel: public Channel
/// The FormattingChannel is a filter channel that routes
/// a Message through a Formatter before passing it on
/// to the destination channel.
{
public:
FormattingChannel();
/// Creates a FormattingChannel.
FormattingChannel(Formatter* pFormatter);
/// Creates a FormattingChannel and attaches a Formatter.
FormattingChannel(Formatter* pFormatter, Channel* pChannel);
/// Creates a FormattingChannel and attaches a Formatter
/// and a Channel.
void setFormatter(Formatter* pFormatter);
/// Sets the Formatter used to format the messages
/// before they are passed on. If null, the message
/// is passed on unmodified.
Formatter* getFormatter() const;
/// Returns the Formatter used to format messages,
/// which may be null.
void setChannel(Channel* pChannel);
/// Sets the destination channel to which the formatted
/// messages are passed on.
Channel* getChannel() const;
/// Returns the channel to which the formatted
/// messages are passed on.
void log(const Message& msg);
/// Formats the given Message using the Formatter and
/// passes the formatted message on to the destination
/// Channel.
void setProperty(const std::string& name, const std::string& value);
/// Sets or changes a configuration property.
///
/// Only the "channel" and "formatter" properties are supported, which allow
/// setting the target channel and formatter, respectively, via the LoggingRegistry.
/// The "channel" and "formatter" properties are set-only.
void open();
/// Opens the attached channel.
void close();
/// Closes the attached channel.
protected:
~FormattingChannel();
private:
Formatter* _pFormatter;
Channel* _pChannel;
};
} // namespace Poco
#endif // Foundation_FormattingChannel_INCLUDED

View File

@@ -0,0 +1,104 @@
//
// Foundation.h
//
// $Id: //poco/1.2/Foundation/include/Poco/Foundation.h#1 $
//
// Library: Foundation
// Package: Core
// Module: Foundation
//
// Basic definitions for the POCO Foundation library.
// This file must be the first file included by every other Foundation
// header file.
//
// 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_Foundation_INCLUDED
#define Foundation_Foundation_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 Foundation_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
// Foundation_API functions as being imported from a DLL, wheras this DLL sees symbols
// defined with this macro as being exported.
//
#if defined(_WIN32) && defined(POCO_DLL)
#if defined(Foundation_EXPORTS)
#define Foundation_API __declspec(dllexport)
#else
#define Foundation_API __declspec(dllimport)
#endif
#endif
#if !defined(Foundation_API)
#define Foundation_API
#endif
//
// Include library configuration
//
#include "Poco/Config.h"
//
// Include platform-specific definitions
//
#if defined(_WIN32)
#include "Poco/Platform_WIN32.h"
#elif defined(__VMS)
#include "Poco/Platform_VMS.h"
#elif defined(POCO_OS_FAMILY_UNIX)
#include "Poco/Platform_POSIX.h"
#endif
//
// Pull in basic definitions
//
#include "Poco/Platform.h"
#include "Poco/Bugcheck.h"
#include "Poco/Types.h"
#include <string>
#endif // Foundation_Foundation_INCLUDED

View File

@@ -0,0 +1,158 @@
//
// Glob.h
//
// $Id: //poco/1.2/Foundation/include/Poco/Glob.h#1 $
//
// Library: Foundation
// Package: Filesystem
// Module: Glob
//
// Definition of the Glob 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_Glob_INCLUDED
#define Foundation_Glob_INCLUDED
#include "Poco/Foundation.h"
#include <set>
namespace Poco {
class Path;
class Foundation_API Glob
/// This class implements glob-style pattern matching
/// as known from Unix shells.
///
/// In the pattern string, '*' matches any sequence of characters,
/// '?' matches any character, [SET] matches any character in the
/// specified set, [!SET] matches any character not in the specified
/// set.
///
/// A set is composed of characters or ranges; a range looks like
/// character hyphen character (as in 0-9 or A-Z).
/// [0-9a-zA-Z_] is the set of characters allowed in C identifiers.
/// Any other character in the pattern must be matched exactly.
///
/// To suppress the special syntactic significance of any of '[]*?!-\',
/// and match the character exactly, precede it with a backslash.
///
/// UTF-8 encoded strings are not supported.
{
public:
enum Options
/// Flags that modify the matching behavior.
{
GLOB_DEFAULT = 0x00, /// default behavior
GLOB_DOT_SPECIAL = 0x01, /// '*' and '?' do not match '.' at beginning of subject
GLOB_DIRS_ONLY = 0x80 /// only glob for directories (for internal use only)
};
Glob(const std::string& pattern, int options = 0);
/// Creates the Glob, using the given pattern. The pattern
/// must not be an empty string.
///
/// If the GLOB_DOT_SPECIAL option is specified, '*' and '?' do
/// not match '.' at the beginning of a matched subject. This is useful for
/// making dot-files invisible in good old Unix-style.
~Glob();
/// Destroys the Glob.
bool match(const std::string& subject);
/// Matches the given subject against the glob pattern.
/// Returns true if the subject matches the pattern, false
/// otherwise.
static void glob(const std::string& pathPattern, std::set<std::string>& files, int options = 0);
/// Creates a set of files that match the given pathPattern.
///
/// The path may be give in either Unix, Windows or VMS syntax and
/// is automatically expanded by calling Path::expand().
///
/// The pattern may contain wildcard expressions even in intermediate
/// directory names (e.g. /usr/include/*/*.h).
///
/// Note that, for obvious reasons, escaping characters in a pattern
/// with a backslash does not work in Windows-style paths.
///
/// Directories that for whatever reason cannot be traversed are
/// ignored.
static void glob(const char* pathPattern, std::set<std::string>& files, int options = 0);
/// Creates a set of files that match the given pathPattern.
///
/// The path may be give in either Unix, Windows or VMS syntax and
/// is automatically expanded by calling Path::expand().
///
/// The pattern may contain wildcard expressions even in intermediate
/// directory names (e.g. /usr/include/*/*.h).
///
/// Note that, for obvious reasons, escaping characters in a pattern
/// with a backslash does not work in Windows-style paths.
///
/// Directories that for whatever reason cannot be traversed are
/// ignored.
static void glob(const Path& pathPattern, std::set<std::string>& files, int options = 0);
/// Creates a set of files that match the given pathPattern.
///
/// The pattern may contain wildcard expressions even in intermediate
/// directory names (e.g. /usr/include/*/*.h).
///
/// Note that, for obvious reasons, escaping characters in a pattern
/// with a backslash does not work in Windows-style paths.
///
/// Directories that for whatever reason cannot be traversed are
/// ignored.
protected:
bool match(std::string::const_iterator& itp, const std::string::const_iterator& endp, std::string::const_iterator& its, const std::string::const_iterator& ends);
bool matchAfterAsterisk(std::string::const_iterator itp, const std::string::const_iterator& endp, std::string::const_iterator its, const std::string::const_iterator& ends);
bool matchSet(std::string::const_iterator& itp, const std::string::const_iterator& endp, char c);
static void collect(const Path& pathPattern, const Path& base, const Path& current, const std::string& pattern, std::set<std::string>& files, int options);
private:
std::string _pattern;
int _options;
Glob();
Glob(const Glob&);
Glob& operator = (const Glob&);
};
} // namespace Poco
#endif // Foundation_Glob_INCLUDED

View File

@@ -0,0 +1,166 @@
//
// HMACEngine.h
//
// $Id: //poco/1.2/Foundation/include/Poco/HMACEngine.h#1 $
//
// Library: Foundation
// Package: Crypt
// Module: HMACEngine
//
// Definition of the HMACEngine 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_HMACEngine_INCLUDED
#define Foundation_HMACEngine_INCLUDED
#include "Poco/Foundation.h"
#include "Poco/DigestEngine.h"
#include <string.h>
namespace Poco {
template <class Engine>
class HMACEngine: public DigestEngine
/// This class implementes the HMAC message
/// authentication code algorithm, as specified
/// in RFC 2104. The underlying DigestEngine
/// (MD5Engine, SHA1Engine, etc.) must be given as
/// template argument.
/// Since the HMACEngine is a DigestEngine, it can
/// be used with the DigestStream class to create
/// a HMAC for a stream.
{
public:
enum
{
BLOCK_SIZE = Engine::BLOCK_SIZE,
DIGEST_SIZE = Engine::DIGEST_SIZE
};
HMACEngine(const std::string& passphrase)
{
init(passphrase.data(), (unsigned) passphrase.length());
}
HMACEngine(const char* passphrase, unsigned length)
{
poco_check_ptr (passphrase);
init(passphrase, length);
}
~HMACEngine()
{
memset(_ipad, 0, BLOCK_SIZE);
memset(_opad, 0, BLOCK_SIZE);
delete [] _ipad;
delete [] _opad;
}
unsigned digestLength() const
{
return DIGEST_SIZE;
}
void reset()
{
_engine.reset();
_engine.update(_ipad, BLOCK_SIZE);
}
const DigestEngine::Digest& digest()
{
const DigestEngine::Digest& d = _engine.digest();
char db[DIGEST_SIZE];
char* pdb = db;
for (DigestEngine::Digest::const_iterator it = d.begin(); it != d.end(); ++it)
*pdb++ = *it;
_engine.reset();
_engine.update(_opad, BLOCK_SIZE);
_engine.update(db, DIGEST_SIZE);
const DigestEngine::Digest& result = _engine.digest();
reset();
return result;
}
protected:
void init(const char* passphrase, unsigned length)
{
_ipad = new char[BLOCK_SIZE];
_opad = new char[BLOCK_SIZE];
memset(_ipad, 0, BLOCK_SIZE);
memset(_opad, 0, BLOCK_SIZE);
if (length > BLOCK_SIZE)
{
_engine.reset();
_engine.update(passphrase, length);
const DigestEngine::Digest& d = _engine.digest();
char* ipad = _ipad;
char* opad = _opad;
int n = BLOCK_SIZE;
for (DigestEngine::Digest::const_iterator it = d.begin(); it != d.end() && n-- > 0; ++it)
{
*ipad++ = *it;
*opad++ = *it;
}
}
else
{
memcpy(_ipad, passphrase, length);
memcpy(_opad, passphrase, length);
}
for (int i = 0; i < BLOCK_SIZE; ++i)
{
_ipad[i] ^= 0x36;
_opad[i] ^= 0x5c;
}
reset();
}
void updateImpl(const void* data, unsigned length)
{
_engine.update(data, length);
}
private:
HMACEngine();
Engine _engine;
char* _ipad;
char* _opad;
};
} // namespace Poco
#endif // Foundation_HMACEngine_INCLUDED

View File

@@ -0,0 +1,82 @@
//
// HashFunction.h
//
// $Id: //poco/1.2/Foundation/include/Poco/HashFunction.h#1 $
//
// Library: Foundation
// Package: Core
// Module: HashFunction
//
// Definition of the HashFunction 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_HashFunction_INCLUDED
#define Foundation_HashFunction_INCLUDED
#include "Poco/Foundation.h"
namespace Poco {
template <class T>
struct HashFunction
/// A generic hash function for numeric values.
{
static UInt32 hash(T key, UInt32 maxValue)
/// Returns the hash value for the given key
{
return key * 0xf4243 % maxValue;
}
};
template <>
struct HashFunction<std::string>
/// A specialization of HashFunction for strings.
{
static UInt32 hash(const std::string& key, UInt32 maxValue)
{
// hash function taken from XML expat
UInt32 h = 0;
for (int i = 0; i < key.length(); ++i)
{
h = h * 0xf4243 ^ key[i];
}
return h % maxValue;
}
};
} // namespace Poco
#endif // Foundation_HashFunctions_INCLUDED

View File

@@ -0,0 +1,147 @@
//
// HashStatistic.h
//
// $Id: //poco/1.2/Foundation/include/Poco/HashStatistic.h#1 $
//
// Library: Foundation
// Package: Core
// Module: HashStatistic
//
// Definition of the HashStatistic 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_HashStatistic_INCLUDED
#define Foundation_HashStatistic_INCLUDED
#include "Poco/Foundation.h"
#include <vector>
namespace Poco {
class Foundation_API HashStatistic
/// HashStatistic class bundles statistical information on the current state of a HashTable
{
public:
HashStatistic(
UInt32 tableSize,
UInt32 numEntries,
UInt32 numZeroEntries,
UInt32 maxEntry,
std::vector<UInt32> details = std::vector<UInt32>());
/// Creates the HashStatistic.
virtual ~HashStatistic();
/// Destroys the HashStatistic.
UInt32 maxPositionsOfTable() const;
/// Returns the maximum number of different hash values possible for the table
UInt32 numberOfEntries() const;
/// Returns the total number of entries currently stored in the HashTable
UInt32 numberOfZeroPositions() const;
/// Returns the number of hash positions that contain no entry.
double avgEntriesPerHash() const;
/// Returns the average number of entries per position in the Hashtable, the higher this value the less efficient
/// performs hashing. If a large value is returned and getNumberOfZeroPositions also returns a large value, this
/// indicates an inefficient hashing function. If the number of zero entries is low, resizing the HashTable, should
/// be enough to improve performance
double avgEntriesPerHashExclZeroEntries() const;
/// Same as getAvgEntriesPerHash but hash values that contain no entry are ignored,
/// getAvgEntriesPerHashExclZeroEntries >= getAvgEntriesPerHash will always be true.
UInt32 maxEntriesPerHash() const;
/// Returns the maximum number of entries per hash value found in the current table.
const std::vector<UInt32> detailedEntriesPerHash() const;
/// Will either be an empty vector or will contain for each possible hash value, the number of entries currently stored
std::string toString() const;
/// Converts the whole data structure into a string.
private:
UInt32 _sizeOfTable;
UInt32 _numberOfEntries;
UInt32 _numZeroEntries;
UInt32 _maxEntriesPerHash;
std::vector<UInt32> _detailedEntriesPerHash;
};
inline UInt32 HashStatistic::maxPositionsOfTable() const
{
return _sizeOfTable;
}
inline UInt32 HashStatistic::numberOfEntries() const
{
return _numberOfEntries;
}
inline UInt32 HashStatistic::numberOfZeroPositions() const
{
return _numZeroEntries;
}
inline double HashStatistic::avgEntriesPerHash() const
{
return ((double) numberOfEntries()) / maxPositionsOfTable();
}
inline double HashStatistic::avgEntriesPerHashExclZeroEntries() const
{
return ((double) numberOfEntries()) / (maxPositionsOfTable() - numberOfZeroPositions());
}
inline UInt32 HashStatistic::maxEntriesPerHash() const
{
return _maxEntriesPerHash;
}
inline const std::vector<UInt32> HashStatistic::detailedEntriesPerHash() const
{
return _detailedEntriesPerHash;
}
} // namespace Poco
#endif // Foundation_HashStatistic_INCLUDED

View File

@@ -0,0 +1,362 @@
//
// HashTable.h
//
// $Id: //poco/1.2/Foundation/include/Poco/HashTable.h#1 $
//
// Library: Foundation
// Package: Core
// Module: HashTable
//
// Definition of the HashTable 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_HashTable_INCLUDED
#define Foundation_HashTable_INCLUDED
#include "Poco/Foundation.h"
#include "Poco/Exception.h"
#include "Poco/HashFunction.h"
#include "Poco/HashStatistic.h"
#include <vector>
#include <map>
#include <stddef.h>
namespace Poco {
template <class Key, class Value, class KeyHashFunction = HashFunction<Key> >
class HashTable
/// A HashTable stores a key value pair that can be looked up via a hashed key.
///
/// Collision handling is done via overflow maps(!). With small hash tables performance of this
/// data struct will be closer to that a map than a hash table, i.e. slower. On the plus side,
/// this class offers remove operations. Also HashTable full errors are not possible. If a fast
/// HashTable implementation is needed and the remove operation is not required, use SimpleHashTable
/// instead.
///
/// This class is NOT thread safe.
{
public:
typedef std::map<Key, Value> HashEntryMap;
typedef HashEntryMap** HashTableVector;
typedef typename HashEntryMap::const_iterator ConstIterator;
typedef typename HashEntryMap::iterator Iterator;
HashTable(UInt32 initialSize = 251):
_entries(0),
_size(0),
_maxCapacity(initialSize)
/// Creates the HashTable.
{
_entries = new HashEntryMap*[initialSize];
memset(_entries, '\0', sizeof(HashEntryMap*)*initialSize);
}
HashTable(const HashTable& ht):
_entries(new HashEntryMap*[ht._maxCapacity]),
_size(ht._size),
_maxCapacity(ht._maxCapacity)
{
for (int i = 0; i < _maxCapacity; ++i)
{
if (ht._entries[i])
_entries[i] = new HashEntryMap(ht._entries[i]->begin(), ht._entries[i]->end());
else
_entries[i] = 0;
}
}
~HashTable()
/// Destroys the HashTable.
{
clear();
}
HashTable& operator = (const HashTable& ht)
{
if (this != &ht)
{
clear();
_maxCapacity = ht._maxCapacity;
poco_assert_dbg (_entries == 0);
_entries = new HashEntryMap*[_maxCapacity];
_size = ht._size;
for (int i = 0; i < _maxCapacity; ++i)
{
if (ht._entries[i])
_entries[i] = new HashEntryMap(ht._entries[i]->begin(), ht._entries[i]->end());
else
_entries[i] = 0;
}
}
return *this;
}
void clear()
{
if (!_entries)
return;
for (int i = 0; i < _maxCapacity; ++i)
{
if (_entries[i])
delete _entries[i];
}
delete[] _entries;
_entries = 0;
_size = 0;
_maxCapacity = 0;
}
UInt32 insert(const Key& key, const Value& value)
/// Returns the hash value of the inserted item.
/// Throws an exception if the entry was already inserted
{
UInt32 hsh = hash(key);
insertRaw(key, hsh, value);
return hsh;
}
void insertRaw(const Key& key, UInt32 hsh, const Value& value)
/// Returns the hash value of the inserted item.
/// Throws an exception if the entry was already inserted
{
if (!_entries[hsh])
_entries[hsh] = new HashEntryMap();
if (!_entries[hsh]->insert(std::make_pair(key, value)).second)
throw InvalidArgumentException("HashTable::insert, key already exists.");
_size++;
}
UInt32 update(const Key& key, const Value& value)
/// Returns the hash value of the inserted item.
/// Replaces an existing entry if it finds one
{
UInt32 hsh = hash(key);
updateRaw(key, hsh, value);
return hsh;
}
void updateRaw(const Key& key, UInt32 hsh, const Value& value)
/// Returns the hash value of the inserted item.
/// Replaces an existing entry if it finds one
{
if (!_entries[hsh])
_entries[hsh] = new HashEntryMap();
std::pair < Iterator, bool > res = _entries[hsh]->insert(make_pair(key, value));
if (res.second == false)
res.first->second = value;
else
_size++;
}
void remove(const Key& key)
{
UInt32 hsh = hash(key);
removeRaw(key, hsh);
}
void removeRaw(const Key& key, UInt32 hsh)
/// Performance version, allows to specify the hash value
{
if (_entries[hsh])
{
_size -= _entries[hsh]->erase(key);
}
}
UInt32 hash(const Key& key) const
{
return KeyHashFunction::hash(key, _maxCapacity);
}
const Value& get(const Key& key) const
/// Throws an exception if the value does not exist
{
UInt32 hsh = hash(key);
return getRaw(key, hsh);
}
const Value& getRaw(const Key& key, UInt32 hsh) const
/// Throws an exception if the value does not exist
{
if (!_entries[hsh])
throw InvalidArgumentException("key not found");
ConstIterator it = _entries[hsh]->find(key);
if (it == _entries[hsh]->end())
throw InvalidArgumentException("key not found");
return it->second;
}
const Key& getKeyRaw(const Key& key, UInt32 hsh)
/// Throws an exception if the key does not exist. returns a reference to the internally
/// stored key. Useful when someone does an insert and wants for performance reason only to store
/// a pointer to the key in another collection
{
if (!_entries[hsh])
throw InvalidArgumentException("key not found");
ConstIterator it = _entries[hsh]->find(key);
if (it == _entries[hsh]->end())
throw InvalidArgumentException("key not found");
return it->first;
}
bool get(const Key& key, Value& v) const
/// Sets v to the found value, returns false if no value was found
{
UInt32 hsh = hash(key);
return getRaw(key, hsh, v);
}
bool getRaw(const Key& key, UInt32 hsh, Value& v) const
/// Sets v to the found value, returns false if no value was found
{
if (!_entries[hsh])
return false;
ConstIterator it = _entries[hsh]->find(key);
if (it == _entries[hsh]->end())
return false;
v = it->second;
return true;
}
bool exists(const Key& key)
{
UInt32 hsh = hash(key);
return existsRaw(key, hsh);
}
bool existsRaw(const Key& key, UInt32 hsh)
{
return _entries[hsh] && (_entries[hsh]->end() != _entries[hsh]->find(key));
}
size_t size() const
/// Returns the number of elements already inserted into the HashTable
{
return _size;
}
UInt32 maxCapacity() const
{
return _maxCapacity;
}
void resize(UInt32 newSize)
/// Resizes the hashtable, rehashes all existing entries. Expensive!
{
if (_maxCapacity != newSize)
{
HashTableVector cpy = _entries;
_entries = 0;
UInt32 oldSize = _maxCapacity;
_maxCapacity = newSize;
_entries = new HashEntryMap*[_maxCapacity];
memset(_entries, '\0', sizeof(HashEntryMap*)*_maxCapacity);
if (_size == 0)
{
// no data was yet inserted
delete[] cpy;
return;
}
_size = 0;
for (int i=0; i < oldSize; ++i)
{
if (cpy[i])
{
ConstIterator it = cpy[i]->begin();
ConstIterator itEnd = cpy[i]->end();
for (; it != itEnd; ++it)
{
insert(it->first, it->second);
}
delete cpy[i];
}
}
delete[] cpy;
}
}
HashStatistic currentState(bool details = false) const
/// Returns the current internal state
{
UInt32 numberOfEntries = (UInt32)_size;
UInt32 numZeroEntries = 0;
UInt32 maxEntriesPerHash = 0;
std::vector<UInt32> detailedEntriesPerHash;
#ifdef DEBUG
UInt32 totalSize = 0;
#endif
for (int i=0; i < _maxCapacity; ++i)
{
if (_entries[i])
{
UInt32 size = (UInt32)_entries[i]->size();
poco_assert_dbg(size != 0);
if (size > maxEntriesPerHash)
maxEntriesPerHash = size;
if (details)
detailedEntriesPerHash.push_back(size);
#ifdef DEBUG
totalSize += size;
#endif
}
else
{
numZeroEntries++;
if (details)
detailedEntriesPerHash.push_back(0);
}
}
#ifdef DEBUG
poco_assert_dbg(totalSize == numberOfEntries);
#endif
return HashStatistic(_maxCapacity, numberOfEntries, numZeroEntries, maxEntriesPerHash, detailedEntriesPerHash);
}
private:
HashTableVector _entries;
size_t _size;
UInt32 _maxCapacity;
};
} // namespace Poco
#endif // Foundation_HashTable_INCLUDED

View File

@@ -0,0 +1,104 @@
//
// HexBinaryDecoder.h
//
// $Id: //poco/1.2/Foundation/include/Poco/HexBinaryDecoder.h#1 $
//
// Library: Foundation
// Package: Streams
// Module: HexBinary
//
// Definition of the HexBinaryDecoder 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_HexBinaryDecoder_INCLUDED
#define Foundation_HexBinaryDecoder_INCLUDED
#include "Poco/Foundation.h"
#include "Poco/UnbufferedStreamBuf.h"
#include <istream>
namespace Poco {
class Foundation_API HexBinaryDecoderBuf: public UnbufferedStreamBuf
/// This streambuf decodes all hexBinary-encoded data read
/// from the istream connected to it.
/// In hexBinary encoding, each binary octet is encoded as a character tuple,
/// consisting of two hexadecimal digits ([0-9a-fA-F]) representing the octet code.
/// See also: XML Schema Part 2: Datatypes (http://www.w3.org/TR/xmlschema-2/),
/// section 3.2.15.
{
public:
HexBinaryDecoderBuf(std::istream& istr);
~HexBinaryDecoderBuf();
private:
int readFromDevice();
int readOne();
std::istream& _istr;
};
class Foundation_API HexBinaryDecoderIOS: public virtual std::ios
/// The base class for HexBinaryDecoder.
///
/// This class is needed to ensure the correct initialization
/// order of the stream buffer and base classes.
{
public:
HexBinaryDecoderIOS(std::istream& istr);
~HexBinaryDecoderIOS();
HexBinaryDecoderBuf* rdbuf();
protected:
HexBinaryDecoderBuf _buf;
};
class Foundation_API HexBinaryDecoder: public HexBinaryDecoderIOS, public std::istream
/// This istream decodes all hexBinary-encoded data read
/// from the istream connected to it.
/// In hexBinary encoding, each binary octet is encoded as a character tuple,
/// consisting of two hexadecimal digits ([0-9a-fA-F]) representing the octet code.
/// See also: XML Schema Part 2: Datatypes (http://www.w3.org/TR/xmlschema-2/),
/// section 3.2.15.
{
public:
HexBinaryDecoder(std::istream& istr);
~HexBinaryDecoder();
};
} // namespace Poco
#endif // Foundation_HexBinaryDecoder_INCLUDED

View File

@@ -0,0 +1,117 @@
//
// HexBinaryEncoder.h
//
// $Id: //poco/1.2/Foundation/include/Poco/HexBinaryEncoder.h#1 $
//
// Library: Foundation
// Package: Streams
// Module: HexBinary
//
// Definition of the HexBinaryEncoder 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_HexBinaryEncoder_INCLUDED
#define Foundation_HexBinaryEncoder_INCLUDED
#include "Poco/Foundation.h"
#include "Poco/UnbufferedStreamBuf.h"
#include <ostream>
namespace Poco {
class Foundation_API HexBinaryEncoderBuf: public UnbufferedStreamBuf
/// This streambuf encodes all data written
/// to it in hexBinary encoding and forwards it to a connected
/// ostream.
/// In hexBinary encoding, each binary octet is encoded as a character tuple,
/// consisting of two hexadecimal digits ([0-9a-fA-F]) representing the octet code.
/// See also: XML Schema Part 2: Datatypes (http://www.w3.org/TR/xmlschema-2/),
/// section 3.2.15.
{
public:
HexBinaryEncoderBuf(std::ostream& ostr);
~HexBinaryEncoderBuf();
int close();
void setLineLength(int lineLength);
int getLineLength() const;
void setUppercase(bool flag = true);
private:
int writeToDevice(char c);
int _pos;
int _lineLength;
int _uppercase;
std::ostream& _ostr;
};
class Foundation_API HexBinaryEncoderIOS: public virtual std::ios
/// The base class for HexBinaryEncoder.
///
/// This class is needed to ensure the correct initialization
/// order of the stream buffer and base classes.
{
public:
HexBinaryEncoderIOS(std::ostream& ostr);
~HexBinaryEncoderIOS();
int close();
HexBinaryEncoderBuf* rdbuf();
protected:
HexBinaryEncoderBuf _buf;
};
class Foundation_API HexBinaryEncoder: public HexBinaryEncoderIOS, public std::ostream
/// This ostream encodes all data
/// written to it in BinHex encoding and forwards it to
/// a connected ostream.
/// Always call close() when done
/// writing data, to ensure proper
/// completion of the encoding operation.
/// In hexBinary encoding, each binary octet is encoded as a character tuple,
/// consisting of two hexadecimal digits ([0-9a-fA-F]) representing the octet code.
/// See also: XML Schema Part 2: Datatypes (http://www.w3.org/TR/xmlschema-2/),
/// section 3.2.15.
{
public:
HexBinaryEncoder(std::ostream& ostr);
~HexBinaryEncoder();
};
} // namespace Poco
#endif // Foundation_HexBinaryEncoder_INCLUDED

View File

@@ -0,0 +1,139 @@
//
// InflatingStream.h
//
// $Id: //poco/1.2/Foundation/include/Poco/InflatingStream.h#1 $
//
// Library: Foundation
// Package: Streams
// Module: ZLibStream
//
// Definition of the InflatingInputStream and InflatingOutputStream 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_InflatingStream_INCLUDED
#define Foundation_InflatingStream_INCLUDED
#include "Poco/Foundation.h"
#include "Poco/BufferedStreamBuf.h"
#include <istream>
#include <ostream>
#include "Poco/zlib.h"
namespace Poco {
class Foundation_API InflatingStreamBuf: public BufferedStreamBuf
/// This is the streambuf class used by InflatingInputStream and InflatingOutputStream.
/// 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 decompression.
{
public:
enum StreamType
{
STREAM_ZLIB,
STREAM_GZIP
};
InflatingStreamBuf(std::istream& istr, StreamType type);
InflatingStreamBuf(std::ostream& ostr, StreamType type);
~InflatingStreamBuf();
int close();
protected:
int readFromDevice(char* buffer, std::streamsize length);
int writeToDevice(const char* buffer, std::streamsize length);
private:
enum
{
STREAM_BUFFER_SIZE = 1024,
INFLATE_BUFFER_SIZE = 32768
};
std::istream* _pIstr;
std::ostream* _pOstr;
char* _buffer;
z_stream _zstr;
bool _eof;
};
class Foundation_API InflatingIOS: public virtual std::ios
/// The base class for InflatingOutputStream and InflatingInputStream.
///
/// This class is needed to ensure the correct initialization
/// order of the stream buffer and base classes.
{
public:
InflatingIOS(std::ostream& ostr, InflatingStreamBuf::StreamType type = InflatingStreamBuf::STREAM_ZLIB);
InflatingIOS(std::istream& istr, InflatingStreamBuf::StreamType type = InflatingStreamBuf::STREAM_ZLIB);
~InflatingIOS();
InflatingStreamBuf* rdbuf();
protected:
InflatingStreamBuf _buf;
};
class Foundation_API InflatingOutputStream: public InflatingIOS, public std::ostream
/// This stream decompresses all data passing through it
/// using zlib's inflate algorithm.
/// After all data has been written to the stream, close()
/// must be called to ensure completion of decompression.
{
public:
InflatingOutputStream(std::ostream& ostr, InflatingStreamBuf::StreamType type = InflatingStreamBuf::STREAM_ZLIB);
~InflatingOutputStream();
int close();
};
class Foundation_API InflatingInputStream: public InflatingIOS, public std::istream
/// This stream decompresses all data passing through it
/// using zlib's inflate algorithm.
/// Example:
/// std::ifstream istr("data.gz", std::ios::binary);
/// InflatingInputStream inflater(istr, InflatingStreamBuf::STREAM_GZIP);
/// std::string data;
/// istr >> data;
{
public:
InflatingInputStream(std::istream& istr, InflatingStreamBuf::StreamType type = InflatingStreamBuf::STREAM_ZLIB);
~InflatingInputStream();
};
} // namespace Poco
#endif // Foundation_InflatingStream_INCLUDED

View File

@@ -0,0 +1,104 @@
//
// Instantiator.h
//
// $Id: //poco/1.2/Foundation/include/Poco/Instantiator.h#1 $
//
// Library: Foundation
// Package: Core
// Module: Instantiator
//
// Definition of the Instantiator 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_Instantiator_INCLUDED
#define Foundation_Instantiator_INCLUDED
#include "Poco/Foundation.h"
namespace Poco {
template <class Base>
class AbstractInstantiator
/// The common base class for all Instantiator instantiations.
/// Used by DynamicFactory.
{
public:
AbstractInstantiator()
/// Creates the AbstractInstantiator.
{
}
virtual ~AbstractInstantiator()
/// Destroys the AbstractInstantiator.
{
}
virtual Base* createInstance() const = 0;
/// Creates an instance of a concrete subclass of Base.
private:
AbstractInstantiator(const AbstractInstantiator&);
AbstractInstantiator& operator = (const AbstractInstantiator&);
};
template <class C, class Base>
class Instantiator: public AbstractInstantiator<Base>
/// A template class for the easy instantiation of
/// instantiators.
///
/// For the Instantiator to work, the class of which
/// instances are to be instantiated must have a no-argument
/// constructor.
{
public:
Instantiator()
/// Creates the Instantiator.
{
}
virtual ~Instantiator()
/// Destroys the Instantiator.
{
}
Base* createInstance() const
{
return new C;
}
};
} // namespace Poco
#endif // Foundation_Instantiator_INCLUDED

View File

@@ -0,0 +1,95 @@
//
// KeyValueArgs.h
//
// $Id: //poco/1.2/Foundation/include/Poco/KeyValueArgs.h#1 $
//
// Library: Foundation
// Package: Cache
// Module: KeyValueArgs
//
// Definition of the KeyValueArgs 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_KeyValueArgs_INCLUDED
#define Foundation_KeyValueArgs_INCLUDED
#include "Poco/Foundation.h"
namespace Poco {
template <class TKey, class TValue>
class KeyValueArgs
/// Simply event arguments class to transfer a key and a value via an event call.
/// Note that key and value are *NOT* copied, only references to them are stored.
{
public:
KeyValueArgs(const TKey& aKey, const TValue& aVal):
_key(aKey),
_value(aVal)
{
}
KeyValueArgs(const KeyValueArgs& args):
_key(args._key),
_value(args._value)
{
}
~KeyValueArgs()
{
}
const TKey& key() const
/// Returns a reference to the key,
{
return _key;
}
const TValue& value() const
/// Returns a Reference to the value.
{
return _value;
}
protected:
const TKey& _key;
const TValue& _value;
private:
KeyValueArgs& operator = (const KeyValueArgs& args);
};
} // namespace Poco
#endif

View File

@@ -0,0 +1,74 @@
//
// LRUCache.h
//
// $Id: //poco/1.2/Foundation/include/Poco/LRUCache.h#1 $
//
// Library: Foundation
// Package: Cache
// Module: LRUCache
//
// Definition of the LRUCache 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_LRUCache_INCLUDED
#define Foundation_LRUCache_INCLUDED
#include "Poco/AbstractCache.h"
#include "Poco/LRUStrategy.h"
namespace Poco {
template <class TKey, class TValue>
class LRUCache: public AbstractCache<TKey, TValue, LRUStrategy<TKey, TValue> >
/// An LRUCache is the interface of all caches.
{
public:
LRUCache(long size = 1024):
AbstractCache<TKey, TValue, LRUStrategy<TKey, TValue> >(LRUStrategy<TKey, TValue>(size))
{
}
virtual ~LRUCache()
{
}
private:
LRUCache(const LRUCache& aCache);
LRUCache& operator = (const LRUCache& aCache);
};
} // namespace Poco
#endif

View File

@@ -0,0 +1,161 @@
//
// LRUStrategy.h
//
// $Id: //poco/1.2/Foundation/include/Poco/LRUStrategy.h#1 $
//
// Library: Foundation
// Package: Cache
// Module: LRUStrategy
//
// Definition of the LRUStrategy 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_LRUStrategy_INCLUDED
#define Foundation_LRUStrategy_INCLUDED
#include "Poco/KeyValueArgs.h"
#include "Poco/ValidArgs.h"
#include "Poco/AbstractStrategy.h"
#include "Poco/EventArgs.h"
#include "Poco/Exception.h"
#include <list>
#include <map>
namespace Poco {
template <class TKey, class TValue>
class LRUStrategy: public AbstractStrategy<TKey, TValue>
/// An LRUStrategy implements least recently used cache replacement.
{
public:
typedef std::list<TKey> Keys;
typedef typename Keys::iterator Iterator;
typedef typename Keys::const_iterator ConstIterator;
typedef std::map<TKey, Iterator> KeyIndex;
typedef typename KeyIndex::iterator IndexIterator;
typedef typename KeyIndex::const_iterator ConstIndexIterator;
public:
LRUStrategy(size_t size):
_size(size)
{
if (_size < 1) throw InvalidArgumentException("size must be > 0");
}
virtual ~LRUStrategy()
{
}
void onAdd(const void*, const KeyValueArgs <TKey, TValue>& args)
{
_keys.push_front(args.key());
std::pair < IndexIterator, bool > stat = _keyIndex.insert(make_pair(args.key(), _keys.begin()));
if (!stat.second)
{
stat.first->second = _keys.begin();
}
}
void onRemove(const void*, const TKey& key)
{
IndexIterator it = _keyIndex.find(key);
if (it != _keyIndex.end())
{
_keys.erase(it->second);
_keyIndex.erase(it);
}
}
void onGet(const void*, const TKey& key)
{
// LRU: in case of an hit, move to begin
IndexIterator it = _keyIndex.find(key);
if (it != _keyIndex.end())
{
_keys.splice(_keys.begin(), _keys, it->second); //_keys.erase(it->second)+_keys.push_front(key);
it->second = _keys.begin();
}
}
void onClear(const void*, const EventArgs& args)
{
_keys.clear();
_keyIndex.clear();
}
void onIsValid(const void*, ValidArgs<TKey>& args)
{
if (_keyIndex.find(args.key()) == _keyIndex.end())
{
args.invalidate();
}
}
void onReplace(const void*, std::set<TKey>& elemsToRemove)
{
// Note: replace only informs the cache which elements
// it would like to remove!
// it does not remove them on its own!
size_t curSize = _keyIndex.size();
if (curSize < _size)
{
return;
}
size_t diff = curSize - _size;
Iterator it = --_keys.end (); //--keys can never be invoked on an empty list due to the minSize==1 requirement of LRU
size_t i = 0;
while (i++ < diff)
{
elemsToRemove.insert(*it);
if (it != _keys.begin())
{
--it;
}
}
}
protected:
size_t _size; /// Number of keys the cache can store.
Keys _keys;
KeyIndex _keyIndex; /// For faster access to _keys
};
} // namespace Poco
#endif

View File

@@ -0,0 +1,68 @@
//
// Latin1Encoding.h
//
// $Id: //poco/1.2/Foundation/include/Poco/Latin1Encoding.h#1 $
//
// Library: Foundation
// Package: Text
// Module: Latin1Encoding
//
// Definition of the Latin1Encoding 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_Latin1Encoding_INCLUDED
#define Foundation_Latin1Encoding_INCLUDED
#include "Poco/Foundation.h"
#include "Poco/TextEncoding.h"
namespace Poco {
class Foundation_API Latin1Encoding: public TextEncoding
/// ISO Latin-1 (8859-1) text encoding.
{
public:
Latin1Encoding();
~Latin1Encoding();
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;
};
} // namespace Poco
#endif // Foundation_Latin1Encoding_INCLUDED

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