diff options
author | orivej <orivej@yandex-team.ru> | 2022-02-10 16:45:01 +0300 |
---|---|---|
committer | Daniil Cherednik <dcherednik@yandex-team.ru> | 2022-02-10 16:45:01 +0300 |
commit | 2d37894b1b037cf24231090eda8589bbb44fb6fc (patch) | |
tree | be835aa92c6248212e705f25388ebafcf84bc7a1 /contrib/libs/poco/Util | |
parent | 718c552901d703c502ccbefdfc3c9028d608b947 (diff) | |
download | ydb-2d37894b1b037cf24231090eda8589bbb44fb6fc.tar.gz |
Restoring authorship annotation for <orivej@yandex-team.ru>. Commit 2 of 2.
Diffstat (limited to 'contrib/libs/poco/Util')
61 files changed, 11620 insertions, 11620 deletions
diff --git a/contrib/libs/poco/Util/include/Poco/Util/AbstractConfiguration.h b/contrib/libs/poco/Util/include/Poco/Util/AbstractConfiguration.h index 5965747a71..277c6d7296 100644 --- a/contrib/libs/poco/Util/include/Poco/Util/AbstractConfiguration.h +++ b/contrib/libs/poco/Util/include/Poco/Util/AbstractConfiguration.h @@ -1,381 +1,381 @@ -// -// AbstractConfiguration.h -// -// Library: Util -// Package: Configuration -// Module: AbstractConfiguration -// -// Definition of the AbstractConfiguration class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// SPDX-License-Identifier: BSL-1.0 -// - - -#ifndef Util_AbstractConfiguration_INCLUDED -#define Util_AbstractConfiguration_INCLUDED - - -#include "Poco/Util/Util.h" -#include "Poco/Mutex.h" -#include "Poco/RefCountedObject.h" -#include "Poco/BasicEvent.h" -#include <vector> -#include <utility> - - -namespace Poco { -namespace Util { - - -class Util_API AbstractConfiguration: public Poco::RefCountedObject - /// AbstractConfiguration is an abstract base class for different - /// kinds of configuration data, such as INI files, property files, - /// XML configuration files or the Windows Registry. - /// - /// Configuration property keys have a hierarchical format, consisting - /// of names separated by periods. The exact interpretation of key names - /// is up to the actual subclass implementation of AbstractConfiguration. - /// Keys are case sensitive. - /// - /// All public methods are synchronized, so the class is safe for multithreaded use. - /// AbstractConfiguration implements reference counting based garbage collection. - /// - /// Subclasses must override the getRaw(), setRaw() and enumerate() methods. -{ -public: - typedef std::vector<std::string> Keys; - - class KeyValue - /// A key-value pair, used as event argument. - { - public: - KeyValue(const std::string& key, std::string& value): - _key(key), - _value(value) - { - } - - const std::string& key() const - { - return _key; - } - - const std::string& value() const - { - return _value; - } - - std::string& value() - { - return _value; - } - - private: - const std::string& _key; - std::string& _value; - }; - - Poco::BasicEvent<KeyValue> propertyChanging; - /// Fired before a property value is changed or - /// a new property is created. - /// - /// Can be used to check or fix a property value, - /// or to cancel the change by throwing an exception. - /// - /// The event delegate can use one of the get...() functions - /// to obtain the current property value. - - Poco::BasicEvent<const KeyValue> propertyChanged; - /// Fired after a property value has been changed - /// or a property has been created. - - Poco::BasicEvent<const std::string> propertyRemoving; - /// Fired before a property is removed by a - /// call to remove(). - /// - /// Note: This will even be fired if the key - /// does not exist and the remove operation will - /// fail with an exception. - - Poco::BasicEvent<const std::string> propertyRemoved; - /// Fired after a property has been removed by - /// a call to remove(). - - AbstractConfiguration(); - /// Creates the AbstractConfiguration. - - bool hasProperty(const std::string& key) const; - /// Returns true iff the property with the given key exists. - - bool hasOption(const std::string& key) const; - /// Returns true iff the property with the given key exists. - /// - /// Same as hasProperty(). - - bool has(const std::string& key) const; - /// Returns true iff the property with the given key exists. - /// - /// Same as hasProperty(). - - std::string getString(const std::string& key) const; - /// Returns the string value of the property with the given name. - /// Throws a NotFoundException if the key does not exist. - /// If the value contains references to other properties (${<property>}), these - /// are expanded. - - std::string getString(const std::string& key, const std::string& defaultValue) const; - /// If a property with the given key exists, returns the property's string value, - /// otherwise returns the given default value. - /// If the value contains references to other properties (${<property>}), these - /// are expanded. - - std::string getRawString(const std::string& key) const; - /// Returns the raw string value of the property with the given name. - /// Throws a NotFoundException if the key does not exist. - /// References to other properties are not expanded. - - std::string getRawString(const std::string& key, const std::string& defaultValue) const; - /// If a property with the given key exists, returns the property's raw string value, - /// otherwise returns the given default value. - /// References to other properties are not expanded. - - int getInt(const std::string& key) const; - /// Returns the int value of the property with the given name. - /// Throws a NotFoundException if the key does not exist. - /// Throws a SyntaxException if the property can not be converted - /// to an int. - /// Numbers starting with 0x are treated as hexadecimal. - /// If the value contains references to other properties (${<property>}), these - /// are expanded. - - unsigned int getUInt(const std::string& key) const; - /// Returns the unsigned int value of the property with the given name. - /// Throws a NotFoundException if the key does not exist. - /// Throws a SyntaxException if the property can not be converted - /// to an unsigned int. - /// Numbers starting with 0x are treated as hexadecimal. - /// If the value contains references to other properties (${<property>}), these - /// are expanded. - - int getInt(const std::string& key, int defaultValue) const; - /// If a property with the given key exists, returns the property's int value, - /// otherwise returns the given default value. - /// Throws a SyntaxException if the property can not be converted - /// to an int. - /// Numbers starting with 0x are treated as hexadecimal. - /// If the value contains references to other properties (${<property>}), these - /// are expanded. - - unsigned int getUInt(const std::string& key, unsigned int defaultValue) const; - /// If a property with the given key exists, returns the property's unsigned int - /// value, otherwise returns the given default value. - /// Throws a SyntaxException if the property can not be converted - /// to an unsigned int. - /// Numbers starting with 0x are treated as hexadecimal. - /// If the value contains references to other properties (${<property>}), these - /// are expanded. - -#if defined(POCO_HAVE_INT64) - - Int64 getInt64(const std::string& key) const; - /// Returns the Int64 value of the property with the given name. - /// Throws a NotFoundException if the key does not exist. - /// Throws a SyntaxException if the property can not be converted - /// to an Int64. - /// Numbers starting with 0x are treated as hexadecimal. - /// If the value contains references to other properties (${<property>}), these - /// are expanded. - - UInt64 getUInt64(const std::string& key) const; - /// Returns the UInt64 value of the property with the given name. - /// Throws a NotFoundException if the key does not exist. - /// Throws a SyntaxException if the property can not be converted - /// to an UInt64. - /// Numbers starting with 0x are treated as hexadecimal. - /// If the value contains references to other properties (${<property>}), these - /// are expanded. - - Int64 getInt64(const std::string& key, Int64 defaultValue) const; - /// If a property with the given key exists, returns the property's Int64 value, - /// otherwise returns the given default value. - /// Throws a SyntaxException if the property can not be converted - /// to an Int64. - /// Numbers starting with 0x are treated as hexadecimal. - /// If the value contains references to other properties (${<property>}), these - /// are expanded. - - UInt64 getUInt64(const std::string& key, UInt64 defaultValue) const; - /// If a property with the given key exists, returns the property's UInt64 - /// value, otherwise returns the given default value. - /// Throws a SyntaxException if the property can not be converted - /// to an UInt64. - /// Numbers starting with 0x are treated as hexadecimal. - /// If the value contains references to other properties (${<property>}), these - /// are expanded. - -#endif // defined(POCO_HAVE_INT64) - - double getDouble(const std::string& key) const; - /// Returns the double value of the property with the given name. - /// Throws a NotFoundException if the key does not exist. - /// Throws a SyntaxException if the property can not be converted - /// to a double. - /// If the value contains references to other properties (${<property>}), these - /// are expanded. - - double getDouble(const std::string& key, double defaultValue) const; - /// If a property with the given key exists, returns the property's double value, - /// otherwise returns the given default value. - /// Throws a SyntaxException if the property can not be converted - /// to an double. - /// If the value contains references to other properties (${<property>}), these - /// are expanded. - - bool getBool(const std::string& key) const; - /// Returns the boolean value of the property with the given name. - /// Throws a NotFoundException if the key does not exist. - /// Throws a SyntaxException if the property can not be converted - /// to a boolean. - /// If the value contains references to other properties (${<property>}), these - /// are expanded. - - bool getBool(const std::string& key, bool defaultValue) const; - /// If a property with the given key exists, returns the property's boolean value, - /// otherwise returns the given default value. - /// Throws a SyntaxException if the property can not be converted - /// to a boolean. - /// The following string values can be converted into a boolean: - /// - numerical values: non zero becomes true, zero becomes false - /// - strings: true, yes, on become true, false, no, off become false - /// Case does not matter. - /// If the value contains references to other properties (${<property>}), these - /// are expanded. - - virtual void setString(const std::string& key, const std::string& value); - /// Sets the property with the given key to the given value. - /// An already existing value for the key is overwritten. - - virtual void setInt(const std::string& key, int value); - /// Sets the property with the given key to the given value. - /// An already existing value for the key is overwritten. - - virtual void setUInt(const std::string& key, unsigned int value); - /// Sets the property with the given key to the given value. - /// An already existing value for the key is overwritten. - -#if defined(POCO_HAVE_INT64) - - virtual void setInt64(const std::string& key, Int64 value); - /// Sets the property with the given key to the given value. - /// An already existing value for the key is overwritten. - - virtual void setUInt64(const std::string& key, UInt64 value); - /// Sets the property with the given key to the given value. - /// An already existing value for the key is overwritten. - -#endif // defined(POCO_HAVE_INT64) - - virtual void setDouble(const std::string& key, double value); - /// Sets the property with the given key to the given value. - /// An already existing value for the key is overwritten. - - virtual void setBool(const std::string& key, bool value); - /// Sets the property with the given key to the given value. - /// An already existing value for the key is overwritten. - - void keys(Keys& range) const; - /// Returns in range the names of all keys at root level. - - void keys(const std::string& key, Keys& range) const; - /// Returns in range the names of all subkeys under the given key. - /// If an empty key is passed, all root level keys are returned. - - const AbstractConfiguration* createView(const std::string& prefix) const; - /// Creates a non-mutable view (see ConfigurationView) into the configuration. - - AbstractConfiguration* createView(const std::string& prefix); - /// Creates a view (see ConfigurationView) into the configuration. - - std::string expand(const std::string& value) const; - /// Replaces all occurrences of ${<property>} in value with the - /// value of the <property>. If <property> does not exist, - /// nothing is changed. - /// - /// If a circular property reference is detected, a - /// CircularReferenceException will be thrown. - - void remove(const std::string& key); - /// Removes the property with the given key. - /// - /// Does nothing if the key does not exist. - - void enableEvents(bool enable = true); - /// Enables (or disables) events. - - bool eventsEnabled() const; - /// Returns true iff events are enabled. - -protected: - virtual bool getRaw(const std::string& key, std::string& value) const = 0; - /// If the property with the given key exists, stores the property's value - /// in value and returns true. Otherwise, returns false. - /// - /// Must be overridden by subclasses. - - virtual void setRaw(const std::string& key, const std::string& value) = 0; - /// Sets the property with the given key to the given value. - /// An already existing value for the key is overwritten. - /// - /// Must be overridden by subclasses. - - virtual void enumerate(const std::string& key, Keys& range) const = 0; - /// Returns in range the names of all subkeys under the given key. - /// If an empty key is passed, all root level keys are returned. - - virtual void removeRaw(const std::string& key); - /// Removes the property with the given key. - /// - /// Does nothing if the key does not exist. - /// - /// Should be overridden by subclasses; the default - /// implementation throws a Poco::NotImplementedException. - - static int parseInt(const std::string& value); - static unsigned parseUInt(const std::string& value); - -#if defined(POCO_HAVE_INT64) - - static Int64 parseInt64(const std::string& value); - static UInt64 parseUInt64(const std::string& value); - -#endif // defined(POCO_HAVE_INT64) - - static bool parseBool(const std::string& value); - void setRawWithEvent(const std::string& key, std::string value); - - virtual ~AbstractConfiguration(); - -private: - std::string internalExpand(const std::string& value) const; - std::string uncheckedExpand(const std::string& value) const; - - AbstractConfiguration(const AbstractConfiguration&); - AbstractConfiguration& operator = (const AbstractConfiguration&); - - mutable int _depth; - bool _eventsEnabled; - mutable Poco::Mutex _mutex; - - friend class LayeredConfiguration; - friend class ConfigurationView; - friend class ConfigurationMapper; -}; - - -} } // namespace Poco::Util - - -#endif // Util_AbstractConfiguration_INCLUDED +// +// AbstractConfiguration.h +// +// Library: Util +// Package: Configuration +// Module: AbstractConfiguration +// +// Definition of the AbstractConfiguration class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Util_AbstractConfiguration_INCLUDED +#define Util_AbstractConfiguration_INCLUDED + + +#include "Poco/Util/Util.h" +#include "Poco/Mutex.h" +#include "Poco/RefCountedObject.h" +#include "Poco/BasicEvent.h" +#include <vector> +#include <utility> + + +namespace Poco { +namespace Util { + + +class Util_API AbstractConfiguration: public Poco::RefCountedObject + /// AbstractConfiguration is an abstract base class for different + /// kinds of configuration data, such as INI files, property files, + /// XML configuration files or the Windows Registry. + /// + /// Configuration property keys have a hierarchical format, consisting + /// of names separated by periods. The exact interpretation of key names + /// is up to the actual subclass implementation of AbstractConfiguration. + /// Keys are case sensitive. + /// + /// All public methods are synchronized, so the class is safe for multithreaded use. + /// AbstractConfiguration implements reference counting based garbage collection. + /// + /// Subclasses must override the getRaw(), setRaw() and enumerate() methods. +{ +public: + typedef std::vector<std::string> Keys; + + class KeyValue + /// A key-value pair, used as event argument. + { + public: + KeyValue(const std::string& key, std::string& value): + _key(key), + _value(value) + { + } + + const std::string& key() const + { + return _key; + } + + const std::string& value() const + { + return _value; + } + + std::string& value() + { + return _value; + } + + private: + const std::string& _key; + std::string& _value; + }; + + Poco::BasicEvent<KeyValue> propertyChanging; + /// Fired before a property value is changed or + /// a new property is created. + /// + /// Can be used to check or fix a property value, + /// or to cancel the change by throwing an exception. + /// + /// The event delegate can use one of the get...() functions + /// to obtain the current property value. + + Poco::BasicEvent<const KeyValue> propertyChanged; + /// Fired after a property value has been changed + /// or a property has been created. + + Poco::BasicEvent<const std::string> propertyRemoving; + /// Fired before a property is removed by a + /// call to remove(). + /// + /// Note: This will even be fired if the key + /// does not exist and the remove operation will + /// fail with an exception. + + Poco::BasicEvent<const std::string> propertyRemoved; + /// Fired after a property has been removed by + /// a call to remove(). + + AbstractConfiguration(); + /// Creates the AbstractConfiguration. + + bool hasProperty(const std::string& key) const; + /// Returns true iff the property with the given key exists. + + bool hasOption(const std::string& key) const; + /// Returns true iff the property with the given key exists. + /// + /// Same as hasProperty(). + + bool has(const std::string& key) const; + /// Returns true iff the property with the given key exists. + /// + /// Same as hasProperty(). + + std::string getString(const std::string& key) const; + /// Returns the string value of the property with the given name. + /// Throws a NotFoundException if the key does not exist. + /// If the value contains references to other properties (${<property>}), these + /// are expanded. + + std::string getString(const std::string& key, const std::string& defaultValue) const; + /// If a property with the given key exists, returns the property's string value, + /// otherwise returns the given default value. + /// If the value contains references to other properties (${<property>}), these + /// are expanded. + + std::string getRawString(const std::string& key) const; + /// Returns the raw string value of the property with the given name. + /// Throws a NotFoundException if the key does not exist. + /// References to other properties are not expanded. + + std::string getRawString(const std::string& key, const std::string& defaultValue) const; + /// If a property with the given key exists, returns the property's raw string value, + /// otherwise returns the given default value. + /// References to other properties are not expanded. + + int getInt(const std::string& key) const; + /// Returns the int value of the property with the given name. + /// Throws a NotFoundException if the key does not exist. + /// Throws a SyntaxException if the property can not be converted + /// to an int. + /// Numbers starting with 0x are treated as hexadecimal. + /// If the value contains references to other properties (${<property>}), these + /// are expanded. + + unsigned int getUInt(const std::string& key) const; + /// Returns the unsigned int value of the property with the given name. + /// Throws a NotFoundException if the key does not exist. + /// Throws a SyntaxException if the property can not be converted + /// to an unsigned int. + /// Numbers starting with 0x are treated as hexadecimal. + /// If the value contains references to other properties (${<property>}), these + /// are expanded. + + int getInt(const std::string& key, int defaultValue) const; + /// If a property with the given key exists, returns the property's int value, + /// otherwise returns the given default value. + /// Throws a SyntaxException if the property can not be converted + /// to an int. + /// Numbers starting with 0x are treated as hexadecimal. + /// If the value contains references to other properties (${<property>}), these + /// are expanded. + + unsigned int getUInt(const std::string& key, unsigned int defaultValue) const; + /// If a property with the given key exists, returns the property's unsigned int + /// value, otherwise returns the given default value. + /// Throws a SyntaxException if the property can not be converted + /// to an unsigned int. + /// Numbers starting with 0x are treated as hexadecimal. + /// If the value contains references to other properties (${<property>}), these + /// are expanded. + +#if defined(POCO_HAVE_INT64) + + Int64 getInt64(const std::string& key) const; + /// Returns the Int64 value of the property with the given name. + /// Throws a NotFoundException if the key does not exist. + /// Throws a SyntaxException if the property can not be converted + /// to an Int64. + /// Numbers starting with 0x are treated as hexadecimal. + /// If the value contains references to other properties (${<property>}), these + /// are expanded. + + UInt64 getUInt64(const std::string& key) const; + /// Returns the UInt64 value of the property with the given name. + /// Throws a NotFoundException if the key does not exist. + /// Throws a SyntaxException if the property can not be converted + /// to an UInt64. + /// Numbers starting with 0x are treated as hexadecimal. + /// If the value contains references to other properties (${<property>}), these + /// are expanded. + + Int64 getInt64(const std::string& key, Int64 defaultValue) const; + /// If a property with the given key exists, returns the property's Int64 value, + /// otherwise returns the given default value. + /// Throws a SyntaxException if the property can not be converted + /// to an Int64. + /// Numbers starting with 0x are treated as hexadecimal. + /// If the value contains references to other properties (${<property>}), these + /// are expanded. + + UInt64 getUInt64(const std::string& key, UInt64 defaultValue) const; + /// If a property with the given key exists, returns the property's UInt64 + /// value, otherwise returns the given default value. + /// Throws a SyntaxException if the property can not be converted + /// to an UInt64. + /// Numbers starting with 0x are treated as hexadecimal. + /// If the value contains references to other properties (${<property>}), these + /// are expanded. + +#endif // defined(POCO_HAVE_INT64) + + double getDouble(const std::string& key) const; + /// Returns the double value of the property with the given name. + /// Throws a NotFoundException if the key does not exist. + /// Throws a SyntaxException if the property can not be converted + /// to a double. + /// If the value contains references to other properties (${<property>}), these + /// are expanded. + + double getDouble(const std::string& key, double defaultValue) const; + /// If a property with the given key exists, returns the property's double value, + /// otherwise returns the given default value. + /// Throws a SyntaxException if the property can not be converted + /// to an double. + /// If the value contains references to other properties (${<property>}), these + /// are expanded. + + bool getBool(const std::string& key) const; + /// Returns the boolean value of the property with the given name. + /// Throws a NotFoundException if the key does not exist. + /// Throws a SyntaxException if the property can not be converted + /// to a boolean. + /// If the value contains references to other properties (${<property>}), these + /// are expanded. + + bool getBool(const std::string& key, bool defaultValue) const; + /// If a property with the given key exists, returns the property's boolean value, + /// otherwise returns the given default value. + /// Throws a SyntaxException if the property can not be converted + /// to a boolean. + /// The following string values can be converted into a boolean: + /// - numerical values: non zero becomes true, zero becomes false + /// - strings: true, yes, on become true, false, no, off become false + /// Case does not matter. + /// If the value contains references to other properties (${<property>}), these + /// are expanded. + + virtual void setString(const std::string& key, const std::string& value); + /// Sets the property with the given key to the given value. + /// An already existing value for the key is overwritten. + + virtual void setInt(const std::string& key, int value); + /// Sets the property with the given key to the given value. + /// An already existing value for the key is overwritten. + + virtual void setUInt(const std::string& key, unsigned int value); + /// Sets the property with the given key to the given value. + /// An already existing value for the key is overwritten. + +#if defined(POCO_HAVE_INT64) + + virtual void setInt64(const std::string& key, Int64 value); + /// Sets the property with the given key to the given value. + /// An already existing value for the key is overwritten. + + virtual void setUInt64(const std::string& key, UInt64 value); + /// Sets the property with the given key to the given value. + /// An already existing value for the key is overwritten. + +#endif // defined(POCO_HAVE_INT64) + + virtual void setDouble(const std::string& key, double value); + /// Sets the property with the given key to the given value. + /// An already existing value for the key is overwritten. + + virtual void setBool(const std::string& key, bool value); + /// Sets the property with the given key to the given value. + /// An already existing value for the key is overwritten. + + void keys(Keys& range) const; + /// Returns in range the names of all keys at root level. + + void keys(const std::string& key, Keys& range) const; + /// Returns in range the names of all subkeys under the given key. + /// If an empty key is passed, all root level keys are returned. + + const AbstractConfiguration* createView(const std::string& prefix) const; + /// Creates a non-mutable view (see ConfigurationView) into the configuration. + + AbstractConfiguration* createView(const std::string& prefix); + /// Creates a view (see ConfigurationView) into the configuration. + + std::string expand(const std::string& value) const; + /// Replaces all occurrences of ${<property>} in value with the + /// value of the <property>. If <property> does not exist, + /// nothing is changed. + /// + /// If a circular property reference is detected, a + /// CircularReferenceException will be thrown. + + void remove(const std::string& key); + /// Removes the property with the given key. + /// + /// Does nothing if the key does not exist. + + void enableEvents(bool enable = true); + /// Enables (or disables) events. + + bool eventsEnabled() const; + /// Returns true iff events are enabled. + +protected: + virtual bool getRaw(const std::string& key, std::string& value) const = 0; + /// If the property with the given key exists, stores the property's value + /// in value and returns true. Otherwise, returns false. + /// + /// Must be overridden by subclasses. + + virtual void setRaw(const std::string& key, const std::string& value) = 0; + /// Sets the property with the given key to the given value. + /// An already existing value for the key is overwritten. + /// + /// Must be overridden by subclasses. + + virtual void enumerate(const std::string& key, Keys& range) const = 0; + /// Returns in range the names of all subkeys under the given key. + /// If an empty key is passed, all root level keys are returned. + + virtual void removeRaw(const std::string& key); + /// Removes the property with the given key. + /// + /// Does nothing if the key does not exist. + /// + /// Should be overridden by subclasses; the default + /// implementation throws a Poco::NotImplementedException. + + static int parseInt(const std::string& value); + static unsigned parseUInt(const std::string& value); + +#if defined(POCO_HAVE_INT64) + + static Int64 parseInt64(const std::string& value); + static UInt64 parseUInt64(const std::string& value); + +#endif // defined(POCO_HAVE_INT64) + + static bool parseBool(const std::string& value); + void setRawWithEvent(const std::string& key, std::string value); + + virtual ~AbstractConfiguration(); + +private: + std::string internalExpand(const std::string& value) const; + std::string uncheckedExpand(const std::string& value) const; + + AbstractConfiguration(const AbstractConfiguration&); + AbstractConfiguration& operator = (const AbstractConfiguration&); + + mutable int _depth; + bool _eventsEnabled; + mutable Poco::Mutex _mutex; + + friend class LayeredConfiguration; + friend class ConfigurationView; + friend class ConfigurationMapper; +}; + + +} } // namespace Poco::Util + + +#endif // Util_AbstractConfiguration_INCLUDED diff --git a/contrib/libs/poco/Util/include/Poco/Util/Application.h b/contrib/libs/poco/Util/include/Poco/Util/Application.h index fc3732b327..da63ecf1b9 100644 --- a/contrib/libs/poco/Util/include/Poco/Util/Application.h +++ b/contrib/libs/poco/Util/include/Poco/Util/Application.h @@ -1,545 +1,545 @@ -// -// Application.h -// -// Library: Util -// Package: Application -// Module: Application -// -// Definition of the Application class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// SPDX-License-Identifier: BSL-1.0 -// - - -#ifndef Util_Application_INCLUDED -#define Util_Application_INCLUDED - - -#include "Poco/Util/Util.h" -#include "Poco/Util/Subsystem.h" -#include "Poco/Util/LayeredConfiguration.h" -#include "Poco/Util/OptionSet.h" -#include "Poco/AutoPtr.h" -#include "Poco/Logger.h" -#include "Poco/Path.h" -#include "Poco/Timestamp.h" -#include "Poco/Timespan.h" -#include "Poco/AutoPtr.h" -#if defined(POCO_VXWORKS) -#include <cstdarg> -#endif -#include <vector> -#include <typeinfo> - - -namespace Poco { -namespace Util { - - -class OptionSet; - - -class Util_API Application: public Subsystem - /// The Application class implements the main subsystem - /// in a process. The application class is responsible for - /// initializing all its subsystems. - /// - /// Subclasses can and should override the following virtual methods: - /// - initialize() (the one-argument, protected variant) - /// - uninitialize() - /// - reinitialize() - /// - defineOptions() - /// - handleOption() - /// - main() - /// - /// The application's main logic should be implemented in - /// the main() method. - /// - /// There may be at most one instance of the Application class - /// in a process. - /// - /// The Application class maintains a LayeredConfiguration (available - /// via the config() member function) consisting of: - /// - a MapConfiguration (priority -100) storing application-specific - /// properties, as well as properties from bound command line arguments. - /// - a SystemConfiguration (priority 100) - /// - the configurations loaded with loadConfiguration(). - /// - /// The Application class sets a few default properties in - /// its configuration. These are: - /// - application.path: the absolute path to application executable - /// - application.name: the file name of the application executable - /// - application.baseName: the file name (excluding extension) of the application executable - /// - application.dir: the path to the directory where the application executable resides - /// - application.configDir: the path to the directory where user specific configuration files of the application should be stored. - /// - application.cacheDir: the path to the directory where user specific non-essential data files of the application should be stored. - /// - application.dataDir: the path to the directory where user specific data files of the application should be stored. - /// - application.tempDir: the path to the directory where user specific temporary files and other file objects of the application should be stored. - /// - /// If loadConfiguration() has never been called, application.configDir will be equal to application.dir. - /// - /// The POCO_APP_MAIN macro can be used to implement main(argc, argv). - /// If POCO has been built with POCO_WIN32_UTF8, POCO_APP_MAIN supports - /// Unicode command line arguments. -{ -public: - typedef std::vector<std::string> ArgVec; - typedef Poco::AutoPtr<Subsystem> SubsystemPtr; - typedef std::vector<SubsystemPtr> SubsystemVec; - - enum ExitCode - /// Commonly used exit status codes. - /// Based on the definitions in the 4.3BSD <sysexits.h> header file. - { - EXIT_OK = 0, /// successful termination - EXIT_USAGE = 64, /// command line usage error - EXIT_DATAERR = 65, /// data format error - EXIT_NOINPUT = 66, /// cannot open input - EXIT_NOUSER = 67, /// addressee unknown - EXIT_NOHOST = 68, /// host name unknown - EXIT_UNAVAILABLE = 69, /// service unavailable - EXIT_SOFTWARE = 70, /// internal software error - EXIT_OSERR = 71, /// system error (e.g., can't fork) - EXIT_OSFILE = 72, /// critical OS file missing - EXIT_CANTCREAT = 73, /// can't create (user) output file - EXIT_IOERR = 74, /// input/output error - EXIT_TEMPFAIL = 75, /// temp failure; user is invited to retry - EXIT_PROTOCOL = 76, /// remote error in protocol - EXIT_NOPERM = 77, /// permission denied - EXIT_CONFIG = 78 /// configuration error - }; - - enum ConfigPriority - { - PRIO_APPLICATION = -100, - PRIO_DEFAULT = 0, - PRIO_SYSTEM = 100 - }; - - Application(); - /// Creates the Application. - - Application(int argc, char* argv[]); - /// Creates the Application and calls init(argc, argv). - - void addSubsystem(Subsystem* pSubsystem); - /// Adds a new subsystem to the application. The - /// application immediately takes ownership of it, so that a - /// call in the form - /// Application::instance().addSubsystem(new MySubsystem); - /// is okay. - - void init(int argc, char* argv[]); - /// Processes the application's command line arguments - /// and sets the application's properties (e.g., - /// "application.path", "application.name", etc.). - /// - /// Note that as of release 1.3.7, init() no longer - /// calls initialize(). This is now called from run(). - -#if defined(POCO_WIN32_UTF8) && !defined(POCO_NO_WSTRING) - void init(int argc, wchar_t* argv[]); - /// Processes the application's command line arguments - /// and sets the application's properties (e.g., - /// "application.path", "application.name", etc.). - /// - /// Note that as of release 1.3.7, init() no longer - /// calls initialize(). This is now called from run(). - /// - /// This Windows-specific version of init is used for passing - /// Unicode command line arguments from wmain(). -#endif - - void init(const ArgVec& args); - /// Processes the application's command line arguments - /// and sets the application's properties (e.g., - /// "application.path", "application.name", etc.). - /// - /// Note that as of release 1.3.7, init() no longer - /// calls initialize(). This is now called from run(). - - bool initialized() const; - /// Returns true iff the application is in initialized state - /// (that means, has been initialized but not yet uninitialized). - - void setUnixOptions(bool flag); - /// Specify whether command line option handling is Unix-style - /// (flag == true; default) or Windows/OpenVMS-style (flag == false). - /// - /// This member function should be called from the constructor of - /// a subclass to be effective. - - int loadConfiguration(int priority = PRIO_DEFAULT); - /// Loads configuration information from a default location. - /// - /// The configuration(s) will be added to the application's - /// LayeredConfiguration with the given priority. - /// - /// The configuration file(s) must be located in the same directory - /// as the executable or a parent directory of it, and must have the - /// same base name as the executable, with one of the following extensions: - /// .properties, .ini or .xml. - /// - /// The .properties file, if it exists, is loaded first, followed - /// by the .ini file and the .xml file. - /// - /// If the application is built in debug mode (the _DEBUG preprocessor - /// macro is defined) and the base name of the appication executable - /// ends with a 'd', a config file without the 'd' ending its base name is - /// also found. - /// - /// Example: Given the application "SampleAppd.exe", built in debug mode. - /// Then loadConfiguration() will automatically find a configuration file - /// named "SampleApp.properties" if it exists and if "SampleAppd.properties" - /// cannot be found. - /// - /// Returns the number of configuration files loaded, which may be zero. - /// - /// This method must not be called before init(argc, argv) - /// has been called. - - void loadConfiguration(const std::string& path, int priority = PRIO_DEFAULT); - /// Loads configuration information from the file specified by - /// the given path. The file type is determined by the file - /// extension. The following extensions are supported: - /// - .properties - properties file (PropertyFileConfiguration) - /// - .ini - initialization file (IniFileConfiguration) - /// - .xml - XML file (XMLConfiguration) - /// - /// Extensions are not case sensitive. - /// - /// The configuration will be added to the application's - /// LayeredConfiguration with the given priority. - - template <class C> C& getSubsystem() const; - /// Returns a reference to the subsystem of the class - /// given as template argument. - /// - /// Throws a NotFoundException if such a subsystem has - /// not been registered. - - SubsystemVec& subsystems(); - /// Returns a reference to the subsystem list - - virtual int run(); - /// Runs the application by performing additional (un)initializations - /// and calling the main() method. - /// - /// First calls initialize(), then calls main(), and - /// finally calls uninitialize(). The latter will be called - /// even if main() throws an exception. If initialize() throws - /// an exception, main() will not be called and the exception - /// will be propagated to the caller. If uninitialize() throws - /// an exception, the exception will be propagated to the caller. - - std::string commandName() const; - /// Returns the command name used to invoke the application. - - std::string commandPath() const; - /// Returns the full command path used to invoke the application. - - LayeredConfiguration& config() const; - /// Returns the application's configuration. - - Poco::Logger& logger() const; - /// Returns the application's logger. - /// - /// Before the logging subsystem has been initialized, the - /// application's logger is "ApplicationStartup", which is - /// connected to a ConsoleChannel. - /// - /// After the logging subsystem has been initialized, which - /// usually happens as the first action in Application::initialize(), - /// the application's logger is the one specified by the - /// "application.logger" configuration property. If that property - /// is not specified, the logger is "Application". - - const ArgVec& argv() const; - /// Returns reference to vector of the application's arguments as - /// specified on the command line. If user overrides the - /// Application::main(const ArgVec&) function, it will receive - /// only the command line parameters that were not processed in - /// Application::processOptons(). This function returns the - /// full set of command line parameters as received in - /// main(argc, argv*). - - const OptionSet& options() const; - /// Returns the application's option set. - - static Application& instance(); - /// Returns a reference to the Application singleton. - /// - /// Throws a NullPointerException if no Application instance exists. - - const Poco::Timestamp& startTime() const; - /// Returns the application start time (UTC). - - Poco::Timespan uptime() const; - /// Returns the application uptime. - - void stopOptionsProcessing(); - /// If called from an option callback, stops all further - /// options processing. - /// - /// If called, the following options on the command line - /// will not be processed, and required options will not - /// be checked. - /// - /// This is useful, for example, if an option for displaying - /// help information has been encountered and no other things - /// besides displaying help shall be done. - - const char* name() const; - -protected: - void initialize(Application& self); - /// Initializes the application and all registered subsystems. - /// Subsystems are always initialized in the exact same order - /// in which they have been registered. - /// - /// Overriding implementations must call the base class implementation. - - void uninitialize(); - /// Uninitializes the application and all registered subsystems. - /// Subsystems are always uninitialized in reverse order in which - /// they have been initialized. - /// - /// Overriding implementations must call the base class implementation. - - void reinitialize(Application& self); - /// Re-nitializes the application and all registered subsystems. - /// Subsystems are always reinitialized in the exact same order - /// in which they have been registered. - /// - /// Overriding implementations must call the base class implementation. - - virtual void defineOptions(OptionSet& options); - /// Called before command line processing begins. - /// If a subclass wants to support command line arguments, - /// it must override this method. - /// The default implementation does not define any options itself, - /// but calls defineOptions() on all registered subsystems. - /// - /// Overriding implementations should call the base class implementation. - - virtual void handleOption(const std::string& name, const std::string& value); - /// Called when the option with the given name is encountered - /// during command line arguments processing. - /// - /// The default implementation does option validation, bindings - /// and callback handling. - /// - /// Overriding implementations must call the base class implementation. - - void setLogger(Poco::Logger& logger); - /// Sets the logger used by the application. - - virtual int main(const std::vector<std::string>& args); - /// The application's main logic. - /// - /// Unprocessed command line arguments are passed in args. - /// Note that all original command line arguments are available - /// via the properties application.argc and application.argv[<n>]. - /// - /// Returns an exit code which should be one of the values - /// from the ExitCode enumeration. - - bool findFile(Poco::Path& path) const; - /// Searches for the file in path in the application directory. - /// - /// If path is absolute, the method immediately returns true and - /// leaves path unchanged. - /// - /// If path is relative, searches for the file in the application - /// directory and in all subsequent parent directories. - /// Returns true and stores the absolute path to the file in - /// path if the file could be found. Returns false and leaves path - /// unchanged otherwise. - - void init(); - /// Common initialization code. - - ~Application(); - /// Destroys the Application and deletes all registered subsystems. - -private: - void setup(); - void setArgs(int argc, char* argv[]); - void setArgs(const ArgVec& args); - void getApplicationPath(Poco::Path& path) const; - void processOptions(); - bool findAppConfigFile(const std::string& appName, const std::string& extension, Poco::Path& path) const; - bool findAppConfigFile(const Path& basePath, const std::string& appName, const std::string& extension, Poco::Path& path) const; - - typedef Poco::AutoPtr<LayeredConfiguration> ConfigPtr; - - ConfigPtr _pConfig; - SubsystemVec _subsystems; - bool _initialized; - std::string _command; - ArgVec _argv; - ArgVec _unprocessedArgs; - OptionSet _options; - bool _unixOptions; - Poco::Logger* _pLogger; - Poco::Timestamp _startTime; - bool _stopOptionsProcessing; - -#if defined(POCO_OS_FAMILY_UNIX) && !defined(POCO_VXWORKS) - std::string _workingDirAtLaunch; -#endif - - static Application* _pInstance; - - friend class LoggingSubsystem; - - Application(const Application&); - Application& operator = (const Application&); -}; - - -// -// inlines -// -template <class C> C& Application::getSubsystem() const -{ - for (SubsystemVec::const_iterator it = _subsystems.begin(); it != _subsystems.end(); ++it) - { - const Subsystem* pSS(it->get()); - const C* pC = dynamic_cast<const C*>(pSS); - if (pC) return *const_cast<C*>(pC); - } - throw Poco::NotFoundException("The subsystem has not been registered", typeid(C).name()); -} - -inline Application::SubsystemVec& Application::subsystems() -{ - return _subsystems; -} - - -inline bool Application::initialized() const -{ - return _initialized; -} - - -inline LayeredConfiguration& Application::config() const -{ - return *const_cast<LayeredConfiguration*>(_pConfig.get()); -} - - -inline Poco::Logger& Application::logger() const -{ - poco_check_ptr (_pLogger); - return *_pLogger; -} - - -inline const Application::ArgVec& Application::argv() const -{ - return _argv; -} - - -inline const OptionSet& Application::options() const -{ - return _options; -} - - -inline Application& Application::instance() -{ - poco_check_ptr (_pInstance); - return *_pInstance; -} - - -inline const Poco::Timestamp& Application::startTime() const -{ - return _startTime; -} - - -inline Poco::Timespan Application::uptime() const -{ - Poco::Timestamp now; - Poco::Timespan uptime = now - _startTime; - - return uptime; -} - - -} } // namespace Poco::Util - - -// -// Macro to implement main() -// -#if defined(_WIN32) && defined(POCO_WIN32_UTF8) && !defined(POCO_NO_WSTRING) - #define POCO_APP_MAIN(App) \ - int wmain(int argc, wchar_t** argv) \ - { \ - Poco::AutoPtr<App> pApp = new App; \ - try \ - { \ - pApp->init(argc, argv); \ - } \ - catch (Poco::Exception& exc) \ - { \ - pApp->logger().log(exc); \ - return Poco::Util::Application::EXIT_CONFIG;\ - } \ - return pApp->run(); \ - } -#elif defined(POCO_VXWORKS) - #define POCO_APP_MAIN(App) \ - int pocoAppMain(const char* appName, ...) \ - { \ - std::vector<std::string> args; \ - args.push_back(std::string(appName)); \ - va_list vargs; \ - va_start(vargs, appName); \ - const char* arg = va_arg(vargs, const char*); \ - while (arg) \ - { \ - args.push_back(std::string(arg)); \ - arg = va_arg(vargs, const char*); \ - } \ - va_end(vargs); \ - Poco::AutoPtr<App> pApp = new App; \ - try \ - { \ - pApp->init(args); \ - } \ - catch (Poco::Exception& exc) \ - { \ - pApp->logger().log(exc); \ - return Poco::Util::Application::EXIT_CONFIG;\ - } \ - return pApp->run(); \ - } -#else - #define POCO_APP_MAIN(App) \ - int main(int argc, char** argv) \ - { \ - Poco::AutoPtr<App> pApp = new App; \ - try \ - { \ - pApp->init(argc, argv); \ - } \ - catch (Poco::Exception& exc) \ - { \ - pApp->logger().log(exc); \ - return Poco::Util::Application::EXIT_CONFIG;\ - } \ - return pApp->run(); \ - } -#endif - - -#endif // Util_Application_INCLUDED +// +// Application.h +// +// Library: Util +// Package: Application +// Module: Application +// +// Definition of the Application class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Util_Application_INCLUDED +#define Util_Application_INCLUDED + + +#include "Poco/Util/Util.h" +#include "Poco/Util/Subsystem.h" +#include "Poco/Util/LayeredConfiguration.h" +#include "Poco/Util/OptionSet.h" +#include "Poco/AutoPtr.h" +#include "Poco/Logger.h" +#include "Poco/Path.h" +#include "Poco/Timestamp.h" +#include "Poco/Timespan.h" +#include "Poco/AutoPtr.h" +#if defined(POCO_VXWORKS) +#include <cstdarg> +#endif +#include <vector> +#include <typeinfo> + + +namespace Poco { +namespace Util { + + +class OptionSet; + + +class Util_API Application: public Subsystem + /// The Application class implements the main subsystem + /// in a process. The application class is responsible for + /// initializing all its subsystems. + /// + /// Subclasses can and should override the following virtual methods: + /// - initialize() (the one-argument, protected variant) + /// - uninitialize() + /// - reinitialize() + /// - defineOptions() + /// - handleOption() + /// - main() + /// + /// The application's main logic should be implemented in + /// the main() method. + /// + /// There may be at most one instance of the Application class + /// in a process. + /// + /// The Application class maintains a LayeredConfiguration (available + /// via the config() member function) consisting of: + /// - a MapConfiguration (priority -100) storing application-specific + /// properties, as well as properties from bound command line arguments. + /// - a SystemConfiguration (priority 100) + /// - the configurations loaded with loadConfiguration(). + /// + /// The Application class sets a few default properties in + /// its configuration. These are: + /// - application.path: the absolute path to application executable + /// - application.name: the file name of the application executable + /// - application.baseName: the file name (excluding extension) of the application executable + /// - application.dir: the path to the directory where the application executable resides + /// - application.configDir: the path to the directory where user specific configuration files of the application should be stored. + /// - application.cacheDir: the path to the directory where user specific non-essential data files of the application should be stored. + /// - application.dataDir: the path to the directory where user specific data files of the application should be stored. + /// - application.tempDir: the path to the directory where user specific temporary files and other file objects of the application should be stored. + /// + /// If loadConfiguration() has never been called, application.configDir will be equal to application.dir. + /// + /// The POCO_APP_MAIN macro can be used to implement main(argc, argv). + /// If POCO has been built with POCO_WIN32_UTF8, POCO_APP_MAIN supports + /// Unicode command line arguments. +{ +public: + typedef std::vector<std::string> ArgVec; + typedef Poco::AutoPtr<Subsystem> SubsystemPtr; + typedef std::vector<SubsystemPtr> SubsystemVec; + + enum ExitCode + /// Commonly used exit status codes. + /// Based on the definitions in the 4.3BSD <sysexits.h> header file. + { + EXIT_OK = 0, /// successful termination + EXIT_USAGE = 64, /// command line usage error + EXIT_DATAERR = 65, /// data format error + EXIT_NOINPUT = 66, /// cannot open input + EXIT_NOUSER = 67, /// addressee unknown + EXIT_NOHOST = 68, /// host name unknown + EXIT_UNAVAILABLE = 69, /// service unavailable + EXIT_SOFTWARE = 70, /// internal software error + EXIT_OSERR = 71, /// system error (e.g., can't fork) + EXIT_OSFILE = 72, /// critical OS file missing + EXIT_CANTCREAT = 73, /// can't create (user) output file + EXIT_IOERR = 74, /// input/output error + EXIT_TEMPFAIL = 75, /// temp failure; user is invited to retry + EXIT_PROTOCOL = 76, /// remote error in protocol + EXIT_NOPERM = 77, /// permission denied + EXIT_CONFIG = 78 /// configuration error + }; + + enum ConfigPriority + { + PRIO_APPLICATION = -100, + PRIO_DEFAULT = 0, + PRIO_SYSTEM = 100 + }; + + Application(); + /// Creates the Application. + + Application(int argc, char* argv[]); + /// Creates the Application and calls init(argc, argv). + + void addSubsystem(Subsystem* pSubsystem); + /// Adds a new subsystem to the application. The + /// application immediately takes ownership of it, so that a + /// call in the form + /// Application::instance().addSubsystem(new MySubsystem); + /// is okay. + + void init(int argc, char* argv[]); + /// Processes the application's command line arguments + /// and sets the application's properties (e.g., + /// "application.path", "application.name", etc.). + /// + /// Note that as of release 1.3.7, init() no longer + /// calls initialize(). This is now called from run(). + +#if defined(POCO_WIN32_UTF8) && !defined(POCO_NO_WSTRING) + void init(int argc, wchar_t* argv[]); + /// Processes the application's command line arguments + /// and sets the application's properties (e.g., + /// "application.path", "application.name", etc.). + /// + /// Note that as of release 1.3.7, init() no longer + /// calls initialize(). This is now called from run(). + /// + /// This Windows-specific version of init is used for passing + /// Unicode command line arguments from wmain(). +#endif + + void init(const ArgVec& args); + /// Processes the application's command line arguments + /// and sets the application's properties (e.g., + /// "application.path", "application.name", etc.). + /// + /// Note that as of release 1.3.7, init() no longer + /// calls initialize(). This is now called from run(). + + bool initialized() const; + /// Returns true iff the application is in initialized state + /// (that means, has been initialized but not yet uninitialized). + + void setUnixOptions(bool flag); + /// Specify whether command line option handling is Unix-style + /// (flag == true; default) or Windows/OpenVMS-style (flag == false). + /// + /// This member function should be called from the constructor of + /// a subclass to be effective. + + int loadConfiguration(int priority = PRIO_DEFAULT); + /// Loads configuration information from a default location. + /// + /// The configuration(s) will be added to the application's + /// LayeredConfiguration with the given priority. + /// + /// The configuration file(s) must be located in the same directory + /// as the executable or a parent directory of it, and must have the + /// same base name as the executable, with one of the following extensions: + /// .properties, .ini or .xml. + /// + /// The .properties file, if it exists, is loaded first, followed + /// by the .ini file and the .xml file. + /// + /// If the application is built in debug mode (the _DEBUG preprocessor + /// macro is defined) and the base name of the appication executable + /// ends with a 'd', a config file without the 'd' ending its base name is + /// also found. + /// + /// Example: Given the application "SampleAppd.exe", built in debug mode. + /// Then loadConfiguration() will automatically find a configuration file + /// named "SampleApp.properties" if it exists and if "SampleAppd.properties" + /// cannot be found. + /// + /// Returns the number of configuration files loaded, which may be zero. + /// + /// This method must not be called before init(argc, argv) + /// has been called. + + void loadConfiguration(const std::string& path, int priority = PRIO_DEFAULT); + /// Loads configuration information from the file specified by + /// the given path. The file type is determined by the file + /// extension. The following extensions are supported: + /// - .properties - properties file (PropertyFileConfiguration) + /// - .ini - initialization file (IniFileConfiguration) + /// - .xml - XML file (XMLConfiguration) + /// + /// Extensions are not case sensitive. + /// + /// The configuration will be added to the application's + /// LayeredConfiguration with the given priority. + + template <class C> C& getSubsystem() const; + /// Returns a reference to the subsystem of the class + /// given as template argument. + /// + /// Throws a NotFoundException if such a subsystem has + /// not been registered. + + SubsystemVec& subsystems(); + /// Returns a reference to the subsystem list + + virtual int run(); + /// Runs the application by performing additional (un)initializations + /// and calling the main() method. + /// + /// First calls initialize(), then calls main(), and + /// finally calls uninitialize(). The latter will be called + /// even if main() throws an exception. If initialize() throws + /// an exception, main() will not be called and the exception + /// will be propagated to the caller. If uninitialize() throws + /// an exception, the exception will be propagated to the caller. + + std::string commandName() const; + /// Returns the command name used to invoke the application. + + std::string commandPath() const; + /// Returns the full command path used to invoke the application. + + LayeredConfiguration& config() const; + /// Returns the application's configuration. + + Poco::Logger& logger() const; + /// Returns the application's logger. + /// + /// Before the logging subsystem has been initialized, the + /// application's logger is "ApplicationStartup", which is + /// connected to a ConsoleChannel. + /// + /// After the logging subsystem has been initialized, which + /// usually happens as the first action in Application::initialize(), + /// the application's logger is the one specified by the + /// "application.logger" configuration property. If that property + /// is not specified, the logger is "Application". + + const ArgVec& argv() const; + /// Returns reference to vector of the application's arguments as + /// specified on the command line. If user overrides the + /// Application::main(const ArgVec&) function, it will receive + /// only the command line parameters that were not processed in + /// Application::processOptons(). This function returns the + /// full set of command line parameters as received in + /// main(argc, argv*). + + const OptionSet& options() const; + /// Returns the application's option set. + + static Application& instance(); + /// Returns a reference to the Application singleton. + /// + /// Throws a NullPointerException if no Application instance exists. + + const Poco::Timestamp& startTime() const; + /// Returns the application start time (UTC). + + Poco::Timespan uptime() const; + /// Returns the application uptime. + + void stopOptionsProcessing(); + /// If called from an option callback, stops all further + /// options processing. + /// + /// If called, the following options on the command line + /// will not be processed, and required options will not + /// be checked. + /// + /// This is useful, for example, if an option for displaying + /// help information has been encountered and no other things + /// besides displaying help shall be done. + + const char* name() const; + +protected: + void initialize(Application& self); + /// Initializes the application and all registered subsystems. + /// Subsystems are always initialized in the exact same order + /// in which they have been registered. + /// + /// Overriding implementations must call the base class implementation. + + void uninitialize(); + /// Uninitializes the application and all registered subsystems. + /// Subsystems are always uninitialized in reverse order in which + /// they have been initialized. + /// + /// Overriding implementations must call the base class implementation. + + void reinitialize(Application& self); + /// Re-nitializes the application and all registered subsystems. + /// Subsystems are always reinitialized in the exact same order + /// in which they have been registered. + /// + /// Overriding implementations must call the base class implementation. + + virtual void defineOptions(OptionSet& options); + /// Called before command line processing begins. + /// If a subclass wants to support command line arguments, + /// it must override this method. + /// The default implementation does not define any options itself, + /// but calls defineOptions() on all registered subsystems. + /// + /// Overriding implementations should call the base class implementation. + + virtual void handleOption(const std::string& name, const std::string& value); + /// Called when the option with the given name is encountered + /// during command line arguments processing. + /// + /// The default implementation does option validation, bindings + /// and callback handling. + /// + /// Overriding implementations must call the base class implementation. + + void setLogger(Poco::Logger& logger); + /// Sets the logger used by the application. + + virtual int main(const std::vector<std::string>& args); + /// The application's main logic. + /// + /// Unprocessed command line arguments are passed in args. + /// Note that all original command line arguments are available + /// via the properties application.argc and application.argv[<n>]. + /// + /// Returns an exit code which should be one of the values + /// from the ExitCode enumeration. + + bool findFile(Poco::Path& path) const; + /// Searches for the file in path in the application directory. + /// + /// If path is absolute, the method immediately returns true and + /// leaves path unchanged. + /// + /// If path is relative, searches for the file in the application + /// directory and in all subsequent parent directories. + /// Returns true and stores the absolute path to the file in + /// path if the file could be found. Returns false and leaves path + /// unchanged otherwise. + + void init(); + /// Common initialization code. + + ~Application(); + /// Destroys the Application and deletes all registered subsystems. + +private: + void setup(); + void setArgs(int argc, char* argv[]); + void setArgs(const ArgVec& args); + void getApplicationPath(Poco::Path& path) const; + void processOptions(); + bool findAppConfigFile(const std::string& appName, const std::string& extension, Poco::Path& path) const; + bool findAppConfigFile(const Path& basePath, const std::string& appName, const std::string& extension, Poco::Path& path) const; + + typedef Poco::AutoPtr<LayeredConfiguration> ConfigPtr; + + ConfigPtr _pConfig; + SubsystemVec _subsystems; + bool _initialized; + std::string _command; + ArgVec _argv; + ArgVec _unprocessedArgs; + OptionSet _options; + bool _unixOptions; + Poco::Logger* _pLogger; + Poco::Timestamp _startTime; + bool _stopOptionsProcessing; + +#if defined(POCO_OS_FAMILY_UNIX) && !defined(POCO_VXWORKS) + std::string _workingDirAtLaunch; +#endif + + static Application* _pInstance; + + friend class LoggingSubsystem; + + Application(const Application&); + Application& operator = (const Application&); +}; + + +// +// inlines +// +template <class C> C& Application::getSubsystem() const +{ + for (SubsystemVec::const_iterator it = _subsystems.begin(); it != _subsystems.end(); ++it) + { + const Subsystem* pSS(it->get()); + const C* pC = dynamic_cast<const C*>(pSS); + if (pC) return *const_cast<C*>(pC); + } + throw Poco::NotFoundException("The subsystem has not been registered", typeid(C).name()); +} + +inline Application::SubsystemVec& Application::subsystems() +{ + return _subsystems; +} + + +inline bool Application::initialized() const +{ + return _initialized; +} + + +inline LayeredConfiguration& Application::config() const +{ + return *const_cast<LayeredConfiguration*>(_pConfig.get()); +} + + +inline Poco::Logger& Application::logger() const +{ + poco_check_ptr (_pLogger); + return *_pLogger; +} + + +inline const Application::ArgVec& Application::argv() const +{ + return _argv; +} + + +inline const OptionSet& Application::options() const +{ + return _options; +} + + +inline Application& Application::instance() +{ + poco_check_ptr (_pInstance); + return *_pInstance; +} + + +inline const Poco::Timestamp& Application::startTime() const +{ + return _startTime; +} + + +inline Poco::Timespan Application::uptime() const +{ + Poco::Timestamp now; + Poco::Timespan uptime = now - _startTime; + + return uptime; +} + + +} } // namespace Poco::Util + + +// +// Macro to implement main() +// +#if defined(_WIN32) && defined(POCO_WIN32_UTF8) && !defined(POCO_NO_WSTRING) + #define POCO_APP_MAIN(App) \ + int wmain(int argc, wchar_t** argv) \ + { \ + Poco::AutoPtr<App> pApp = new App; \ + try \ + { \ + pApp->init(argc, argv); \ + } \ + catch (Poco::Exception& exc) \ + { \ + pApp->logger().log(exc); \ + return Poco::Util::Application::EXIT_CONFIG;\ + } \ + return pApp->run(); \ + } +#elif defined(POCO_VXWORKS) + #define POCO_APP_MAIN(App) \ + int pocoAppMain(const char* appName, ...) \ + { \ + std::vector<std::string> args; \ + args.push_back(std::string(appName)); \ + va_list vargs; \ + va_start(vargs, appName); \ + const char* arg = va_arg(vargs, const char*); \ + while (arg) \ + { \ + args.push_back(std::string(arg)); \ + arg = va_arg(vargs, const char*); \ + } \ + va_end(vargs); \ + Poco::AutoPtr<App> pApp = new App; \ + try \ + { \ + pApp->init(args); \ + } \ + catch (Poco::Exception& exc) \ + { \ + pApp->logger().log(exc); \ + return Poco::Util::Application::EXIT_CONFIG;\ + } \ + return pApp->run(); \ + } +#else + #define POCO_APP_MAIN(App) \ + int main(int argc, char** argv) \ + { \ + Poco::AutoPtr<App> pApp = new App; \ + try \ + { \ + pApp->init(argc, argv); \ + } \ + catch (Poco::Exception& exc) \ + { \ + pApp->logger().log(exc); \ + return Poco::Util::Application::EXIT_CONFIG;\ + } \ + return pApp->run(); \ + } +#endif + + +#endif // Util_Application_INCLUDED diff --git a/contrib/libs/poco/Util/include/Poco/Util/ConfigurationMapper.h b/contrib/libs/poco/Util/include/Poco/Util/ConfigurationMapper.h index a8280f1303..ef8e960d51 100644 --- a/contrib/libs/poco/Util/include/Poco/Util/ConfigurationMapper.h +++ b/contrib/libs/poco/Util/include/Poco/Util/ConfigurationMapper.h @@ -1,94 +1,94 @@ -// -// ConfigurationMapper.h -// -// Library: Util -// Package: Configuration -// Module: ConfigurationMapper -// -// Definition of the ConfigurationMapper class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// SPDX-License-Identifier: BSL-1.0 -// - - -#ifndef Util_ConfigurationMapper_INCLUDED -#define Util_ConfigurationMapper_INCLUDED - - -#include "Poco/Util/Util.h" -#include "Poco/Util/AbstractConfiguration.h" - - -namespace Poco { -namespace Util { - - -class Util_API ConfigurationMapper: public AbstractConfiguration - /// This configuration maps a property hierarchy into another - /// hierarchy. - /// - /// For example, given a configuration with the following properties: - /// config.value1 - /// config.value2 - /// config.sub.value1 - /// config.sub.value2 - /// and a ConfigurationView with fromPrefix == "config" and toPrefix == "root.conf", then - /// the above properties will be available via the mapper as - /// root.conf.value1 - /// root.conf.value2 - /// root.conf.sub.value1 - /// root.conf.sub.value2 +// +// ConfigurationMapper.h +// +// Library: Util +// Package: Configuration +// Module: ConfigurationMapper +// +// Definition of the ConfigurationMapper class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Util_ConfigurationMapper_INCLUDED +#define Util_ConfigurationMapper_INCLUDED + + +#include "Poco/Util/Util.h" +#include "Poco/Util/AbstractConfiguration.h" + + +namespace Poco { +namespace Util { + + +class Util_API ConfigurationMapper: public AbstractConfiguration + /// This configuration maps a property hierarchy into another + /// hierarchy. /// - /// FromPrefix can be empty, in which case, and given toPrefix == "root", - /// the properties will be available as - /// root.config.value1 - /// root.config.value2 - /// root.config.sub.value1 - /// root.config.sub.value2 - /// - /// This is equivalent to the functionality of the ConfigurationView class. - /// - /// Similarly, toPrefix can also be empty. Given fromPrefix == "config" and - /// toPrefix == "", the properties will be available as - /// value1 - /// value2 - /// sub.value1 - /// sub.value2 - /// - /// If both fromPrefix and toPrefix are empty, no mapping is performed. - /// - /// A ConfigurationMapper is most useful in combination with a - /// LayeredConfiguration. -{ -public: - ConfigurationMapper(const std::string& fromPrefix, const std::string& toPrefix, AbstractConfiguration* pConfig); - /// Creates the ConfigurationMapper. The ConfigurationMapper does not take - /// ownership of the passed configuration. - -protected: - bool getRaw(const std::string& key, std::string& value) const; - void setRaw(const std::string& key, const std::string& value); - void enumerate(const std::string& key, Keys& range) const; - void removeRaw(const std::string& key); - - std::string translateKey(const std::string& key) const; - - ~ConfigurationMapper(); - -private: - ConfigurationMapper(const ConfigurationMapper&); - ConfigurationMapper& operator = (const ConfigurationMapper&); - - std::string _fromPrefix; - std::string _toPrefix; - AbstractConfiguration* _pConfig; -}; - - -} } // namespace Poco::Util - - -#endif // Util_ConfigurationMapper_INCLUDED + /// For example, given a configuration with the following properties: + /// config.value1 + /// config.value2 + /// config.sub.value1 + /// config.sub.value2 + /// and a ConfigurationView with fromPrefix == "config" and toPrefix == "root.conf", then + /// the above properties will be available via the mapper as + /// root.conf.value1 + /// root.conf.value2 + /// root.conf.sub.value1 + /// root.conf.sub.value2 + /// + /// FromPrefix can be empty, in which case, and given toPrefix == "root", + /// the properties will be available as + /// root.config.value1 + /// root.config.value2 + /// root.config.sub.value1 + /// root.config.sub.value2 + /// + /// This is equivalent to the functionality of the ConfigurationView class. + /// + /// Similarly, toPrefix can also be empty. Given fromPrefix == "config" and + /// toPrefix == "", the properties will be available as + /// value1 + /// value2 + /// sub.value1 + /// sub.value2 + /// + /// If both fromPrefix and toPrefix are empty, no mapping is performed. + /// + /// A ConfigurationMapper is most useful in combination with a + /// LayeredConfiguration. +{ +public: + ConfigurationMapper(const std::string& fromPrefix, const std::string& toPrefix, AbstractConfiguration* pConfig); + /// Creates the ConfigurationMapper. The ConfigurationMapper does not take + /// ownership of the passed configuration. + +protected: + bool getRaw(const std::string& key, std::string& value) const; + void setRaw(const std::string& key, const std::string& value); + void enumerate(const std::string& key, Keys& range) const; + void removeRaw(const std::string& key); + + std::string translateKey(const std::string& key) const; + + ~ConfigurationMapper(); + +private: + ConfigurationMapper(const ConfigurationMapper&); + ConfigurationMapper& operator = (const ConfigurationMapper&); + + std::string _fromPrefix; + std::string _toPrefix; + AbstractConfiguration* _pConfig; +}; + + +} } // namespace Poco::Util + + +#endif // Util_ConfigurationMapper_INCLUDED diff --git a/contrib/libs/poco/Util/include/Poco/Util/ConfigurationView.h b/contrib/libs/poco/Util/include/Poco/Util/ConfigurationView.h index 3b86fe7d85..10f8948747 100644 --- a/contrib/libs/poco/Util/include/Poco/Util/ConfigurationView.h +++ b/contrib/libs/poco/Util/include/Poco/Util/ConfigurationView.h @@ -1,82 +1,82 @@ -// -// ConfigurationView.h -// -// Library: Util -// Package: Configuration -// Module: ConfigurationView -// -// Definition of the ConfigurationView class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// SPDX-License-Identifier: BSL-1.0 -// - - -#ifndef Util_ConfigurationView_INCLUDED -#define Util_ConfigurationView_INCLUDED - - -#include "Poco/Util/Util.h" -#include "Poco/Util/AbstractConfiguration.h" - - -namespace Poco { -namespace Util { - - -class Util_API ConfigurationView: public AbstractConfiguration - /// This configuration implements a "view" into a sub-hierarchy - /// of another configuration. - /// - /// For example, given a configuration with the following properties: - /// config.value1 - /// config.value2 - /// config.sub.value1 - /// config.sub.value2 - /// and a ConfigurationView with the prefix "config", then - /// the above properties will be available via the view as - /// value1 - /// value2 - /// sub.value1 - /// sub.value2 +// +// ConfigurationView.h +// +// Library: Util +// Package: Configuration +// Module: ConfigurationView +// +// Definition of the ConfigurationView class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Util_ConfigurationView_INCLUDED +#define Util_ConfigurationView_INCLUDED + + +#include "Poco/Util/Util.h" +#include "Poco/Util/AbstractConfiguration.h" + + +namespace Poco { +namespace Util { + + +class Util_API ConfigurationView: public AbstractConfiguration + /// This configuration implements a "view" into a sub-hierarchy + /// of another configuration. /// - /// A ConfigurationView is most useful in combination with a - /// LayeredConfiguration. - /// - /// If a property is not found in the view, it is searched in - /// the original configuration. Given the above example configuration, - /// the property named "config.value1" will still be found in the view. - /// - /// The main reason for this is that placeholder expansion (${property}) - /// still works as expected given a ConfigurationView. -{ -public: - ConfigurationView(const std::string& prefix, AbstractConfiguration* pConfig); - /// Creates the ConfigurationView. The ConfigurationView does not take - /// ownership of the passed configuration. - -protected: - bool getRaw(const std::string& key, std::string& value) const; - void setRaw(const std::string& key, const std::string& value); - void enumerate(const std::string& key, Keys& range) const; - void removeRaw(const std::string& key); - - std::string translateKey(const std::string& key) const; - - ~ConfigurationView(); - -private: - ConfigurationView(const ConfigurationView&); - ConfigurationView& operator = (const ConfigurationView&); - - std::string _prefix; - AbstractConfiguration* _pConfig; -}; - - -} } // namespace Poco::Util - - -#endif // Util_ConfigurationView_INCLUDED + /// For example, given a configuration with the following properties: + /// config.value1 + /// config.value2 + /// config.sub.value1 + /// config.sub.value2 + /// and a ConfigurationView with the prefix "config", then + /// the above properties will be available via the view as + /// value1 + /// value2 + /// sub.value1 + /// sub.value2 + /// + /// A ConfigurationView is most useful in combination with a + /// LayeredConfiguration. + /// + /// If a property is not found in the view, it is searched in + /// the original configuration. Given the above example configuration, + /// the property named "config.value1" will still be found in the view. + /// + /// The main reason for this is that placeholder expansion (${property}) + /// still works as expected given a ConfigurationView. +{ +public: + ConfigurationView(const std::string& prefix, AbstractConfiguration* pConfig); + /// Creates the ConfigurationView. The ConfigurationView does not take + /// ownership of the passed configuration. + +protected: + bool getRaw(const std::string& key, std::string& value) const; + void setRaw(const std::string& key, const std::string& value); + void enumerate(const std::string& key, Keys& range) const; + void removeRaw(const std::string& key); + + std::string translateKey(const std::string& key) const; + + ~ConfigurationView(); + +private: + ConfigurationView(const ConfigurationView&); + ConfigurationView& operator = (const ConfigurationView&); + + std::string _prefix; + AbstractConfiguration* _pConfig; +}; + + +} } // namespace Poco::Util + + +#endif // Util_ConfigurationView_INCLUDED diff --git a/contrib/libs/poco/Util/include/Poco/Util/FilesystemConfiguration.h b/contrib/libs/poco/Util/include/Poco/Util/FilesystemConfiguration.h index d313e1d645..d0a1718982 100644 --- a/contrib/libs/poco/Util/include/Poco/Util/FilesystemConfiguration.h +++ b/contrib/libs/poco/Util/include/Poco/Util/FilesystemConfiguration.h @@ -1,93 +1,93 @@ -// -// FilesystemConfiguration.h -// -// Library: Util -// Package: Configuration -// Module: FilesystemConfiguration -// -// Definition of the FilesystemConfiguration class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// SPDX-License-Identifier: BSL-1.0 -// - - -#ifndef Util_FilesystemConfiguration_INCLUDED -#define Util_FilesystemConfiguration_INCLUDED - - -#include "Poco/Util/Util.h" -#include "Poco/Util/AbstractConfiguration.h" -#include "Poco/Path.h" - - -namespace Poco { -namespace Util { - - -class Util_API FilesystemConfiguration: public AbstractConfiguration - /// An implementation of AbstractConfiguration that stores configuration data - /// in a directory hierarchy in the filesystem. +// +// FilesystemConfiguration.h +// +// Library: Util +// Package: Configuration +// Module: FilesystemConfiguration +// +// Definition of the FilesystemConfiguration class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Util_FilesystemConfiguration_INCLUDED +#define Util_FilesystemConfiguration_INCLUDED + + +#include "Poco/Util/Util.h" +#include "Poco/Util/AbstractConfiguration.h" +#include "Poco/Path.h" + + +namespace Poco { +namespace Util { + + +class Util_API FilesystemConfiguration: public AbstractConfiguration + /// An implementation of AbstractConfiguration that stores configuration data + /// in a directory hierarchy in the filesystem. + /// + /// Every period-separated part of a property name is represented + /// as a directory in the filesystem, relative to the base directory. + /// Values are stored in files named "data". + /// + /// All changes to properties are immediately persisted in the filesystem. + /// + /// For example, a configuration consisting of the properties /// - /// Every period-separated part of a property name is represented - /// as a directory in the filesystem, relative to the base directory. - /// Values are stored in files named "data". - /// - /// All changes to properties are immediately persisted in the filesystem. - /// - /// For example, a configuration consisting of the properties - /// - /// logging.loggers.root.channel.class = ConsoleChannel - /// logging.loggers.app.name = Application - /// logging.loggers.app.channel = c1 - /// logging.formatters.f1.class = PatternFormatter - /// logging.formatters.f1.pattern = [%p] %t - /// - /// is stored in the filesystem as follows: - /// - /// logging/ - /// loggers/ - /// root/ - /// channel/ - /// class/ - /// data ("ConsoleChannel") - /// app/ - /// name/ - /// data ("Application") - /// channel/ - /// data ("c1") - /// formatters/ - /// f1/ - /// class/ - /// data ("PatternFormatter") - /// pattern/ - /// data ("[%p] %t") -{ -public: - FilesystemConfiguration(const std::string& path); - /// Creates a FilesystemConfiguration using the given path. - /// All directories are created as necessary. - - void clear(); - /// Clears the configuration by erasing the configuration - /// directory and all its subdirectories and files. - -protected: - bool getRaw(const std::string& key, std::string& value) const; - void setRaw(const std::string& key, const std::string& value); - void enumerate(const std::string& key, Keys& range) const; - void removeRaw(const std::string& key); - Poco::Path keyToPath(const std::string& key) const; - ~FilesystemConfiguration(); - -private: - Poco::Path _path; -}; - - -} } // namespace Poco::Util - - -#endif // Util_FilesystemConfiguration_INCLUDED + /// logging.loggers.root.channel.class = ConsoleChannel + /// logging.loggers.app.name = Application + /// logging.loggers.app.channel = c1 + /// logging.formatters.f1.class = PatternFormatter + /// logging.formatters.f1.pattern = [%p] %t + /// + /// is stored in the filesystem as follows: + /// + /// logging/ + /// loggers/ + /// root/ + /// channel/ + /// class/ + /// data ("ConsoleChannel") + /// app/ + /// name/ + /// data ("Application") + /// channel/ + /// data ("c1") + /// formatters/ + /// f1/ + /// class/ + /// data ("PatternFormatter") + /// pattern/ + /// data ("[%p] %t") +{ +public: + FilesystemConfiguration(const std::string& path); + /// Creates a FilesystemConfiguration using the given path. + /// All directories are created as necessary. + + void clear(); + /// Clears the configuration by erasing the configuration + /// directory and all its subdirectories and files. + +protected: + bool getRaw(const std::string& key, std::string& value) const; + void setRaw(const std::string& key, const std::string& value); + void enumerate(const std::string& key, Keys& range) const; + void removeRaw(const std::string& key); + Poco::Path keyToPath(const std::string& key) const; + ~FilesystemConfiguration(); + +private: + Poco::Path _path; +}; + + +} } // namespace Poco::Util + + +#endif // Util_FilesystemConfiguration_INCLUDED diff --git a/contrib/libs/poco/Util/include/Poco/Util/HelpFormatter.h b/contrib/libs/poco/Util/include/Poco/Util/HelpFormatter.h index ec51595337..3d79ec0111 100644 --- a/contrib/libs/poco/Util/include/Poco/Util/HelpFormatter.h +++ b/contrib/libs/poco/Util/include/Poco/Util/HelpFormatter.h @@ -1,202 +1,202 @@ -// -// HelpFormatter.h -// -// Library: Util -// Package: Options -// Module: HelpFormatter -// -// Definition of the HelpFormatter class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// SPDX-License-Identifier: BSL-1.0 -// - - -#ifndef Util_HelpFormatter_INCLUDED -#define Util_HelpFormatter_INCLUDED - - -#include "Poco/Util/Util.h" -#include <ostream> - - -namespace Poco { -namespace Util { - - -class OptionSet; -class Option; - - -class Util_API HelpFormatter - /// This class formats a help message from an OptionSet. -{ -public: - HelpFormatter(const OptionSet& options); - /// Creates the HelpFormatter, using the given - /// options. - /// - /// The HelpFormatter just stores a reference - /// to the given OptionSet, so the OptionSet must not - /// be destroyed during the lifetime of the HelpFormatter. - - ~HelpFormatter(); - /// Destroys the HelpFormatter. - - void setCommand(const std::string& command); - /// Sets the command name. - - const std::string& getCommand() const; - /// Returns the command name. - - void setUsage(const std::string& usage); - /// Sets the usage string. - - const std::string& getUsage() const; - /// Returns the usage string. - - void setHeader(const std::string& header); - /// Sets the header string. - - const std::string& getHeader() const; - /// Returns the header string. - - void setFooter(const std::string& footer); - /// Sets the footer string. - - const std::string& getFooter() const; - /// Returns the footer string. - - void format(std::ostream& ostr) const; - /// Writes the formatted help text to the given stream. - - void setWidth(int width); - /// Sets the line width for the formatted help text. - - int getWidth() const; - /// Returns the line width for the formatted help text. - /// - /// The default width is 72. - - void setIndent(int indent); - /// Sets the indentation for description continuation lines. - - int getIndent() const; - /// Returns the indentation for description continuation lines. - - void setAutoIndent(); - /// Sets the indentation for description continuation lines so that - /// the description text is left-aligned. - - void setUnixStyle(bool flag); - /// Enables Unix-style options. Both short and long option names - /// are printed if Unix-style is set. Otherwise, only long option - /// names are printed. - /// - /// After calling setUnixStyle(), setAutoIndent() should be called - /// as well to ensure proper help text formatting. - - bool isUnixStyle() const; - /// Returns if Unix-style options are set. - - std::string shortPrefix() const; - /// Returns the platform-specific prefix for short options. - /// "-" on Unix, "/" on Windows and OpenVMS. - - std::string longPrefix() const; - /// Returns the platform-specific prefix for long options. - /// "--" on Unix, "/" on Windows and OpenVMS. - -protected: - int calcIndent() const; - /// Calculates the indentation for the option descriptions - /// from the given options. - - void formatOptions(std::ostream& ostr) const; - /// Formats all options. - - void formatOption(std::ostream& ostr, const Option& option, int width) const; - /// Formats an option, using the platform-specific - /// prefixes. - - void formatText(std::ostream& ostr, const std::string& text, int indent) const; - /// Formats the given text. - - void formatText(std::ostream& ostr, const std::string& text, int indent, int firstIndent) const; - /// Formats the given text. - - void formatWord(std::ostream& ostr, int& pos, const std::string& word, int indent) const; - /// Formats the given word. - - void clearWord(std::ostream& ostr, int& pos, std::string& word, int indent) const; - /// Formats and then clears the given word. - -private: - HelpFormatter(const HelpFormatter&); - HelpFormatter& operator = (const HelpFormatter&); - - const OptionSet& _options; - int _width; - int _indent; - std::string _command; - std::string _usage; - std::string _header; - std::string _footer; - bool _unixStyle; - - static const int TAB_WIDTH; - static const int LINE_WIDTH; -}; - - -// -// inlines -// -inline int HelpFormatter::getWidth() const -{ - return _width; -} - - -inline int HelpFormatter::getIndent() const -{ - return _indent; -} - - -inline const std::string& HelpFormatter::getCommand() const -{ - return _command; -} - - -inline const std::string& HelpFormatter::getUsage() const -{ - return _usage; -} - - -inline const std::string& HelpFormatter::getHeader() const -{ - return _header; -} - - -inline const std::string& HelpFormatter::getFooter() const -{ - return _footer; -} - - -inline bool HelpFormatter::isUnixStyle() const -{ - return _unixStyle; -} - - -} } // namespace Poco::Util - - -#endif // Util_HelpFormatter_INCLUDED +// +// HelpFormatter.h +// +// Library: Util +// Package: Options +// Module: HelpFormatter +// +// Definition of the HelpFormatter class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Util_HelpFormatter_INCLUDED +#define Util_HelpFormatter_INCLUDED + + +#include "Poco/Util/Util.h" +#include <ostream> + + +namespace Poco { +namespace Util { + + +class OptionSet; +class Option; + + +class Util_API HelpFormatter + /// This class formats a help message from an OptionSet. +{ +public: + HelpFormatter(const OptionSet& options); + /// Creates the HelpFormatter, using the given + /// options. + /// + /// The HelpFormatter just stores a reference + /// to the given OptionSet, so the OptionSet must not + /// be destroyed during the lifetime of the HelpFormatter. + + ~HelpFormatter(); + /// Destroys the HelpFormatter. + + void setCommand(const std::string& command); + /// Sets the command name. + + const std::string& getCommand() const; + /// Returns the command name. + + void setUsage(const std::string& usage); + /// Sets the usage string. + + const std::string& getUsage() const; + /// Returns the usage string. + + void setHeader(const std::string& header); + /// Sets the header string. + + const std::string& getHeader() const; + /// Returns the header string. + + void setFooter(const std::string& footer); + /// Sets the footer string. + + const std::string& getFooter() const; + /// Returns the footer string. + + void format(std::ostream& ostr) const; + /// Writes the formatted help text to the given stream. + + void setWidth(int width); + /// Sets the line width for the formatted help text. + + int getWidth() const; + /// Returns the line width for the formatted help text. + /// + /// The default width is 72. + + void setIndent(int indent); + /// Sets the indentation for description continuation lines. + + int getIndent() const; + /// Returns the indentation for description continuation lines. + + void setAutoIndent(); + /// Sets the indentation for description continuation lines so that + /// the description text is left-aligned. + + void setUnixStyle(bool flag); + /// Enables Unix-style options. Both short and long option names + /// are printed if Unix-style is set. Otherwise, only long option + /// names are printed. + /// + /// After calling setUnixStyle(), setAutoIndent() should be called + /// as well to ensure proper help text formatting. + + bool isUnixStyle() const; + /// Returns if Unix-style options are set. + + std::string shortPrefix() const; + /// Returns the platform-specific prefix for short options. + /// "-" on Unix, "/" on Windows and OpenVMS. + + std::string longPrefix() const; + /// Returns the platform-specific prefix for long options. + /// "--" on Unix, "/" on Windows and OpenVMS. + +protected: + int calcIndent() const; + /// Calculates the indentation for the option descriptions + /// from the given options. + + void formatOptions(std::ostream& ostr) const; + /// Formats all options. + + void formatOption(std::ostream& ostr, const Option& option, int width) const; + /// Formats an option, using the platform-specific + /// prefixes. + + void formatText(std::ostream& ostr, const std::string& text, int indent) const; + /// Formats the given text. + + void formatText(std::ostream& ostr, const std::string& text, int indent, int firstIndent) const; + /// Formats the given text. + + void formatWord(std::ostream& ostr, int& pos, const std::string& word, int indent) const; + /// Formats the given word. + + void clearWord(std::ostream& ostr, int& pos, std::string& word, int indent) const; + /// Formats and then clears the given word. + +private: + HelpFormatter(const HelpFormatter&); + HelpFormatter& operator = (const HelpFormatter&); + + const OptionSet& _options; + int _width; + int _indent; + std::string _command; + std::string _usage; + std::string _header; + std::string _footer; + bool _unixStyle; + + static const int TAB_WIDTH; + static const int LINE_WIDTH; +}; + + +// +// inlines +// +inline int HelpFormatter::getWidth() const +{ + return _width; +} + + +inline int HelpFormatter::getIndent() const +{ + return _indent; +} + + +inline const std::string& HelpFormatter::getCommand() const +{ + return _command; +} + + +inline const std::string& HelpFormatter::getUsage() const +{ + return _usage; +} + + +inline const std::string& HelpFormatter::getHeader() const +{ + return _header; +} + + +inline const std::string& HelpFormatter::getFooter() const +{ + return _footer; +} + + +inline bool HelpFormatter::isUnixStyle() const +{ + return _unixStyle; +} + + +} } // namespace Poco::Util + + +#endif // Util_HelpFormatter_INCLUDED diff --git a/contrib/libs/poco/Util/include/Poco/Util/IniFileConfiguration.h b/contrib/libs/poco/Util/include/Poco/Util/IniFileConfiguration.h index 3da2582370..94ea5da333 100644 --- a/contrib/libs/poco/Util/include/Poco/Util/IniFileConfiguration.h +++ b/contrib/libs/poco/Util/include/Poco/Util/IniFileConfiguration.h @@ -1,99 +1,99 @@ -// -// IniFileConfiguration.h -// -// Library: Util -// Package: Configuration -// Module: IniFileConfiguration -// -// Definition of the IniFileConfiguration class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// SPDX-License-Identifier: BSL-1.0 -// - - -#ifndef Util_IniFileConfiguration_INCLUDED -#define Util_IniFileConfiguration_INCLUDED - - -#include "Poco/Util/Util.h" - - -#ifndef POCO_UTIL_NO_INIFILECONFIGURATION - - -#include "Poco/Util/AbstractConfiguration.h" -#include <map> -#include <istream> - - -namespace Poco { -namespace Util { - - -class Util_API IniFileConfiguration: public AbstractConfiguration - /// This implementation of a Configuration reads properties - /// from a legacy Windows initialization (.ini) file. - /// - /// The file syntax is implemented as follows. - /// - a line starting with a semicolon is treated as a comment and ignored - /// - a line starting with a square bracket denotes a section key [<key>] - /// - every other line denotes a property assignment in the form - /// <value key> = <value> - /// - /// The name of a property is composed of the section key and the value key, - /// separated by a period (<section key>.<value key>). - /// - /// Property names are not case sensitive. Leading and trailing whitespace is - /// removed from both keys and values. -{ -public: - IniFileConfiguration(); - /// Creates an empty IniFileConfiguration. - - IniFileConfiguration(std::istream& istr); - /// Creates an IniFileConfiguration and loads the configuration data - /// from the given stream, which must be in initialization file format. - - IniFileConfiguration(const std::string& path); - /// Creates an IniFileConfiguration and loads the configuration data - /// from the given file, which must be in initialization file format. - - void load(std::istream& istr); - /// Loads the configuration data from the given stream, which - /// must be in initialization file format. - - void load(const std::string& path); - /// Loads the configuration data from the given file, which - /// must be in initialization file format. - -protected: - bool getRaw(const std::string& key, std::string& value) const; - void setRaw(const std::string& key, const std::string& value); - void enumerate(const std::string& key, Keys& range) const; - void removeRaw(const std::string& key); - ~IniFileConfiguration(); - -private: - void parseLine(std::istream& istr); - - struct ICompare - { - bool operator () (const std::string& s1, const std::string& s2) const; - }; - typedef std::map<std::string, std::string, ICompare> IStringMap; - - IStringMap _map; - std::string _sectionKey; -}; - - -} } // namespace Poco::Util - - -#endif // POCO_UTIL_NO_INIFILECONFIGURATION - - -#endif // Util_IniFileConfiguration_INCLUDED +// +// IniFileConfiguration.h +// +// Library: Util +// Package: Configuration +// Module: IniFileConfiguration +// +// Definition of the IniFileConfiguration class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Util_IniFileConfiguration_INCLUDED +#define Util_IniFileConfiguration_INCLUDED + + +#include "Poco/Util/Util.h" + + +#ifndef POCO_UTIL_NO_INIFILECONFIGURATION + + +#include "Poco/Util/AbstractConfiguration.h" +#include <map> +#include <istream> + + +namespace Poco { +namespace Util { + + +class Util_API IniFileConfiguration: public AbstractConfiguration + /// This implementation of a Configuration reads properties + /// from a legacy Windows initialization (.ini) file. + /// + /// The file syntax is implemented as follows. + /// - a line starting with a semicolon is treated as a comment and ignored + /// - a line starting with a square bracket denotes a section key [<key>] + /// - every other line denotes a property assignment in the form + /// <value key> = <value> + /// + /// The name of a property is composed of the section key and the value key, + /// separated by a period (<section key>.<value key>). + /// + /// Property names are not case sensitive. Leading and trailing whitespace is + /// removed from both keys and values. +{ +public: + IniFileConfiguration(); + /// Creates an empty IniFileConfiguration. + + IniFileConfiguration(std::istream& istr); + /// Creates an IniFileConfiguration and loads the configuration data + /// from the given stream, which must be in initialization file format. + + IniFileConfiguration(const std::string& path); + /// Creates an IniFileConfiguration and loads the configuration data + /// from the given file, which must be in initialization file format. + + void load(std::istream& istr); + /// Loads the configuration data from the given stream, which + /// must be in initialization file format. + + void load(const std::string& path); + /// Loads the configuration data from the given file, which + /// must be in initialization file format. + +protected: + bool getRaw(const std::string& key, std::string& value) const; + void setRaw(const std::string& key, const std::string& value); + void enumerate(const std::string& key, Keys& range) const; + void removeRaw(const std::string& key); + ~IniFileConfiguration(); + +private: + void parseLine(std::istream& istr); + + struct ICompare + { + bool operator () (const std::string& s1, const std::string& s2) const; + }; + typedef std::map<std::string, std::string, ICompare> IStringMap; + + IStringMap _map; + std::string _sectionKey; +}; + + +} } // namespace Poco::Util + + +#endif // POCO_UTIL_NO_INIFILECONFIGURATION + + +#endif // Util_IniFileConfiguration_INCLUDED diff --git a/contrib/libs/poco/Util/include/Poco/Util/IntValidator.h b/contrib/libs/poco/Util/include/Poco/Util/IntValidator.h index f997028f09..10e15f83f3 100644 --- a/contrib/libs/poco/Util/include/Poco/Util/IntValidator.h +++ b/contrib/libs/poco/Util/include/Poco/Util/IntValidator.h @@ -1,56 +1,56 @@ -// -// IntValidator.h -// -// Library: Util -// Package: Options -// Module: IntValidator -// -// Definition of the IntValidator class. -// -// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// SPDX-License-Identifier: BSL-1.0 -// - - -#ifndef Util_IntValidator_INCLUDED -#define Util_IntValidator_INCLUDED - - -#include "Poco/Util/Util.h" -#include "Poco/Util/Validator.h" - - -namespace Poco { -namespace Util { - - -class Util_API IntValidator: public Validator - /// The IntValidator tests whether the option argument, - /// which must be an integer, lies within a given range. -{ -public: - IntValidator(int min, int max); - /// Creates the IntValidator. - - ~IntValidator(); - /// Destroys the IntValidator. - - void validate(const Option& option, const std::string& value); - /// Validates the value for the given option by - /// testing whether it's an integer that lies within - /// a given range. - -private: - IntValidator(); - - int _min; - int _max; -}; - - -} } // namespace Poco::Util - - -#endif // Util_IntValidator_INCLUDED +// +// IntValidator.h +// +// Library: Util +// Package: Options +// Module: IntValidator +// +// Definition of the IntValidator class. +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Util_IntValidator_INCLUDED +#define Util_IntValidator_INCLUDED + + +#include "Poco/Util/Util.h" +#include "Poco/Util/Validator.h" + + +namespace Poco { +namespace Util { + + +class Util_API IntValidator: public Validator + /// The IntValidator tests whether the option argument, + /// which must be an integer, lies within a given range. +{ +public: + IntValidator(int min, int max); + /// Creates the IntValidator. + + ~IntValidator(); + /// Destroys the IntValidator. + + void validate(const Option& option, const std::string& value); + /// Validates the value for the given option by + /// testing whether it's an integer that lies within + /// a given range. + +private: + IntValidator(); + + int _min; + int _max; +}; + + +} } // namespace Poco::Util + + +#endif // Util_IntValidator_INCLUDED diff --git a/contrib/libs/poco/Util/include/Poco/Util/JSONConfiguration.h b/contrib/libs/poco/Util/include/Poco/Util/JSONConfiguration.h index 8baec47dfb..d1fa53ece9 100644 --- a/contrib/libs/poco/Util/include/Poco/Util/JSONConfiguration.h +++ b/contrib/libs/poco/Util/include/Poco/Util/JSONConfiguration.h @@ -1,150 +1,150 @@ -// -// JSONConfiguration.h -// -// Library: Util -// Package: Util -// Module: JSONConfiguration -// -// Definition of the JSONConfiguration class. -// -// Copyright (c) 2012, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// SPDX-License-Identifier: BSL-1.0 -// - - -#ifndef Util_JSONConfiguration_INCLUDED -#define Util_JSONConfiguration_INCLUDED - - -#include "Poco/Util/Util.h" - - -#ifndef POCO_UTIL_NO_JSONCONFIGURATION - - -#include "Poco/Util/AbstractConfiguration.h" -#include "Poco/JSON/Object.h" -#include <istream> - - -namespace Poco { -namespace Util { - - -class Util_API JSONConfiguration : public AbstractConfiguration - /// This configuration class extracts configuration properties - /// from a JSON object. An XPath-like syntax for property - /// names is supported to allow full access to the JSON object. - /// - /// Given the following JSON object as an example: - /// { - /// "config" : { - /// "prop1" : "value1", - /// "prop2" : 10, - /// "prop3" : [ - /// "element1", - /// "element2" - /// ], - /// "prop4" : { - /// "prop5" : false, - /// "prop6" : null - /// } - /// } - /// } - /// The following property names would be valid and would - /// yield the shown values: - /// - /// config.prop1 --> "value1" - /// config.prop3[1] --> "element2" - /// config.prop4.prop5 --> false -{ -public: - - JSONConfiguration(); - /// Creates an empty configuration - - - JSONConfiguration(const std::string& path); - /// Creates a configuration and loads the JSON structure from the given file - - - JSONConfiguration(std::istream& istr); - /// Creates a configuration and loads the JSON structure from the given stream - - - JSONConfiguration(const JSON::Object::Ptr& object); - /// Creates a configuration from the given JSON object - - - virtual ~JSONConfiguration(); - /// Destructor - - - void load(const std::string& path); - /// Loads the configuration from the given file - - - void load(std::istream& istr); - /// Loads the configuration from the given stream - - - void loadEmpty(const std::string& root); - /// Loads an empty object containing only a root object with the given name. - - - void save(std::ostream& ostr, unsigned int indent = 2) const; - /// Saves the configuration to the given stream - - - virtual void setInt(const std::string& key, int value); - - - virtual void setBool(const std::string& key, bool value); - - - virtual void setDouble(const std::string& key, double value); - - - virtual void setString(const std::string& key, const std::string& value); - - - virtual void removeRaw(const std::string& key); - - -protected: - - bool getRaw(const std::string & key, std::string & value) const; - - - void setRaw(const std::string& key, const std::string& value); - - - void enumerate(const std::string& key, Keys& range) const; - - -private: - - - JSON::Object::Ptr findStart(const std::string& key, std::string& lastPart); - - - void getIndexes(std::string& name, std::vector<int>& indexes); - - - void setValue(const std::string& key, const Poco::DynamicAny& value); - - - JSON::Object::Ptr _object; -}; - - -} } // namespace Poco::Util - - -#endif // POCO_UTIL_NO_JSONCONFIGURATION - - -#endif // Util_JSONConfiguration_INCLUDED - +// +// JSONConfiguration.h +// +// Library: Util +// Package: Util +// Module: JSONConfiguration +// +// Definition of the JSONConfiguration class. +// +// Copyright (c) 2012, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Util_JSONConfiguration_INCLUDED +#define Util_JSONConfiguration_INCLUDED + + +#include "Poco/Util/Util.h" + + +#ifndef POCO_UTIL_NO_JSONCONFIGURATION + + +#include "Poco/Util/AbstractConfiguration.h" +#include "Poco/JSON/Object.h" +#include <istream> + + +namespace Poco { +namespace Util { + + +class Util_API JSONConfiguration : public AbstractConfiguration + /// This configuration class extracts configuration properties + /// from a JSON object. An XPath-like syntax for property + /// names is supported to allow full access to the JSON object. + /// + /// Given the following JSON object as an example: + /// { + /// "config" : { + /// "prop1" : "value1", + /// "prop2" : 10, + /// "prop3" : [ + /// "element1", + /// "element2" + /// ], + /// "prop4" : { + /// "prop5" : false, + /// "prop6" : null + /// } + /// } + /// } + /// The following property names would be valid and would + /// yield the shown values: + /// + /// config.prop1 --> "value1" + /// config.prop3[1] --> "element2" + /// config.prop4.prop5 --> false +{ +public: + + JSONConfiguration(); + /// Creates an empty configuration + + + JSONConfiguration(const std::string& path); + /// Creates a configuration and loads the JSON structure from the given file + + + JSONConfiguration(std::istream& istr); + /// Creates a configuration and loads the JSON structure from the given stream + + + JSONConfiguration(const JSON::Object::Ptr& object); + /// Creates a configuration from the given JSON object + + + virtual ~JSONConfiguration(); + /// Destructor + + + void load(const std::string& path); + /// Loads the configuration from the given file + + + void load(std::istream& istr); + /// Loads the configuration from the given stream + + + void loadEmpty(const std::string& root); + /// Loads an empty object containing only a root object with the given name. + + + void save(std::ostream& ostr, unsigned int indent = 2) const; + /// Saves the configuration to the given stream + + + virtual void setInt(const std::string& key, int value); + + + virtual void setBool(const std::string& key, bool value); + + + virtual void setDouble(const std::string& key, double value); + + + virtual void setString(const std::string& key, const std::string& value); + + + virtual void removeRaw(const std::string& key); + + +protected: + + bool getRaw(const std::string & key, std::string & value) const; + + + void setRaw(const std::string& key, const std::string& value); + + + void enumerate(const std::string& key, Keys& range) const; + + +private: + + + JSON::Object::Ptr findStart(const std::string& key, std::string& lastPart); + + + void getIndexes(std::string& name, std::vector<int>& indexes); + + + void setValue(const std::string& key, const Poco::DynamicAny& value); + + + JSON::Object::Ptr _object; +}; + + +} } // namespace Poco::Util + + +#endif // POCO_UTIL_NO_JSONCONFIGURATION + + +#endif // Util_JSONConfiguration_INCLUDED + diff --git a/contrib/libs/poco/Util/include/Poco/Util/LayeredConfiguration.h b/contrib/libs/poco/Util/include/Poco/Util/LayeredConfiguration.h index 47137c9be2..59628b36b1 100644 --- a/contrib/libs/poco/Util/include/Poco/Util/LayeredConfiguration.h +++ b/contrib/libs/poco/Util/include/Poco/Util/LayeredConfiguration.h @@ -1,184 +1,184 @@ -// -// LayeredConfiguration.h -// -// Library: Util -// Package: Configuration -// Module: LayeredConfiguration -// -// Definition of the LayeredConfiguration class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// SPDX-License-Identifier: BSL-1.0 -// - - -#ifndef Util_LayeredConfiguration_INCLUDED -#define Util_LayeredConfiguration_INCLUDED - - -#include "Poco/Util/Util.h" -#include "Poco/Util/AbstractConfiguration.h" -#include "Poco/AutoPtr.h" -#include <list> - - -namespace Poco { -namespace Util { - - -class Util_API LayeredConfiguration: public AbstractConfiguration - /// A LayeredConfiguration consists of a number of AbstractConfigurations. - /// - /// When reading a configuration property in a LayeredConfiguration, - /// all added configurations are searched, in order of their priority. - /// Configurations with lower priority values have precedence. - /// - /// When setting a property, the property is always written to the first writeable - /// configuration (see addWriteable()). - /// If no writeable configuration has been added to the LayeredConfiguration, and an - /// attempt is made to set a property, a RuntimeException is thrown. - /// - /// Every configuration added to the LayeredConfiguration has a priority value. - /// The priority determines the position where the configuration is inserted, - /// with lower priority values coming before higher priority values. - /// - /// If no priority is specified, a priority of 0 is assumed. -{ -public: - typedef Poco::AutoPtr<AbstractConfiguration> ConfigPtr; - - LayeredConfiguration(); - /// Creates the LayeredConfiguration. - - void add(AbstractConfiguration* pConfig); - /// Adds a read-only configuration to the back of the LayeredConfiguration. - /// The LayeredConfiguration does not take ownership of the given - /// configuration. In other words, the configuration's reference - /// count is incremented. - - void add(AbstractConfiguration* pConfig, const std::string& label); - /// Adds a read-only configuration with the given label to the back of the LayeredConfiguration. - /// The LayeredConfiguration does not take ownership of the given - /// configuration. In other words, the configuration's reference - /// count is incremented. - - void add(AbstractConfiguration* pConfig, bool shared); - /// Adds a read-only configuration to the back of the LayeredConfiguration. - /// If shared is false, the LayeredConfiguration takes ownership - /// of the given configuration (and the configuration's reference - /// count remains unchanged). - - void add(AbstractConfiguration* pConfig, const std::string& label, bool shared); - /// Adds a read-only configuration with the given label to the back of the LayeredConfiguration. - /// If shared is false, the LayeredConfiguration takes ownership - /// of the given configuration (and the configuration's reference - /// count remains unchanged). - - void add(AbstractConfiguration* pConfig, int priority); - /// Adds a read-only configuration to the LayeredConfiguration. - /// The LayeredConfiguration does not take ownership of the given - /// configuration. In other words, the configuration's reference - /// count is incremented. - - void add(AbstractConfiguration* pConfig, const std::string& label, int priority); - /// Adds a read-only configuration with the given label to the LayeredConfiguration. - /// The LayeredConfiguration does not take ownership of the given - /// configuration. In other words, the configuration's reference - /// count is incremented. - - void add(AbstractConfiguration* pConfig, int priority, bool shared); - /// Adds a read-only configuration the LayeredConfiguration. - /// If shared is false, the LayeredConfiguration takes ownership - /// of the given configuration (and the configuration's reference - /// count remains unchanged). - - void add(AbstractConfiguration* pConfig, const std::string& label, int priority, bool shared); - /// Adds a read-only configuration with the given label the LayeredConfiguration. - /// If shared is false, the LayeredConfiguration takes ownership - /// of the given configuration (and the configuration's reference - /// count remains unchanged). - - void add(AbstractConfiguration* pConfig, int priority, bool writeable, bool shared); - /// Adds a configuration to the LayeredConfiguration. - /// If shared is false, the LayeredConfiguration takes ownership - /// of the given configuration (and the configuration's reference - /// count remains unchanged). - - void add(AbstractConfiguration* pConfig, const std::string& label, int priority, bool writeable, bool shared); - /// Adds a configuration with the given label to the LayeredConfiguration. - /// If shared is false, the LayeredConfiguration takes ownership - /// of the given configuration (and the configuration's reference - /// count remains unchanged). - - void addWriteable(AbstractConfiguration* pConfig, int priority); - /// Adds a writeable configuration to the LayeredConfiguration. - /// The LayeredConfiguration does not take ownership of the given - /// configuration. In other words, the configuration's reference - /// count is incremented. - - void addWriteable(AbstractConfiguration* pConfig, int priority, bool shared); - /// Adds a writeable configuration to the LayeredConfiguration. - /// If shared is false, the LayeredConfiguration takes ownership - /// of the given configuration (and the configuration's reference - /// count remains unchanged). - - ConfigPtr find(const std::string& label) const; - /// Finds and returns the configuration with the given label. - /// - /// Returns null if no such configuration can be found. - - //@ deprecated - void addFront(AbstractConfiguration* pConfig); - /// Adds a read-only configuration to the front of the LayeredConfiguration. - /// The LayeredConfiguration does not take ownership of the given - /// configuration. In other words, the configuration's reference - /// count is incremented. - - //@ deprecated - void addFront(AbstractConfiguration* pConfig, bool shared); - /// Adds a read-only configuration to the front of the LayeredConfiguration. - /// If shared is true, the LayeredConfiguration takes ownership - /// of the given configuration. - - void removeConfiguration(AbstractConfiguration* pConfig); - /// Removes the given configuration from the LayeredConfiguration. - /// - /// Does nothing if the given configuration is not part of the - /// LayeredConfiguration. - -protected: - struct ConfigItem - { - ConfigPtr pConfig; - int priority; - bool writeable; - std::string label; - }; - - bool getRaw(const std::string& key, std::string& value) const; - void setRaw(const std::string& key, const std::string& value); - void enumerate(const std::string& key, Keys& range) const; - void removeRaw(const std::string& key); - - int lowest() const; - int highest() const; - void insert(const ConfigItem& item); - - ~LayeredConfiguration(); - -private: - LayeredConfiguration(const LayeredConfiguration&); - LayeredConfiguration& operator = (const LayeredConfiguration&); - - typedef std::list<ConfigItem> ConfigList; - - ConfigList _configs; -}; - - -} } // namespace Poco::Util - - -#endif // Util_LayeredConfiguration_INCLUDED +// +// LayeredConfiguration.h +// +// Library: Util +// Package: Configuration +// Module: LayeredConfiguration +// +// Definition of the LayeredConfiguration class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Util_LayeredConfiguration_INCLUDED +#define Util_LayeredConfiguration_INCLUDED + + +#include "Poco/Util/Util.h" +#include "Poco/Util/AbstractConfiguration.h" +#include "Poco/AutoPtr.h" +#include <list> + + +namespace Poco { +namespace Util { + + +class Util_API LayeredConfiguration: public AbstractConfiguration + /// A LayeredConfiguration consists of a number of AbstractConfigurations. + /// + /// When reading a configuration property in a LayeredConfiguration, + /// all added configurations are searched, in order of their priority. + /// Configurations with lower priority values have precedence. + /// + /// When setting a property, the property is always written to the first writeable + /// configuration (see addWriteable()). + /// If no writeable configuration has been added to the LayeredConfiguration, and an + /// attempt is made to set a property, a RuntimeException is thrown. + /// + /// Every configuration added to the LayeredConfiguration has a priority value. + /// The priority determines the position where the configuration is inserted, + /// with lower priority values coming before higher priority values. + /// + /// If no priority is specified, a priority of 0 is assumed. +{ +public: + typedef Poco::AutoPtr<AbstractConfiguration> ConfigPtr; + + LayeredConfiguration(); + /// Creates the LayeredConfiguration. + + void add(AbstractConfiguration* pConfig); + /// Adds a read-only configuration to the back of the LayeredConfiguration. + /// The LayeredConfiguration does not take ownership of the given + /// configuration. In other words, the configuration's reference + /// count is incremented. + + void add(AbstractConfiguration* pConfig, const std::string& label); + /// Adds a read-only configuration with the given label to the back of the LayeredConfiguration. + /// The LayeredConfiguration does not take ownership of the given + /// configuration. In other words, the configuration's reference + /// count is incremented. + + void add(AbstractConfiguration* pConfig, bool shared); + /// Adds a read-only configuration to the back of the LayeredConfiguration. + /// If shared is false, the LayeredConfiguration takes ownership + /// of the given configuration (and the configuration's reference + /// count remains unchanged). + + void add(AbstractConfiguration* pConfig, const std::string& label, bool shared); + /// Adds a read-only configuration with the given label to the back of the LayeredConfiguration. + /// If shared is false, the LayeredConfiguration takes ownership + /// of the given configuration (and the configuration's reference + /// count remains unchanged). + + void add(AbstractConfiguration* pConfig, int priority); + /// Adds a read-only configuration to the LayeredConfiguration. + /// The LayeredConfiguration does not take ownership of the given + /// configuration. In other words, the configuration's reference + /// count is incremented. + + void add(AbstractConfiguration* pConfig, const std::string& label, int priority); + /// Adds a read-only configuration with the given label to the LayeredConfiguration. + /// The LayeredConfiguration does not take ownership of the given + /// configuration. In other words, the configuration's reference + /// count is incremented. + + void add(AbstractConfiguration* pConfig, int priority, bool shared); + /// Adds a read-only configuration the LayeredConfiguration. + /// If shared is false, the LayeredConfiguration takes ownership + /// of the given configuration (and the configuration's reference + /// count remains unchanged). + + void add(AbstractConfiguration* pConfig, const std::string& label, int priority, bool shared); + /// Adds a read-only configuration with the given label the LayeredConfiguration. + /// If shared is false, the LayeredConfiguration takes ownership + /// of the given configuration (and the configuration's reference + /// count remains unchanged). + + void add(AbstractConfiguration* pConfig, int priority, bool writeable, bool shared); + /// Adds a configuration to the LayeredConfiguration. + /// If shared is false, the LayeredConfiguration takes ownership + /// of the given configuration (and the configuration's reference + /// count remains unchanged). + + void add(AbstractConfiguration* pConfig, const std::string& label, int priority, bool writeable, bool shared); + /// Adds a configuration with the given label to the LayeredConfiguration. + /// If shared is false, the LayeredConfiguration takes ownership + /// of the given configuration (and the configuration's reference + /// count remains unchanged). + + void addWriteable(AbstractConfiguration* pConfig, int priority); + /// Adds a writeable configuration to the LayeredConfiguration. + /// The LayeredConfiguration does not take ownership of the given + /// configuration. In other words, the configuration's reference + /// count is incremented. + + void addWriteable(AbstractConfiguration* pConfig, int priority, bool shared); + /// Adds a writeable configuration to the LayeredConfiguration. + /// If shared is false, the LayeredConfiguration takes ownership + /// of the given configuration (and the configuration's reference + /// count remains unchanged). + + ConfigPtr find(const std::string& label) const; + /// Finds and returns the configuration with the given label. + /// + /// Returns null if no such configuration can be found. + + //@ deprecated + void addFront(AbstractConfiguration* pConfig); + /// Adds a read-only configuration to the front of the LayeredConfiguration. + /// The LayeredConfiguration does not take ownership of the given + /// configuration. In other words, the configuration's reference + /// count is incremented. + + //@ deprecated + void addFront(AbstractConfiguration* pConfig, bool shared); + /// Adds a read-only configuration to the front of the LayeredConfiguration. + /// If shared is true, the LayeredConfiguration takes ownership + /// of the given configuration. + + void removeConfiguration(AbstractConfiguration* pConfig); + /// Removes the given configuration from the LayeredConfiguration. + /// + /// Does nothing if the given configuration is not part of the + /// LayeredConfiguration. + +protected: + struct ConfigItem + { + ConfigPtr pConfig; + int priority; + bool writeable; + std::string label; + }; + + bool getRaw(const std::string& key, std::string& value) const; + void setRaw(const std::string& key, const std::string& value); + void enumerate(const std::string& key, Keys& range) const; + void removeRaw(const std::string& key); + + int lowest() const; + int highest() const; + void insert(const ConfigItem& item); + + ~LayeredConfiguration(); + +private: + LayeredConfiguration(const LayeredConfiguration&); + LayeredConfiguration& operator = (const LayeredConfiguration&); + + typedef std::list<ConfigItem> ConfigList; + + ConfigList _configs; +}; + + +} } // namespace Poco::Util + + +#endif // Util_LayeredConfiguration_INCLUDED diff --git a/contrib/libs/poco/Util/include/Poco/Util/LoggingConfigurator.h b/contrib/libs/poco/Util/include/Poco/Util/LoggingConfigurator.h index 9e27ecba74..e5ed99aab4 100644 --- a/contrib/libs/poco/Util/include/Poco/Util/LoggingConfigurator.h +++ b/contrib/libs/poco/Util/include/Poco/Util/LoggingConfigurator.h @@ -1,139 +1,139 @@ -// -// LoggingConfigurator.h -// -// Library: Util -// Package: Configuration -// Module: LoggingConfigurator -// -// Definition of the LoggingConfigurator class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// SPDX-License-Identifier: BSL-1.0 -// - - -#ifndef Util_LoggingConfigurator_INCLUDED -#define Util_LoggingConfigurator_INCLUDED - - -#include "Poco/Util/Util.h" -#include "Poco/Formatter.h" -#include "Poco/Channel.h" - - -namespace Poco { -namespace Util { - - -class AbstractConfiguration; - - -class Util_API LoggingConfigurator - /// This utility class uses a configuration object to configure the - /// logging subsystem of an application. +// +// LoggingConfigurator.h +// +// Library: Util +// Package: Configuration +// Module: LoggingConfigurator +// +// Definition of the LoggingConfigurator class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Util_LoggingConfigurator_INCLUDED +#define Util_LoggingConfigurator_INCLUDED + + +#include "Poco/Util/Util.h" +#include "Poco/Formatter.h" +#include "Poco/Channel.h" + + +namespace Poco { +namespace Util { + + +class AbstractConfiguration; + + +class Util_API LoggingConfigurator + /// This utility class uses a configuration object to configure the + /// logging subsystem of an application. + /// + /// The LoggingConfigurator sets up and connects formatters, channels + /// and loggers. To accomplish its work, the LoggingConfigurator relies on the + /// functionality provided by the LoggingFactory and LoggingRegistry classes. + /// + /// The LoggingConfigurator expects all configuration data to be under a root + /// property named "logging". /// - /// The LoggingConfigurator sets up and connects formatters, channels - /// and loggers. To accomplish its work, the LoggingConfigurator relies on the - /// functionality provided by the LoggingFactory and LoggingRegistry classes. + /// Configuring Formatters + /// + /// A formatter is configured using the "logging.formatters" property. Every + /// formatter has an internal name, which is only used for referring to it + /// during configuration time. This name becomes part of the property name. + /// Every formatter has a mandatory "class" property, which specifies the actual + /// class implementing the formatter. Any other properties are passed on to + /// the formatter by calling its setProperty() method. + /// + /// A typical formatter definition looks as follows: + /// logging.formatters.f1.class = PatternFormatter + /// logging.formatters.f1.pattern = %s: [%p] %t + /// logging.formatters.f1.times = UTC + /// + /// Configuring Channels + /// + /// A channel is configured using the "logging.channels" property. Like with + /// Formatters, every channel has an internal name, which is used during + /// configuration only. The name becomes part of the property name. + /// Every channel has a mandatory "class" property, which specifies the actual + /// class implementing the channel. Any other properties are passed on to + /// the formatter by calling its setProperty() method. + /// + /// For convenience, the "formatter" property of a channel is treated + /// specifically. The "formatter" property can either be used to refer to + /// an already defined formatter, or it can be used to specify an "inline" + /// formatter definition. In either case, when a "formatter" property is + /// present, the channel is automatically "wrapped" in a FormattingChannel + /// object. /// - /// The LoggingConfigurator expects all configuration data to be under a root - /// property named "logging". - /// - /// Configuring Formatters + /// Similarly, a channel supports also a "pattern" property, which results + /// in the automatic instantiation of a FormattingChannel object with a + /// connected PatternFormatter. /// - /// A formatter is configured using the "logging.formatters" property. Every - /// formatter has an internal name, which is only used for referring to it - /// during configuration time. This name becomes part of the property name. - /// Every formatter has a mandatory "class" property, which specifies the actual - /// class implementing the formatter. Any other properties are passed on to - /// the formatter by calling its setProperty() method. - /// - /// A typical formatter definition looks as follows: - /// logging.formatters.f1.class = PatternFormatter - /// logging.formatters.f1.pattern = %s: [%p] %t - /// logging.formatters.f1.times = UTC - /// - /// Configuring Channels - /// - /// A channel is configured using the "logging.channels" property. Like with - /// Formatters, every channel has an internal name, which is used during - /// configuration only. The name becomes part of the property name. - /// Every channel has a mandatory "class" property, which specifies the actual - /// class implementing the channel. Any other properties are passed on to - /// the formatter by calling its setProperty() method. - /// - /// For convenience, the "formatter" property of a channel is treated - /// specifically. The "formatter" property can either be used to refer to - /// an already defined formatter, or it can be used to specify an "inline" - /// formatter definition. In either case, when a "formatter" property is - /// present, the channel is automatically "wrapped" in a FormattingChannel - /// object. - /// - /// Similarly, a channel supports also a "pattern" property, which results - /// in the automatic instantiation of a FormattingChannel object with a - /// connected PatternFormatter. - /// - /// Examples: - /// logging.channels.c1.class = ConsoleChannel - /// logging.channels.c1.formatter = f1 - /// logging.channels.c2.class = FileChannel - /// logging.channels.c2.path = ${system.tempDir}/sample.log - /// logging.channels.c2.formatter.class = PatternFormatter - /// logging.channels.c2.formatter.pattern = %s: [%p] %t - /// logging.channels.c3.class = ConsoleChannel - /// logging.channels.c3.pattern = %s: [%p] %t - /// - /// Configuring Loggers - /// - /// A logger is configured using the "logging.loggers" property. Like with - /// channels and formatters, every logger has an internal name, which, however, - /// is only used to ensure the uniqueness of the property names. Note that this - /// name is different from the logger's full name, which is used to access - /// the logger at runtime. - /// Every logger except the root logger has a mandatory "name" property which - /// is used to specify the logger's full name. - /// Furthermore, a "channel" property is supported, which can either refer - /// to a named channel, or which can contain an inline channel definition. - /// - /// Examples: - /// logging.loggers.root.channel = c1 - /// logging.loggers.root.level = warning - /// logging.loggers.l1.name = logger1 - /// logging.loggers.l1.channel.class = ConsoleChannel - /// logging.loggers.l1.channel.pattern = %s: [%p] %t - /// logging.loggers.l1.level = information -{ -public: - LoggingConfigurator(); - /// Creates the LoggingConfigurator. - - ~LoggingConfigurator(); - /// Destroys the LoggingConfigurator. - - void configure(AbstractConfiguration* pConfig); - /// Configures the logging subsystem based on - /// the given configuration. - /// - /// A ConfigurationView can be used to pass only - /// a part of a larger configuration. - -private: - void configureFormatters(AbstractConfiguration* pConfig); - void configureChannels(AbstractConfiguration* pConfig); - void configureLoggers(AbstractConfiguration* pConfig); - Poco::Formatter* createFormatter(AbstractConfiguration* pConfig); - Poco::Channel* createChannel(AbstractConfiguration* pConfig); - void configureChannel(Channel* pChannel, AbstractConfiguration* pConfig); - void configureLogger(AbstractConfiguration* pConfig); - - LoggingConfigurator(const LoggingConfigurator&); - LoggingConfigurator& operator = (const LoggingConfigurator&); -}; - - -} } // namespace Poco::Util - - -#endif // Util_LoggingConfigurator_INCLUDED + /// Examples: + /// logging.channels.c1.class = ConsoleChannel + /// logging.channels.c1.formatter = f1 + /// logging.channels.c2.class = FileChannel + /// logging.channels.c2.path = ${system.tempDir}/sample.log + /// logging.channels.c2.formatter.class = PatternFormatter + /// logging.channels.c2.formatter.pattern = %s: [%p] %t + /// logging.channels.c3.class = ConsoleChannel + /// logging.channels.c3.pattern = %s: [%p] %t + /// + /// Configuring Loggers + /// + /// A logger is configured using the "logging.loggers" property. Like with + /// channels and formatters, every logger has an internal name, which, however, + /// is only used to ensure the uniqueness of the property names. Note that this + /// name is different from the logger's full name, which is used to access + /// the logger at runtime. + /// Every logger except the root logger has a mandatory "name" property which + /// is used to specify the logger's full name. + /// Furthermore, a "channel" property is supported, which can either refer + /// to a named channel, or which can contain an inline channel definition. + /// + /// Examples: + /// logging.loggers.root.channel = c1 + /// logging.loggers.root.level = warning + /// logging.loggers.l1.name = logger1 + /// logging.loggers.l1.channel.class = ConsoleChannel + /// logging.loggers.l1.channel.pattern = %s: [%p] %t + /// logging.loggers.l1.level = information +{ +public: + LoggingConfigurator(); + /// Creates the LoggingConfigurator. + + ~LoggingConfigurator(); + /// Destroys the LoggingConfigurator. + + void configure(AbstractConfiguration* pConfig); + /// Configures the logging subsystem based on + /// the given configuration. + /// + /// A ConfigurationView can be used to pass only + /// a part of a larger configuration. + +private: + void configureFormatters(AbstractConfiguration* pConfig); + void configureChannels(AbstractConfiguration* pConfig); + void configureLoggers(AbstractConfiguration* pConfig); + Poco::Formatter* createFormatter(AbstractConfiguration* pConfig); + Poco::Channel* createChannel(AbstractConfiguration* pConfig); + void configureChannel(Channel* pChannel, AbstractConfiguration* pConfig); + void configureLogger(AbstractConfiguration* pConfig); + + LoggingConfigurator(const LoggingConfigurator&); + LoggingConfigurator& operator = (const LoggingConfigurator&); +}; + + +} } // namespace Poco::Util + + +#endif // Util_LoggingConfigurator_INCLUDED diff --git a/contrib/libs/poco/Util/include/Poco/Util/LoggingSubsystem.h b/contrib/libs/poco/Util/include/Poco/Util/LoggingSubsystem.h index c5476b6eec..53e8c9a8b0 100644 --- a/contrib/libs/poco/Util/include/Poco/Util/LoggingSubsystem.h +++ b/contrib/libs/poco/Util/include/Poco/Util/LoggingSubsystem.h @@ -1,52 +1,52 @@ -// -// LoggingSubsystem.h -// -// Library: Util -// Package: Application -// Module: LoggingSubsystem -// -// Definition of the LoggingSubsystem class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// SPDX-License-Identifier: BSL-1.0 -// - - -#ifndef Util_LoggingSubsystem_INCLUDED -#define Util_LoggingSubsystem_INCLUDED - - -#include "Poco/Util/Util.h" -#include "Poco/Util/Subsystem.h" - - -namespace Poco { -namespace Util { - - -class Util_API LoggingSubsystem: public Subsystem - /// The LoggingSubsystem class initializes the logging - /// framework using the LoggingConfigurator. - /// - /// It also sets the Application's logger to - /// the logger specified by the "application.logger" - /// property, or to "Application" if the property - /// is not specified. -{ -public: - LoggingSubsystem(); - const char* name() const; - -protected: - void initialize(Application& self); - void uninitialize(); - ~LoggingSubsystem(); -}; - - -} } // namespace Poco::Util - - -#endif // Util_LoggingSubsystem_INCLUDED +// +// LoggingSubsystem.h +// +// Library: Util +// Package: Application +// Module: LoggingSubsystem +// +// Definition of the LoggingSubsystem class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Util_LoggingSubsystem_INCLUDED +#define Util_LoggingSubsystem_INCLUDED + + +#include "Poco/Util/Util.h" +#include "Poco/Util/Subsystem.h" + + +namespace Poco { +namespace Util { + + +class Util_API LoggingSubsystem: public Subsystem + /// The LoggingSubsystem class initializes the logging + /// framework using the LoggingConfigurator. + /// + /// It also sets the Application's logger to + /// the logger specified by the "application.logger" + /// property, or to "Application" if the property + /// is not specified. +{ +public: + LoggingSubsystem(); + const char* name() const; + +protected: + void initialize(Application& self); + void uninitialize(); + ~LoggingSubsystem(); +}; + + +} } // namespace Poco::Util + + +#endif // Util_LoggingSubsystem_INCLUDED diff --git a/contrib/libs/poco/Util/include/Poco/Util/MapConfiguration.h b/contrib/libs/poco/Util/include/Poco/Util/MapConfiguration.h index 09ae15a384..ac725cd152 100644 --- a/contrib/libs/poco/Util/include/Poco/Util/MapConfiguration.h +++ b/contrib/libs/poco/Util/include/Poco/Util/MapConfiguration.h @@ -1,64 +1,64 @@ -// -// MapConfiguration.h -// -// Library: Util -// Package: Configuration -// Module: MapConfiguration -// -// Definition of the MapConfiguration class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// SPDX-License-Identifier: BSL-1.0 -// - - -#ifndef Util_MapConfiguration_INCLUDED -#define Util_MapConfiguration_INCLUDED - - -#include "Poco/Util/Util.h" -#include "Poco/Util/AbstractConfiguration.h" -#include <map> - - -namespace Poco { -namespace Util { - - -class Util_API MapConfiguration: public AbstractConfiguration - /// An implementation of AbstractConfiguration that stores configuration data in a map. -{ -public: - MapConfiguration(); - /// Creates an empty MapConfiguration. - - void copyTo(AbstractConfiguration& config); - /// Copies all configuration properties to the given configuration. - - void clear(); - /// Clears the configuration. - -protected: - typedef std::map<std::string, std::string> StringMap; - typedef StringMap::const_iterator iterator; - - bool getRaw(const std::string& key, std::string& value) const; - void setRaw(const std::string& key, const std::string& value); - void enumerate(const std::string& key, Keys& range) const; - void removeRaw(const std::string& key); - ~MapConfiguration(); - - iterator begin() const; - iterator end() const; - -private: - StringMap _map; -}; - - -} } // namespace Poco::Util - - -#endif // Util_MapConfiguration_INCLUDED +// +// MapConfiguration.h +// +// Library: Util +// Package: Configuration +// Module: MapConfiguration +// +// Definition of the MapConfiguration class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Util_MapConfiguration_INCLUDED +#define Util_MapConfiguration_INCLUDED + + +#include "Poco/Util/Util.h" +#include "Poco/Util/AbstractConfiguration.h" +#include <map> + + +namespace Poco { +namespace Util { + + +class Util_API MapConfiguration: public AbstractConfiguration + /// An implementation of AbstractConfiguration that stores configuration data in a map. +{ +public: + MapConfiguration(); + /// Creates an empty MapConfiguration. + + void copyTo(AbstractConfiguration& config); + /// Copies all configuration properties to the given configuration. + + void clear(); + /// Clears the configuration. + +protected: + typedef std::map<std::string, std::string> StringMap; + typedef StringMap::const_iterator iterator; + + bool getRaw(const std::string& key, std::string& value) const; + void setRaw(const std::string& key, const std::string& value); + void enumerate(const std::string& key, Keys& range) const; + void removeRaw(const std::string& key); + ~MapConfiguration(); + + iterator begin() const; + iterator end() const; + +private: + StringMap _map; +}; + + +} } // namespace Poco::Util + + +#endif // Util_MapConfiguration_INCLUDED diff --git a/contrib/libs/poco/Util/include/Poco/Util/Option.h b/contrib/libs/poco/Util/include/Poco/Util/Option.h index eae7ca2812..051f7c0094 100644 --- a/contrib/libs/poco/Util/include/Poco/Util/Option.h +++ b/contrib/libs/poco/Util/include/Poco/Util/Option.h @@ -1,332 +1,332 @@ -// -// Option.h -// -// Library: Util -// Package: Options -// Module: Option -// -// Definition of the Option class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// SPDX-License-Identifier: BSL-1.0 -// - - -#ifndef Util_Option_INCLUDED -#define Util_Option_INCLUDED - - -#include "Poco/Util/Util.h" -#include "Poco/Util/OptionCallback.h" - - -namespace Poco { -namespace Util { - - -class Application; -class Validator; -class AbstractConfiguration; - - -class Util_API Option - /// This class represents and stores the properties - /// of a command line option. - /// - /// An option has a full name, an optional short name, - /// a description (used for printing a usage statement), - /// and an optional argument name. - /// An option can be optional or required. - /// An option can be repeatable, which means that it can - /// be given more than once on the command line. - /// - /// An option can be part of an option group. At most one - /// option of each group may be specified on the command - /// line. - /// - /// An option can be bound to a configuration property. - /// In this case, a configuration property will automatically - /// receive the option's argument value. - /// - /// A callback method can be specified for options. This method - /// is called whenever an option is specified on the command line. - /// - /// Option argument values can be automatically validated using a - /// Validator. - /// - /// Option instances are value objects. - /// - /// Typically, after construction, an Option object is immediately - /// passed to an Options object. - /// - /// An Option object can be created by chaining the constructor - /// with any of the setter methods, as in the following example: - /// - /// Option versionOpt("include", "I", "specify an include directory") - /// .required(false) - /// .repeatable(true) - /// .argument("directory"); -{ -public: - Option(); - /// Creates an empty Option. - - Option(const Option& option); - /// Creates an option from another one. - - Option(const std::string& fullName, const std::string& shortName); - /// Creates an option with the given properties. - - Option(const std::string& fullName, const std::string& shortName, const std::string& description, bool required = false); - /// Creates an option with the given properties. - - Option(const std::string& fullName, const std::string& shortName, const std::string& description, bool required, const std::string& argName, bool argRequired = false); - /// Creates an option with the given properties. - - ~Option(); - /// Destroys the Option. - - Option& operator = (const Option& option); - /// Assignment operator. - - void swap(Option& option); - /// Swaps the option with another one. - - Option& shortName(const std::string& name); - /// Sets the short name of the option. - - Option& fullName(const std::string& name); - /// Sets the full name of the option. - - Option& description(const std::string& text); - /// Sets the description of the option. - - Option& required(bool flag); - /// Sets whether the option is required (flag == true) - /// or optional (flag == false). - - Option& repeatable(bool flag); - /// Sets whether the option can be specified more than once - /// (flag == true) or at most once (flag == false). - - Option& argument(const std::string& name, bool required = true); - /// Specifies that the option takes an (optional or required) - /// argument. - - Option& noArgument(); - /// Specifies that the option does not take an argument (default). - - Option& group(const std::string& group); - /// Specifies the option group the option is part of. - - Option& binding(const std::string& propertyName); - /// Binds the option to the configuration property with the given name. - /// - /// The configuration will automatically receive the option's argument. - - Option& binding(const std::string& propertyName, AbstractConfiguration* pConfig); - /// Binds the option to the configuration property with the given name, - /// using the given AbstractConfiguration. - /// - /// The configuration will automatically receive the option's argument. - - Option& callback(const AbstractOptionCallback& cb); - /// Binds the option to the given method. - /// - /// The callback method will be called when the option - /// has been specified on the command line. - /// - /// Usage: - /// callback(OptionCallback<MyApplication>(this, &MyApplication::myCallback)); - - Option& validator(Validator* pValidator); - /// Sets the validator for the given option. - /// - /// The Option takes ownership of the Validator and - /// deletes it when it's no longer needed. - - const std::string& shortName() const; - /// Returns the short name of the option. - - const std::string& fullName() const; - /// Returns the full name of the option. - - const std::string& description() const; - /// Returns the description of the option. - - bool required() const; - /// Returns true if the option is required, false if not. - - bool repeatable() const; - /// Returns true if the option can be specified more than - /// once, or false if at most once. - - bool takesArgument() const; - /// Returns true if the options takes an (optional) argument. - - bool argumentRequired() const; - /// Returns true if the argument is required. - - const std::string& argumentName() const; - /// Returns the argument name, if specified. - - const std::string& group() const; - /// Returns the option group the option is part of, - /// or an empty string, if the option is not part of - /// a group. - - const std::string& binding() const; - /// Returns the property name the option is bound to, - /// or an empty string in case it is not bound. - - AbstractOptionCallback* callback() const; - /// Returns a pointer to the callback method for the option, - /// or NULL if no callback has been specified. - - Validator* validator() const; - /// Returns the option's Validator, if one has been specified, - /// or NULL otherwise. - - AbstractConfiguration* config() const; - /// Returns the configuration, if specified, or NULL otherwise. - - bool matchesShort(const std::string& option) const; - /// Returns true if the given option string matches the - /// short name. - /// - /// The first characters of the option string must match - /// the short name of the option (case sensitive), - /// or the option string must partially match the full - /// name (case insensitive). - - bool matchesFull(const std::string& option) const; - /// Returns true if the given option string matches the - /// full name. - /// - /// The option string must match the full - /// name (case insensitive). - - bool matchesPartial(const std::string& option) const; - /// Returns true if the given option string partially matches the - /// full name. - /// - /// The option string must partially match the full - /// name (case insensitive). - - void process(const std::string& option, std::string& arg) const; - /// Verifies that the given option string matches the - /// requirements of the option, and extracts the option argument, - /// if present. - /// - /// If the option string is okay and carries an argument, - /// the argument is returned in arg. - /// - /// Throws a MissingArgumentException if a required argument - /// is missing. Throws an UnexpectedArgumentException if an - /// argument has been found, but none is expected. - -private: - std::string _shortName; - std::string _fullName; - std::string _description; - bool _required; - bool _repeatable; - std::string _argName; - bool _argRequired; - std::string _group; - std::string _binding; - Validator* _pValidator; - AbstractOptionCallback* _pCallback; - AbstractConfiguration* _pConfig; -}; - - -// -// inlines -// - - -inline const std::string& Option::shortName() const -{ - return _shortName; -} - - -inline const std::string& Option::fullName() const -{ - return _fullName; -} - - -inline const std::string& Option::description() const -{ - return _description; -} - - -inline bool Option::required() const -{ - return _required; -} - - -inline bool Option::repeatable() const -{ - return _repeatable; -} - - -inline bool Option::takesArgument() const -{ - return !_argName.empty(); -} - - -inline bool Option::argumentRequired() const -{ - return _argRequired; -} - - -inline const std::string& Option::argumentName() const -{ - return _argName; -} - - -inline const std::string& Option::group() const -{ - return _group; -} - - -inline const std::string& Option::binding() const -{ - return _binding; -} - - -inline AbstractOptionCallback* Option::callback() const -{ - return _pCallback; -} - - -inline Validator* Option::validator() const -{ - return _pValidator; -} - - -inline AbstractConfiguration* Option::config() const -{ - return _pConfig; -} - - -} } // namespace Poco::Util - - -#endif // Util_Option_INCLUDED +// +// Option.h +// +// Library: Util +// Package: Options +// Module: Option +// +// Definition of the Option class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Util_Option_INCLUDED +#define Util_Option_INCLUDED + + +#include "Poco/Util/Util.h" +#include "Poco/Util/OptionCallback.h" + + +namespace Poco { +namespace Util { + + +class Application; +class Validator; +class AbstractConfiguration; + + +class Util_API Option + /// This class represents and stores the properties + /// of a command line option. + /// + /// An option has a full name, an optional short name, + /// a description (used for printing a usage statement), + /// and an optional argument name. + /// An option can be optional or required. + /// An option can be repeatable, which means that it can + /// be given more than once on the command line. + /// + /// An option can be part of an option group. At most one + /// option of each group may be specified on the command + /// line. + /// + /// An option can be bound to a configuration property. + /// In this case, a configuration property will automatically + /// receive the option's argument value. + /// + /// A callback method can be specified for options. This method + /// is called whenever an option is specified on the command line. + /// + /// Option argument values can be automatically validated using a + /// Validator. + /// + /// Option instances are value objects. + /// + /// Typically, after construction, an Option object is immediately + /// passed to an Options object. + /// + /// An Option object can be created by chaining the constructor + /// with any of the setter methods, as in the following example: + /// + /// Option versionOpt("include", "I", "specify an include directory") + /// .required(false) + /// .repeatable(true) + /// .argument("directory"); +{ +public: + Option(); + /// Creates an empty Option. + + Option(const Option& option); + /// Creates an option from another one. + + Option(const std::string& fullName, const std::string& shortName); + /// Creates an option with the given properties. + + Option(const std::string& fullName, const std::string& shortName, const std::string& description, bool required = false); + /// Creates an option with the given properties. + + Option(const std::string& fullName, const std::string& shortName, const std::string& description, bool required, const std::string& argName, bool argRequired = false); + /// Creates an option with the given properties. + + ~Option(); + /// Destroys the Option. + + Option& operator = (const Option& option); + /// Assignment operator. + + void swap(Option& option); + /// Swaps the option with another one. + + Option& shortName(const std::string& name); + /// Sets the short name of the option. + + Option& fullName(const std::string& name); + /// Sets the full name of the option. + + Option& description(const std::string& text); + /// Sets the description of the option. + + Option& required(bool flag); + /// Sets whether the option is required (flag == true) + /// or optional (flag == false). + + Option& repeatable(bool flag); + /// Sets whether the option can be specified more than once + /// (flag == true) or at most once (flag == false). + + Option& argument(const std::string& name, bool required = true); + /// Specifies that the option takes an (optional or required) + /// argument. + + Option& noArgument(); + /// Specifies that the option does not take an argument (default). + + Option& group(const std::string& group); + /// Specifies the option group the option is part of. + + Option& binding(const std::string& propertyName); + /// Binds the option to the configuration property with the given name. + /// + /// The configuration will automatically receive the option's argument. + + Option& binding(const std::string& propertyName, AbstractConfiguration* pConfig); + /// Binds the option to the configuration property with the given name, + /// using the given AbstractConfiguration. + /// + /// The configuration will automatically receive the option's argument. + + Option& callback(const AbstractOptionCallback& cb); + /// Binds the option to the given method. + /// + /// The callback method will be called when the option + /// has been specified on the command line. + /// + /// Usage: + /// callback(OptionCallback<MyApplication>(this, &MyApplication::myCallback)); + + Option& validator(Validator* pValidator); + /// Sets the validator for the given option. + /// + /// The Option takes ownership of the Validator and + /// deletes it when it's no longer needed. + + const std::string& shortName() const; + /// Returns the short name of the option. + + const std::string& fullName() const; + /// Returns the full name of the option. + + const std::string& description() const; + /// Returns the description of the option. + + bool required() const; + /// Returns true if the option is required, false if not. + + bool repeatable() const; + /// Returns true if the option can be specified more than + /// once, or false if at most once. + + bool takesArgument() const; + /// Returns true if the options takes an (optional) argument. + + bool argumentRequired() const; + /// Returns true if the argument is required. + + const std::string& argumentName() const; + /// Returns the argument name, if specified. + + const std::string& group() const; + /// Returns the option group the option is part of, + /// or an empty string, if the option is not part of + /// a group. + + const std::string& binding() const; + /// Returns the property name the option is bound to, + /// or an empty string in case it is not bound. + + AbstractOptionCallback* callback() const; + /// Returns a pointer to the callback method for the option, + /// or NULL if no callback has been specified. + + Validator* validator() const; + /// Returns the option's Validator, if one has been specified, + /// or NULL otherwise. + + AbstractConfiguration* config() const; + /// Returns the configuration, if specified, or NULL otherwise. + + bool matchesShort(const std::string& option) const; + /// Returns true if the given option string matches the + /// short name. + /// + /// The first characters of the option string must match + /// the short name of the option (case sensitive), + /// or the option string must partially match the full + /// name (case insensitive). + + bool matchesFull(const std::string& option) const; + /// Returns true if the given option string matches the + /// full name. + /// + /// The option string must match the full + /// name (case insensitive). + + bool matchesPartial(const std::string& option) const; + /// Returns true if the given option string partially matches the + /// full name. + /// + /// The option string must partially match the full + /// name (case insensitive). + + void process(const std::string& option, std::string& arg) const; + /// Verifies that the given option string matches the + /// requirements of the option, and extracts the option argument, + /// if present. + /// + /// If the option string is okay and carries an argument, + /// the argument is returned in arg. + /// + /// Throws a MissingArgumentException if a required argument + /// is missing. Throws an UnexpectedArgumentException if an + /// argument has been found, but none is expected. + +private: + std::string _shortName; + std::string _fullName; + std::string _description; + bool _required; + bool _repeatable; + std::string _argName; + bool _argRequired; + std::string _group; + std::string _binding; + Validator* _pValidator; + AbstractOptionCallback* _pCallback; + AbstractConfiguration* _pConfig; +}; + + +// +// inlines +// + + +inline const std::string& Option::shortName() const +{ + return _shortName; +} + + +inline const std::string& Option::fullName() const +{ + return _fullName; +} + + +inline const std::string& Option::description() const +{ + return _description; +} + + +inline bool Option::required() const +{ + return _required; +} + + +inline bool Option::repeatable() const +{ + return _repeatable; +} + + +inline bool Option::takesArgument() const +{ + return !_argName.empty(); +} + + +inline bool Option::argumentRequired() const +{ + return _argRequired; +} + + +inline const std::string& Option::argumentName() const +{ + return _argName; +} + + +inline const std::string& Option::group() const +{ + return _group; +} + + +inline const std::string& Option::binding() const +{ + return _binding; +} + + +inline AbstractOptionCallback* Option::callback() const +{ + return _pCallback; +} + + +inline Validator* Option::validator() const +{ + return _pValidator; +} + + +inline AbstractConfiguration* Option::config() const +{ + return _pConfig; +} + + +} } // namespace Poco::Util + + +#endif // Util_Option_INCLUDED diff --git a/contrib/libs/poco/Util/include/Poco/Util/OptionCallback.h b/contrib/libs/poco/Util/include/Poco/Util/OptionCallback.h index e5b1b3fed8..63dd4a30e4 100644 --- a/contrib/libs/poco/Util/include/Poco/Util/OptionCallback.h +++ b/contrib/libs/poco/Util/include/Poco/Util/OptionCallback.h @@ -1,109 +1,109 @@ -// -// OptionCallback.h -// -// Library: Util -// Package: Options -// Module: OptionCallback -// -// Definition of the OptionCallback class. -// -// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// SPDX-License-Identifier: BSL-1.0 -// - - -#ifndef Util_OptionCallback_INCLUDED -#define Util_OptionCallback_INCLUDED - - -#include "Poco/Util/Util.h" - - -namespace Poco { -namespace Util { - - -class Util_API AbstractOptionCallback - /// Base class for OptionCallback. -{ -public: - virtual void invoke(const std::string& name, const std::string& value) const = 0; - /// Invokes the callback member function. - - virtual AbstractOptionCallback* clone() const = 0; - /// Creates and returns a copy of the object. - - virtual ~AbstractOptionCallback(); - /// Destroys the AbstractOptionCallback. - -protected: - AbstractOptionCallback(); - AbstractOptionCallback(const AbstractOptionCallback&); -}; - - -template <class C> -class OptionCallback: public AbstractOptionCallback - /// This class is used as an argument to Option::callback(). - /// - /// It stores a pointer to an object and a pointer to a member - /// function of the object's class. -{ -public: - typedef void (C::*Callback)(const std::string& name, const std::string& value); - - OptionCallback(C* pObject, Callback method): - _pObject(pObject), - _method(method) - /// Creates the OptionCallback for the given object and member function. - { - poco_check_ptr (pObject); - } - - OptionCallback(const OptionCallback& cb): - AbstractOptionCallback(cb), - _pObject(cb._pObject), - _method(cb._method) - /// Creates an OptionCallback from another one. - { - } - - ~OptionCallback() - /// Destroys the OptionCallback. - { - } - - OptionCallback& operator = (const OptionCallback& cb) - { - if (&cb != this) - { - this->_pObject = cb._pObject; - this->_method = cb._method; - } - return *this; - } - - void invoke(const std::string& name, const std::string& value) const - { - (_pObject->*_method)(name, value); - } - - AbstractOptionCallback* clone() const - { - return new OptionCallback(_pObject, _method); - } - -private: - OptionCallback(); - - C* _pObject; - Callback _method; -}; - - -} } // namespace Poco::Util - - -#endif // Util_OptionCallback_INCLUDED +// +// OptionCallback.h +// +// Library: Util +// Package: Options +// Module: OptionCallback +// +// Definition of the OptionCallback class. +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Util_OptionCallback_INCLUDED +#define Util_OptionCallback_INCLUDED + + +#include "Poco/Util/Util.h" + + +namespace Poco { +namespace Util { + + +class Util_API AbstractOptionCallback + /// Base class for OptionCallback. +{ +public: + virtual void invoke(const std::string& name, const std::string& value) const = 0; + /// Invokes the callback member function. + + virtual AbstractOptionCallback* clone() const = 0; + /// Creates and returns a copy of the object. + + virtual ~AbstractOptionCallback(); + /// Destroys the AbstractOptionCallback. + +protected: + AbstractOptionCallback(); + AbstractOptionCallback(const AbstractOptionCallback&); +}; + + +template <class C> +class OptionCallback: public AbstractOptionCallback + /// This class is used as an argument to Option::callback(). + /// + /// It stores a pointer to an object and a pointer to a member + /// function of the object's class. +{ +public: + typedef void (C::*Callback)(const std::string& name, const std::string& value); + + OptionCallback(C* pObject, Callback method): + _pObject(pObject), + _method(method) + /// Creates the OptionCallback for the given object and member function. + { + poco_check_ptr (pObject); + } + + OptionCallback(const OptionCallback& cb): + AbstractOptionCallback(cb), + _pObject(cb._pObject), + _method(cb._method) + /// Creates an OptionCallback from another one. + { + } + + ~OptionCallback() + /// Destroys the OptionCallback. + { + } + + OptionCallback& operator = (const OptionCallback& cb) + { + if (&cb != this) + { + this->_pObject = cb._pObject; + this->_method = cb._method; + } + return *this; + } + + void invoke(const std::string& name, const std::string& value) const + { + (_pObject->*_method)(name, value); + } + + AbstractOptionCallback* clone() const + { + return new OptionCallback(_pObject, _method); + } + +private: + OptionCallback(); + + C* _pObject; + Callback _method; +}; + + +} } // namespace Poco::Util + + +#endif // Util_OptionCallback_INCLUDED diff --git a/contrib/libs/poco/Util/include/Poco/Util/OptionException.h b/contrib/libs/poco/Util/include/Poco/Util/OptionException.h index 848ef44000..35e7bff1d3 100644 --- a/contrib/libs/poco/Util/include/Poco/Util/OptionException.h +++ b/contrib/libs/poco/Util/include/Poco/Util/OptionException.h @@ -1,44 +1,44 @@ -// -// OptionException.h -// -// Library: Util -// Package: Options -// Module: OptionException -// -// Definition of the OptionException class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// SPDX-License-Identifier: BSL-1.0 -// - - -#ifndef Util_OptionException_INCLUDED -#define Util_OptionException_INCLUDED - - -#include "Poco/Util/Util.h" -#include "Poco/Exception.h" - - -namespace Poco { -namespace Util { - - -POCO_DECLARE_EXCEPTION(Util_API, OptionException, Poco::DataException) -POCO_DECLARE_EXCEPTION(Util_API, UnknownOptionException, OptionException) -POCO_DECLARE_EXCEPTION(Util_API, AmbiguousOptionException, OptionException) -POCO_DECLARE_EXCEPTION(Util_API, MissingOptionException, OptionException) -POCO_DECLARE_EXCEPTION(Util_API, MissingArgumentException, OptionException) -POCO_DECLARE_EXCEPTION(Util_API, InvalidArgumentException, OptionException) -POCO_DECLARE_EXCEPTION(Util_API, UnexpectedArgumentException, OptionException) -POCO_DECLARE_EXCEPTION(Util_API, IncompatibleOptionsException, OptionException) -POCO_DECLARE_EXCEPTION(Util_API, DuplicateOptionException, OptionException) -POCO_DECLARE_EXCEPTION(Util_API, EmptyOptionException, OptionException) - - -} } // namespace Poco::Util - - -#endif // Util_OptionException_INCLUDED +// +// OptionException.h +// +// Library: Util +// Package: Options +// Module: OptionException +// +// Definition of the OptionException class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Util_OptionException_INCLUDED +#define Util_OptionException_INCLUDED + + +#include "Poco/Util/Util.h" +#include "Poco/Exception.h" + + +namespace Poco { +namespace Util { + + +POCO_DECLARE_EXCEPTION(Util_API, OptionException, Poco::DataException) +POCO_DECLARE_EXCEPTION(Util_API, UnknownOptionException, OptionException) +POCO_DECLARE_EXCEPTION(Util_API, AmbiguousOptionException, OptionException) +POCO_DECLARE_EXCEPTION(Util_API, MissingOptionException, OptionException) +POCO_DECLARE_EXCEPTION(Util_API, MissingArgumentException, OptionException) +POCO_DECLARE_EXCEPTION(Util_API, InvalidArgumentException, OptionException) +POCO_DECLARE_EXCEPTION(Util_API, UnexpectedArgumentException, OptionException) +POCO_DECLARE_EXCEPTION(Util_API, IncompatibleOptionsException, OptionException) +POCO_DECLARE_EXCEPTION(Util_API, DuplicateOptionException, OptionException) +POCO_DECLARE_EXCEPTION(Util_API, EmptyOptionException, OptionException) + + +} } // namespace Poco::Util + + +#endif // Util_OptionException_INCLUDED diff --git a/contrib/libs/poco/Util/include/Poco/Util/OptionProcessor.h b/contrib/libs/poco/Util/include/Poco/Util/OptionProcessor.h index b015e5d882..47e5eb873c 100644 --- a/contrib/libs/poco/Util/include/Poco/Util/OptionProcessor.h +++ b/contrib/libs/poco/Util/include/Poco/Util/OptionProcessor.h @@ -1,137 +1,137 @@ -// -// OptionProcessor.h -// -// Library: Util -// Package: Options -// Module: OptionProcessor -// -// Definition of the OptionProcessor class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// SPDX-License-Identifier: BSL-1.0 -// - - -#ifndef Util_OptionProcessor_INCLUDED -#define Util_OptionProcessor_INCLUDED - - -#include "Poco/Util/Util.h" -#include <set> - - -namespace Poco { -namespace Util { - - -class OptionSet; - - -class Util_API OptionProcessor - /// An OptionProcessor is used to process the command line - /// arguments of an application. - /// - /// The process() method takes an argument from the command line. - /// If that argument starts with an option prefix, the argument - /// is further processed. Otherwise, the argument is ignored and - /// false is returned. The argument must match one of the options - /// given in the OptionSet that is passed to the OptionProcessor - /// with the constructor. If an option is part of a group, at most - /// one option of the group can be passed to the OptionProcessor. - /// Otherwise an IncompatibleOptionsException is thrown. - /// If the same option is given multiple times, but the option - /// is not repeatable, a DuplicateOptionException is thrown. - /// If the option is not recognized, a UnexpectedArgumentException - /// is thrown. - /// If the option requires an argument, but none is given, an - /// MissingArgumentException is thrown. - /// If no argument is expected, but one is present, a - /// UnexpectedArgumentException is thrown. - /// If a partial option name is ambiguous, an AmbiguousOptionException - /// is thrown. - /// - /// The OptionProcessor supports two modes: Unix mode and default mode. - /// In Unix mode, the option prefix is a dash '-'. A dash must be followed - /// by a short option name, or another dash, followed by a (partial) - /// long option name. - /// In default mode, the option prefix is a slash '/', followed by - /// a (partial) long option name. - /// If the special option '--' is encountered in Unix mode, all following - /// options are ignored. - /// - /// Option arguments can be specified in three ways. If a Unix short option - /// ("-o") is given, the argument directly follows the option name, without - /// any delimiting character or space ("-ovalue"). In default option mode, or if a - /// Unix long option ("--option") is given, the option argument is - /// delimited from the option name with either an equal sign ('=') or - /// a colon (':'), as in "--option=value" or "/option:value". Finally, - /// a required option argument can be specified on the command line after the - /// option, delimited with a space, as in "--option value" or "-o value". - /// The latter only works for required option arguments, not optional ones. -{ -public: - OptionProcessor(const OptionSet& options); - /// Creates the OptionProcessor, using the given OptionSet. - - ~OptionProcessor(); - /// Destroys the OptionProcessor. - - void setUnixStyle(bool flag); - /// Enables (flag == true) or disables (flag == false) Unix-style - /// option processing. - /// - /// If Unix-style processing is enabled, options are expected to - /// begin with a single or a double dash ('-' or '--', respectively). - /// A single dash must be followed by a short option name. A double - /// dash must be followed by a (partial) full option name. - /// - /// If Unix-style processing is disabled, options are expected to - /// begin with a slash ('/'), followed by a (partial) full option name. - - bool isUnixStyle() const; - /// Returns true iff Unix-style option processing is enabled. - - bool process(const std::string& argument, std::string& optionName, std::string& optionArg); - /// Examines and processes the given command line argument. - /// - /// If the argument begins with an option prefix, the option is processed - /// and true is returned. The full option name is stored in optionName and the - /// option argument, if present, is stored in optionArg. - /// - /// If the option does not begin with an option prefix, false is returned. - - void checkRequired() const; - /// Checks if all required options have been processed. - /// - /// Does nothing if all required options have been processed. - /// Throws a MissingOptionException otherwise. - -private: - bool processUnix(const std::string& argument, std::string& optionName, std::string& optionArg); - bool processDefault(const std::string& argument, std::string& optionName, std::string& optionArg); - bool processCommon(const std::string& option, bool isShort, std::string& optionName, std::string& optionArg); - - const OptionSet& _options; - bool _unixStyle; - bool _ignore; - std::set<std::string> _groups; - std::set<std::string> _specifiedOptions; - std::string _deferredOption; -}; - - -// -// inlines -// -inline bool OptionProcessor::isUnixStyle() const -{ - return _unixStyle; -} - - -} } // namespace Poco::Util - - -#endif // Util_OptionProcessor_INCLUDED +// +// OptionProcessor.h +// +// Library: Util +// Package: Options +// Module: OptionProcessor +// +// Definition of the OptionProcessor class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Util_OptionProcessor_INCLUDED +#define Util_OptionProcessor_INCLUDED + + +#include "Poco/Util/Util.h" +#include <set> + + +namespace Poco { +namespace Util { + + +class OptionSet; + + +class Util_API OptionProcessor + /// An OptionProcessor is used to process the command line + /// arguments of an application. + /// + /// The process() method takes an argument from the command line. + /// If that argument starts with an option prefix, the argument + /// is further processed. Otherwise, the argument is ignored and + /// false is returned. The argument must match one of the options + /// given in the OptionSet that is passed to the OptionProcessor + /// with the constructor. If an option is part of a group, at most + /// one option of the group can be passed to the OptionProcessor. + /// Otherwise an IncompatibleOptionsException is thrown. + /// If the same option is given multiple times, but the option + /// is not repeatable, a DuplicateOptionException is thrown. + /// If the option is not recognized, a UnexpectedArgumentException + /// is thrown. + /// If the option requires an argument, but none is given, an + /// MissingArgumentException is thrown. + /// If no argument is expected, but one is present, a + /// UnexpectedArgumentException is thrown. + /// If a partial option name is ambiguous, an AmbiguousOptionException + /// is thrown. + /// + /// The OptionProcessor supports two modes: Unix mode and default mode. + /// In Unix mode, the option prefix is a dash '-'. A dash must be followed + /// by a short option name, or another dash, followed by a (partial) + /// long option name. + /// In default mode, the option prefix is a slash '/', followed by + /// a (partial) long option name. + /// If the special option '--' is encountered in Unix mode, all following + /// options are ignored. + /// + /// Option arguments can be specified in three ways. If a Unix short option + /// ("-o") is given, the argument directly follows the option name, without + /// any delimiting character or space ("-ovalue"). In default option mode, or if a + /// Unix long option ("--option") is given, the option argument is + /// delimited from the option name with either an equal sign ('=') or + /// a colon (':'), as in "--option=value" or "/option:value". Finally, + /// a required option argument can be specified on the command line after the + /// option, delimited with a space, as in "--option value" or "-o value". + /// The latter only works for required option arguments, not optional ones. +{ +public: + OptionProcessor(const OptionSet& options); + /// Creates the OptionProcessor, using the given OptionSet. + + ~OptionProcessor(); + /// Destroys the OptionProcessor. + + void setUnixStyle(bool flag); + /// Enables (flag == true) or disables (flag == false) Unix-style + /// option processing. + /// + /// If Unix-style processing is enabled, options are expected to + /// begin with a single or a double dash ('-' or '--', respectively). + /// A single dash must be followed by a short option name. A double + /// dash must be followed by a (partial) full option name. + /// + /// If Unix-style processing is disabled, options are expected to + /// begin with a slash ('/'), followed by a (partial) full option name. + + bool isUnixStyle() const; + /// Returns true iff Unix-style option processing is enabled. + + bool process(const std::string& argument, std::string& optionName, std::string& optionArg); + /// Examines and processes the given command line argument. + /// + /// If the argument begins with an option prefix, the option is processed + /// and true is returned. The full option name is stored in optionName and the + /// option argument, if present, is stored in optionArg. + /// + /// If the option does not begin with an option prefix, false is returned. + + void checkRequired() const; + /// Checks if all required options have been processed. + /// + /// Does nothing if all required options have been processed. + /// Throws a MissingOptionException otherwise. + +private: + bool processUnix(const std::string& argument, std::string& optionName, std::string& optionArg); + bool processDefault(const std::string& argument, std::string& optionName, std::string& optionArg); + bool processCommon(const std::string& option, bool isShort, std::string& optionName, std::string& optionArg); + + const OptionSet& _options; + bool _unixStyle; + bool _ignore; + std::set<std::string> _groups; + std::set<std::string> _specifiedOptions; + std::string _deferredOption; +}; + + +// +// inlines +// +inline bool OptionProcessor::isUnixStyle() const +{ + return _unixStyle; +} + + +} } // namespace Poco::Util + + +#endif // Util_OptionProcessor_INCLUDED diff --git a/contrib/libs/poco/Util/include/Poco/Util/OptionSet.h b/contrib/libs/poco/Util/include/Poco/Util/OptionSet.h index 00c76263d3..31e36fe7db 100644 --- a/contrib/libs/poco/Util/include/Poco/Util/OptionSet.h +++ b/contrib/libs/poco/Util/include/Poco/Util/OptionSet.h @@ -1,88 +1,88 @@ -// -// OptionSet.h -// -// Library: Util -// Package: Options -// Module: OptionSet -// -// Definition of the OptionSet class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// SPDX-License-Identifier: BSL-1.0 -// - - -#ifndef Util_OptionSet_INCLUDED -#define Util_OptionSet_INCLUDED - - -#include "Poco/Util/Util.h" -#include "Poco/Util/Option.h" -#include <vector> - - -namespace Poco { -namespace Util { - - -class Util_API OptionSet - /// A collection of Option objects. -{ -public: - typedef std::vector<Option> OptionVec; - typedef OptionVec::const_iterator Iterator; - - OptionSet(); - /// Creates the OptionSet. - - OptionSet(const OptionSet& options); - /// Creates an option set from another one. - - ~OptionSet(); - /// Destroys the OptionSet. - - OptionSet& operator = (const OptionSet& options); - /// Assignment operator. - - void addOption(const Option& option); - /// Adds an option to the collection. - - bool hasOption(const std::string& name, bool matchShort = false) const; - /// Returns a true iff an option with the given name exists. - /// - /// The given name can either be a fully specified short name, - /// or a partially specified full name. If a partial name - /// matches more than one full name, false is returned. - /// The name must either match the short or full name of an - /// option. Comparison case sensitive for the short name and - /// not case sensitive for the full name. - - const Option& getOption(const std::string& name, bool matchShort = false) const; - /// Returns a reference to the option with the given name. - /// - /// The given name can either be a fully specified short name, - /// or a partially specified full name. - /// The name must either match the short or full name of an - /// option. Comparison case sensitive for the short name and - /// not case sensitive for the full name. - /// Throws a NotFoundException if no matching option has been found. - /// Throws an UnknownOptionException if a partial full name matches - /// more than one option. - - Iterator begin() const; - /// Supports iterating over all options. - - Iterator end() const; - /// Supports iterating over all options. - -private: - OptionVec _options; -}; - - -} } // namespace Poco::Util - - -#endif // Util_OptionSet_INCLUDED +// +// OptionSet.h +// +// Library: Util +// Package: Options +// Module: OptionSet +// +// Definition of the OptionSet class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Util_OptionSet_INCLUDED +#define Util_OptionSet_INCLUDED + + +#include "Poco/Util/Util.h" +#include "Poco/Util/Option.h" +#include <vector> + + +namespace Poco { +namespace Util { + + +class Util_API OptionSet + /// A collection of Option objects. +{ +public: + typedef std::vector<Option> OptionVec; + typedef OptionVec::const_iterator Iterator; + + OptionSet(); + /// Creates the OptionSet. + + OptionSet(const OptionSet& options); + /// Creates an option set from another one. + + ~OptionSet(); + /// Destroys the OptionSet. + + OptionSet& operator = (const OptionSet& options); + /// Assignment operator. + + void addOption(const Option& option); + /// Adds an option to the collection. + + bool hasOption(const std::string& name, bool matchShort = false) const; + /// Returns a true iff an option with the given name exists. + /// + /// The given name can either be a fully specified short name, + /// or a partially specified full name. If a partial name + /// matches more than one full name, false is returned. + /// The name must either match the short or full name of an + /// option. Comparison case sensitive for the short name and + /// not case sensitive for the full name. + + const Option& getOption(const std::string& name, bool matchShort = false) const; + /// Returns a reference to the option with the given name. + /// + /// The given name can either be a fully specified short name, + /// or a partially specified full name. + /// The name must either match the short or full name of an + /// option. Comparison case sensitive for the short name and + /// not case sensitive for the full name. + /// Throws a NotFoundException if no matching option has been found. + /// Throws an UnknownOptionException if a partial full name matches + /// more than one option. + + Iterator begin() const; + /// Supports iterating over all options. + + Iterator end() const; + /// Supports iterating over all options. + +private: + OptionVec _options; +}; + + +} } // namespace Poco::Util + + +#endif // Util_OptionSet_INCLUDED diff --git a/contrib/libs/poco/Util/include/Poco/Util/PropertyFileConfiguration.h b/contrib/libs/poco/Util/include/Poco/Util/PropertyFileConfiguration.h index aee16b8fdf..bf478d9d21 100644 --- a/contrib/libs/poco/Util/include/Poco/Util/PropertyFileConfiguration.h +++ b/contrib/libs/poco/Util/include/Poco/Util/PropertyFileConfiguration.h @@ -1,99 +1,99 @@ -// -// PropertyFileConfiguration.h -// -// Library: Util -// Package: Configuration -// Module: PropertyFileConfiguration -// -// Definition of the PropertyFileConfiguration class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// SPDX-License-Identifier: BSL-1.0 -// - - -#ifndef Util_PropertyFileConfiguration_INCLUDED -#define Util_PropertyFileConfiguration_INCLUDED - - -#include "Poco/Util/Util.h" -#include "Poco/Util/MapConfiguration.h" -#include <istream> -#include <ostream> - - -namespace Poco { -namespace Util { - - -class Util_API PropertyFileConfiguration: public MapConfiguration - /// This implementation of a Configuration reads properties - /// from a Java-style properties file. - /// - /// The file syntax is implemented as follows. - /// - a line starting with a hash '#' or exclamation mark '!' is treated as a comment and ignored - /// - every other line denotes a property assignment in the form - /// <key> = <value> or - /// <key> : <value> - /// - /// Keys and values may contain special characters represented by the following escape sequences: - /// - \t: tab (0x09) - /// - \n: line feed (0x0a) - /// - \r: carriage return (0x0d) - /// - \f: form feed (0x0c) - /// - /// For every other sequence that starts with a backslash, the backslash is removed. - /// Therefore, the sequence \a would just yield an 'a'. - /// - /// A value can spread across multiple lines if the last character in a line (the character - /// immediately before the carriage return or line feed character) is a single backslash. - /// - /// Property names are case sensitive. Leading and trailing whitespace is - /// removed from both keys and values. A property name can neither contain - /// a colon ':' nor an equal sign '=' character. -{ -public: - PropertyFileConfiguration(); - /// Creates an empty PropertyFileConfiguration. - - PropertyFileConfiguration(std::istream& istr); - /// Creates an PropertyFileConfiguration and loads the configuration data - /// from the given stream, which must be in properties file format. - - PropertyFileConfiguration(const std::string& path); - /// Creates an PropertyFileConfiguration and loads the configuration data - /// from the given file, which must be in properties file format. - - void load(std::istream& istr); - /// Loads the configuration data from the given stream, which - /// must be in properties file format. - - void load(const std::string& path); - /// Loads the configuration data from the given file, which - /// must be in properties file format. - - void save(std::ostream& ostr) const; - /// Writes the configuration data to the given stream. - /// - /// The data is written as a sequence of statements in the form - /// <key>: <value> - /// separated by a newline character. - - void save(const std::string& path) const; - /// Writes the configuration data to the given file. - -protected: - ~PropertyFileConfiguration(); - -private: - void parseLine(std::istream& istr); - static int readChar(std::istream& istr); -}; - - -} } // namespace Poco::Util - - -#endif // Util_PropertyFileConfiguration_INCLUDED +// +// PropertyFileConfiguration.h +// +// Library: Util +// Package: Configuration +// Module: PropertyFileConfiguration +// +// Definition of the PropertyFileConfiguration class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Util_PropertyFileConfiguration_INCLUDED +#define Util_PropertyFileConfiguration_INCLUDED + + +#include "Poco/Util/Util.h" +#include "Poco/Util/MapConfiguration.h" +#include <istream> +#include <ostream> + + +namespace Poco { +namespace Util { + + +class Util_API PropertyFileConfiguration: public MapConfiguration + /// This implementation of a Configuration reads properties + /// from a Java-style properties file. + /// + /// The file syntax is implemented as follows. + /// - a line starting with a hash '#' or exclamation mark '!' is treated as a comment and ignored + /// - every other line denotes a property assignment in the form + /// <key> = <value> or + /// <key> : <value> + /// + /// Keys and values may contain special characters represented by the following escape sequences: + /// - \t: tab (0x09) + /// - \n: line feed (0x0a) + /// - \r: carriage return (0x0d) + /// - \f: form feed (0x0c) + /// + /// For every other sequence that starts with a backslash, the backslash is removed. + /// Therefore, the sequence \a would just yield an 'a'. + /// + /// A value can spread across multiple lines if the last character in a line (the character + /// immediately before the carriage return or line feed character) is a single backslash. + /// + /// Property names are case sensitive. Leading and trailing whitespace is + /// removed from both keys and values. A property name can neither contain + /// a colon ':' nor an equal sign '=' character. +{ +public: + PropertyFileConfiguration(); + /// Creates an empty PropertyFileConfiguration. + + PropertyFileConfiguration(std::istream& istr); + /// Creates an PropertyFileConfiguration and loads the configuration data + /// from the given stream, which must be in properties file format. + + PropertyFileConfiguration(const std::string& path); + /// Creates an PropertyFileConfiguration and loads the configuration data + /// from the given file, which must be in properties file format. + + void load(std::istream& istr); + /// Loads the configuration data from the given stream, which + /// must be in properties file format. + + void load(const std::string& path); + /// Loads the configuration data from the given file, which + /// must be in properties file format. + + void save(std::ostream& ostr) const; + /// Writes the configuration data to the given stream. + /// + /// The data is written as a sequence of statements in the form + /// <key>: <value> + /// separated by a newline character. + + void save(const std::string& path) const; + /// Writes the configuration data to the given file. + +protected: + ~PropertyFileConfiguration(); + +private: + void parseLine(std::istream& istr); + static int readChar(std::istream& istr); +}; + + +} } // namespace Poco::Util + + +#endif // Util_PropertyFileConfiguration_INCLUDED diff --git a/contrib/libs/poco/Util/include/Poco/Util/RegExpValidator.h b/contrib/libs/poco/Util/include/Poco/Util/RegExpValidator.h index c1a492be66..81e5d4ad94 100644 --- a/contrib/libs/poco/Util/include/Poco/Util/RegExpValidator.h +++ b/contrib/libs/poco/Util/include/Poco/Util/RegExpValidator.h @@ -1,54 +1,54 @@ -// -// RegExpValidator.h -// -// Library: Util -// Package: Options -// Module: RegExpValidator -// -// Definition of the RegExpValidator class. -// -// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// SPDX-License-Identifier: BSL-1.0 -// - - -#ifndef Util_RegExpValidator_INCLUDED -#define Util_RegExpValidator_INCLUDED - - -#include "Poco/Util/Util.h" -#include "Poco/Util/Validator.h" - - -namespace Poco { -namespace Util { - - -class Util_API RegExpValidator: public Validator - /// This validator matches the option value against - /// a regular expression. -{ -public: - RegExpValidator(const std::string& regexp); - /// Creates the RegExpValidator, using the given regular expression. - - ~RegExpValidator(); - /// Destroys the RegExpValidator. - - void validate(const Option& option, const std::string& value); - /// Validates the value for the given option by - /// matching it with the regular expression. - -private: - RegExpValidator(); - - std::string _regexp; -}; - - -} } // namespace Poco::Util - - -#endif // Util_RegExpValidator_INCLUDED +// +// RegExpValidator.h +// +// Library: Util +// Package: Options +// Module: RegExpValidator +// +// Definition of the RegExpValidator class. +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Util_RegExpValidator_INCLUDED +#define Util_RegExpValidator_INCLUDED + + +#include "Poco/Util/Util.h" +#include "Poco/Util/Validator.h" + + +namespace Poco { +namespace Util { + + +class Util_API RegExpValidator: public Validator + /// This validator matches the option value against + /// a regular expression. +{ +public: + RegExpValidator(const std::string& regexp); + /// Creates the RegExpValidator, using the given regular expression. + + ~RegExpValidator(); + /// Destroys the RegExpValidator. + + void validate(const Option& option, const std::string& value); + /// Validates the value for the given option by + /// matching it with the regular expression. + +private: + RegExpValidator(); + + std::string _regexp; +}; + + +} } // namespace Poco::Util + + +#endif // Util_RegExpValidator_INCLUDED diff --git a/contrib/libs/poco/Util/include/Poco/Util/ServerApplication.h b/contrib/libs/poco/Util/include/Poco/Util/ServerApplication.h index 2c1010827b..fdc314b758 100644 --- a/contrib/libs/poco/Util/include/Poco/Util/ServerApplication.h +++ b/contrib/libs/poco/Util/include/Poco/Util/ServerApplication.h @@ -1,287 +1,287 @@ -// -// ServerApplication.h -// -// Library: Util -// Package: Application -// Module: ServerApplication -// -// Definition of the ServerApplication class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// SPDX-License-Identifier: BSL-1.0 -// - - -#ifndef Util_ServerApplication_INCLUDED -#define Util_ServerApplication_INCLUDED - - -#include "Poco/Util/Util.h" -#include "Poco/Util/Application.h" -#include "Poco/Event.h" -#if defined(POCO_OS_FAMILY_WINDOWS) -#include "Poco/NamedEvent.h" -#endif - - -namespace Poco { -namespace Util { - - -class Util_API ServerApplication: public Application - /// A subclass of the Application class that is used - /// for implementing server applications. +// +// ServerApplication.h +// +// Library: Util +// Package: Application +// Module: ServerApplication +// +// Definition of the ServerApplication class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Util_ServerApplication_INCLUDED +#define Util_ServerApplication_INCLUDED + + +#include "Poco/Util/Util.h" +#include "Poco/Util/Application.h" +#include "Poco/Event.h" +#if defined(POCO_OS_FAMILY_WINDOWS) +#include "Poco/NamedEvent.h" +#endif + + +namespace Poco { +namespace Util { + + +class Util_API ServerApplication: public Application + /// A subclass of the Application class that is used + /// for implementing server applications. + /// + /// A ServerApplication allows for the application + /// to run as a Windows service or as a Unix daemon + /// without the need to add extra code. + /// + /// For a ServerApplication to work both from the command line + /// and as a daemon or service, a few rules must be met: + /// - Subsystems must be registered in the constructor. + /// - All non-trivial initializations must be made in the + /// initialize() method. + /// - At the end of the main() method, waitForTerminationRequest() + /// should be called. + /// - New threads must only be created in initialize() or main() or + /// methods called from there, but not in the application class' + /// constructor or in the constructor of instance variables. + /// The reason for this is that fork() will be called in order to + /// create the daemon process, and threads created prior to calling + /// fork() won't be taken over to the daemon process. + /// - The main(argc, argv) function must look as follows: + /// + /// int main(int argc, char** argv) + /// { + /// MyServerApplication app; + /// return app.run(argc, argv); + /// } + /// + /// The POCO_SERVER_MAIN macro can be used to implement main(argc, argv). + /// If POCO has been built with POCO_WIN32_UTF8, POCO_SERVER_MAIN supports + /// Unicode command line arguments. + /// + /// On Windows platforms, an application built on top of the + /// ServerApplication class can be run both from the command line + /// or as a service. + /// + /// To run an application as a Windows service, it must be registered + /// with the Windows Service Control Manager (SCM). To do this, the application + /// can be started from the command line, with the /registerService option + /// specified. This causes the application to register itself with the + /// SCM, and then exit. Similarly, an application registered as a service can + /// be unregistered, by specifying the /unregisterService option. + /// The file name of the application executable (excluding the .exe suffix) + /// is used as the service name. Additionally, a more user-friendly name can be + /// specified, using the /displayName option (e.g., /displayName="Demo Service") + /// and a service description can be added with the /description option. + /// The startup mode (automatic or manual) for the service can be specified + /// with the /startup option. + /// + /// An application can determine whether it is running as a service by checking + /// for the "application.runAsService" configuration property. /// - /// A ServerApplication allows for the application - /// to run as a Windows service or as a Unix daemon - /// without the need to add extra code. + /// if (config().getBool("application.runAsService", false)) + /// { + /// // do service specific things + /// } + /// + /// Note that the working directory for an application running as a service + /// is the Windows system directory (e.g., C:\Windows\system32). Take this + /// into account when working with relative filesystem paths. Also, services + /// run under a different user account, so an application that works when + /// started from the command line may fail to run as a service if it depends + /// on a certain environment (e.g., the PATH environment variable). + /// + /// An application registered as a Windows service can be started + /// with the NET START <name> command and stopped with the NET STOP <name> + /// command. Alternatively, the Services MMC applet can be used. + /// + /// On Unix platforms, an application built on top of the ServerApplication + /// class can be optionally run as a daemon by giving the --daemon + /// command line option. A daemon, when launched, immediately + /// forks off a background process that does the actual work. After launching + /// the background process, the foreground process exits. /// - /// For a ServerApplication to work both from the command line - /// and as a daemon or service, a few rules must be met: - /// - Subsystems must be registered in the constructor. - /// - All non-trivial initializations must be made in the - /// initialize() method. - /// - At the end of the main() method, waitForTerminationRequest() - /// should be called. - /// - New threads must only be created in initialize() or main() or - /// methods called from there, but not in the application class' - /// constructor or in the constructor of instance variables. - /// The reason for this is that fork() will be called in order to - /// create the daemon process, and threads created prior to calling - /// fork() won't be taken over to the daemon process. - /// - The main(argc, argv) function must look as follows: - /// - /// int main(int argc, char** argv) - /// { - /// MyServerApplication app; - /// return app.run(argc, argv); - /// } - /// - /// The POCO_SERVER_MAIN macro can be used to implement main(argc, argv). - /// If POCO has been built with POCO_WIN32_UTF8, POCO_SERVER_MAIN supports - /// Unicode command line arguments. - /// - /// On Windows platforms, an application built on top of the - /// ServerApplication class can be run both from the command line - /// or as a service. - /// - /// To run an application as a Windows service, it must be registered - /// with the Windows Service Control Manager (SCM). To do this, the application - /// can be started from the command line, with the /registerService option - /// specified. This causes the application to register itself with the - /// SCM, and then exit. Similarly, an application registered as a service can - /// be unregistered, by specifying the /unregisterService option. - /// The file name of the application executable (excluding the .exe suffix) - /// is used as the service name. Additionally, a more user-friendly name can be - /// specified, using the /displayName option (e.g., /displayName="Demo Service") - /// and a service description can be added with the /description option. - /// The startup mode (automatic or manual) for the service can be specified - /// with the /startup option. - /// - /// An application can determine whether it is running as a service by checking - /// for the "application.runAsService" configuration property. - /// - /// if (config().getBool("application.runAsService", false)) - /// { - /// // do service specific things - /// } - /// - /// Note that the working directory for an application running as a service - /// is the Windows system directory (e.g., C:\Windows\system32). Take this - /// into account when working with relative filesystem paths. Also, services - /// run under a different user account, so an application that works when - /// started from the command line may fail to run as a service if it depends - /// on a certain environment (e.g., the PATH environment variable). - /// - /// An application registered as a Windows service can be started - /// with the NET START <name> command and stopped with the NET STOP <name> - /// command. Alternatively, the Services MMC applet can be used. - /// - /// On Unix platforms, an application built on top of the ServerApplication - /// class can be optionally run as a daemon by giving the --daemon - /// command line option. A daemon, when launched, immediately - /// forks off a background process that does the actual work. After launching - /// the background process, the foreground process exits. - /// - /// After the initialization is complete, but before entering the main() method, - /// the current working directory for the daemon process is changed to the root - /// directory ("/"), as it is common practice for daemon processes. Therefore, be - /// careful when working with files, as relative paths may not point to where - /// you expect them point to. - /// - /// An application can determine whether it is running as a daemon by checking - /// for the "application.runAsDaemon" configuration property. - /// - /// if (config().getBool("application.runAsDaemon", false)) - /// { - /// // do daemon specific things - /// } - /// - /// When running as a daemon, specifying the --pidfile option (e.g., - /// --pidfile=/var/run/sample.pid) may be useful to record the process ID of - /// the daemon in a file. The PID file will be removed when the daemon process - /// terminates (but not, if it crashes). -{ -public: - ServerApplication(); - /// Creates the ServerApplication. - - ~ServerApplication(); - /// Destroys the ServerApplication. - - bool isInteractive() const; - /// Returns true if the application runs from the command line. - /// Returns false if the application runs as a Unix daemon - /// or Windows service. - - int run(int argc, char** argv); - /// Runs the application by performing additional initializations - /// and calling the main() method. - - int run(const std::vector<std::string>& args); - /// Runs the application by performing additional initializations - /// and calling the main() method. - -#if defined(POCO_WIN32_UTF8) && !defined(POCO_NO_WSTRING) - int run(int argc, wchar_t** argv); - /// Runs the application by performing additional initializations - /// and calling the main() method. - /// - /// This Windows-specific version of init is used for passing - /// Unicode command line arguments from wmain(). -#endif - - static void terminate(); - /// Sends a friendly termination request to the application. - /// If the application's main thread is waiting in - /// waitForTerminationRequest(), this method will return - /// and the application can shut down. - -protected: - int run(); - virtual void waitForTerminationRequest(); -#if !defined(_WIN32_WCE) - void defineOptions(OptionSet& options); -#endif - -private: -#if defined(POCO_VXWORKS) - static Poco::Event _terminate; -#elif defined(POCO_OS_FAMILY_UNIX) - void handleDaemon(const std::string& name, const std::string& value); - void handleUMask(const std::string& name, const std::string& value); - void handlePidFile(const std::string& name, const std::string& value); - bool isDaemon(int argc, char** argv); - void beDaemon(); -#if POCO_OS == POCO_OS_ANDROID - static Poco::Event _terminate; -#endif -#elif defined(POCO_OS_FAMILY_WINDOWS) -#if !defined(_WIN32_WCE) - enum Action - { - SRV_RUN, - SRV_REGISTER, - SRV_UNREGISTER - }; - static BOOL __stdcall ConsoleCtrlHandler(DWORD ctrlType); - static void __stdcall ServiceControlHandler(DWORD control); -#if defined(POCO_WIN32_UTF8) && !defined(POCO_NO_WSTRING) - static void __stdcall ServiceMain(DWORD argc, LPWSTR* argv); -#else - static void __stdcall ServiceMain(DWORD argc, LPTSTR* argv); -#endif - - bool hasConsole(); - bool isService(); - void beService(); - void registerService(); - void unregisterService(); - void handleRegisterService(const std::string& name, const std::string& value); - void handleUnregisterService(const std::string& name, const std::string& value); - void handleDisplayName(const std::string& name, const std::string& value); - void handleDescription(const std::string& name, const std::string& value); - void handleStartup(const std::string& name, const std::string& value); - - Action _action; - std::string _displayName; - std::string _description; - std::string _startup; - - static Poco::Event _terminated; - static SERVICE_STATUS _serviceStatus; - static SERVICE_STATUS_HANDLE _serviceStatusHandle; -#endif // _WIN32_WCE - static Poco::NamedEvent _terminate; -#endif -}; - - -} } // namespace Poco::Util - - -// -// Macro to implement main() -// -#if defined(_WIN32) && defined(POCO_WIN32_UTF8) - #define POCO_SERVER_MAIN(App) \ - int wmain(int argc, wchar_t** argv) \ - { \ - try \ - { \ - App app; \ - return app.run(argc, argv); \ - } \ - catch (Poco::Exception& exc) \ - { \ - std::cerr << exc.displayText() << std::endl; \ - return Poco::Util::Application::EXIT_SOFTWARE; \ - } \ - } -#elif defined(POCO_VXWORKS) - #define POCO_SERVER_MAIN(App) \ - int pocoSrvMain(const char* appName, ...) \ - { \ - std::vector<std::string> args; \ - args.push_back(std::string(appName)); \ - va_list vargs; \ - va_start(vargs, appName); \ - const char* arg = va_arg(vargs, const char*); \ - while (arg) \ - { \ - args.push_back(std::string(arg)); \ - arg = va_arg(vargs, const char*); \ - } \ - va_end(vargs); \ - try \ - { \ - App app; \ - return app.run(args); \ - } \ - catch (Poco::Exception& exc) \ - { \ - std::cerr << exc.displayText() << std::endl; \ - return Poco::Util::Application::EXIT_SOFTWARE; \ - } \ - } -#else - #define POCO_SERVER_MAIN(App) \ - int main(int argc, char** argv) \ - { \ - try \ - { \ - App app; \ - return app.run(argc, argv); \ - } \ - catch (Poco::Exception& exc) \ - { \ - std::cerr << exc.displayText() << std::endl; \ - return Poco::Util::Application::EXIT_SOFTWARE; \ - } \ - } -#endif - - -#endif // Util_ServerApplication_INCLUDED + /// After the initialization is complete, but before entering the main() method, + /// the current working directory for the daemon process is changed to the root + /// directory ("/"), as it is common practice for daemon processes. Therefore, be + /// careful when working with files, as relative paths may not point to where + /// you expect them point to. + /// + /// An application can determine whether it is running as a daemon by checking + /// for the "application.runAsDaemon" configuration property. + /// + /// if (config().getBool("application.runAsDaemon", false)) + /// { + /// // do daemon specific things + /// } + /// + /// When running as a daemon, specifying the --pidfile option (e.g., + /// --pidfile=/var/run/sample.pid) may be useful to record the process ID of + /// the daemon in a file. The PID file will be removed when the daemon process + /// terminates (but not, if it crashes). +{ +public: + ServerApplication(); + /// Creates the ServerApplication. + + ~ServerApplication(); + /// Destroys the ServerApplication. + + bool isInteractive() const; + /// Returns true if the application runs from the command line. + /// Returns false if the application runs as a Unix daemon + /// or Windows service. + + int run(int argc, char** argv); + /// Runs the application by performing additional initializations + /// and calling the main() method. + + int run(const std::vector<std::string>& args); + /// Runs the application by performing additional initializations + /// and calling the main() method. + +#if defined(POCO_WIN32_UTF8) && !defined(POCO_NO_WSTRING) + int run(int argc, wchar_t** argv); + /// Runs the application by performing additional initializations + /// and calling the main() method. + /// + /// This Windows-specific version of init is used for passing + /// Unicode command line arguments from wmain(). +#endif + + static void terminate(); + /// Sends a friendly termination request to the application. + /// If the application's main thread is waiting in + /// waitForTerminationRequest(), this method will return + /// and the application can shut down. + +protected: + int run(); + virtual void waitForTerminationRequest(); +#if !defined(_WIN32_WCE) + void defineOptions(OptionSet& options); +#endif + +private: +#if defined(POCO_VXWORKS) + static Poco::Event _terminate; +#elif defined(POCO_OS_FAMILY_UNIX) + void handleDaemon(const std::string& name, const std::string& value); + void handleUMask(const std::string& name, const std::string& value); + void handlePidFile(const std::string& name, const std::string& value); + bool isDaemon(int argc, char** argv); + void beDaemon(); +#if POCO_OS == POCO_OS_ANDROID + static Poco::Event _terminate; +#endif +#elif defined(POCO_OS_FAMILY_WINDOWS) +#if !defined(_WIN32_WCE) + enum Action + { + SRV_RUN, + SRV_REGISTER, + SRV_UNREGISTER + }; + static BOOL __stdcall ConsoleCtrlHandler(DWORD ctrlType); + static void __stdcall ServiceControlHandler(DWORD control); +#if defined(POCO_WIN32_UTF8) && !defined(POCO_NO_WSTRING) + static void __stdcall ServiceMain(DWORD argc, LPWSTR* argv); +#else + static void __stdcall ServiceMain(DWORD argc, LPTSTR* argv); +#endif + + bool hasConsole(); + bool isService(); + void beService(); + void registerService(); + void unregisterService(); + void handleRegisterService(const std::string& name, const std::string& value); + void handleUnregisterService(const std::string& name, const std::string& value); + void handleDisplayName(const std::string& name, const std::string& value); + void handleDescription(const std::string& name, const std::string& value); + void handleStartup(const std::string& name, const std::string& value); + + Action _action; + std::string _displayName; + std::string _description; + std::string _startup; + + static Poco::Event _terminated; + static SERVICE_STATUS _serviceStatus; + static SERVICE_STATUS_HANDLE _serviceStatusHandle; +#endif // _WIN32_WCE + static Poco::NamedEvent _terminate; +#endif +}; + + +} } // namespace Poco::Util + + +// +// Macro to implement main() +// +#if defined(_WIN32) && defined(POCO_WIN32_UTF8) + #define POCO_SERVER_MAIN(App) \ + int wmain(int argc, wchar_t** argv) \ + { \ + try \ + { \ + App app; \ + return app.run(argc, argv); \ + } \ + catch (Poco::Exception& exc) \ + { \ + std::cerr << exc.displayText() << std::endl; \ + return Poco::Util::Application::EXIT_SOFTWARE; \ + } \ + } +#elif defined(POCO_VXWORKS) + #define POCO_SERVER_MAIN(App) \ + int pocoSrvMain(const char* appName, ...) \ + { \ + std::vector<std::string> args; \ + args.push_back(std::string(appName)); \ + va_list vargs; \ + va_start(vargs, appName); \ + const char* arg = va_arg(vargs, const char*); \ + while (arg) \ + { \ + args.push_back(std::string(arg)); \ + arg = va_arg(vargs, const char*); \ + } \ + va_end(vargs); \ + try \ + { \ + App app; \ + return app.run(args); \ + } \ + catch (Poco::Exception& exc) \ + { \ + std::cerr << exc.displayText() << std::endl; \ + return Poco::Util::Application::EXIT_SOFTWARE; \ + } \ + } +#else + #define POCO_SERVER_MAIN(App) \ + int main(int argc, char** argv) \ + { \ + try \ + { \ + App app; \ + return app.run(argc, argv); \ + } \ + catch (Poco::Exception& exc) \ + { \ + std::cerr << exc.displayText() << std::endl; \ + return Poco::Util::Application::EXIT_SOFTWARE; \ + } \ + } +#endif + + +#endif // Util_ServerApplication_INCLUDED diff --git a/contrib/libs/poco/Util/include/Poco/Util/Subsystem.h b/contrib/libs/poco/Util/include/Poco/Util/Subsystem.h index 564bb8fa46..ce6eda24eb 100644 --- a/contrib/libs/poco/Util/include/Poco/Util/Subsystem.h +++ b/contrib/libs/poco/Util/include/Poco/Util/Subsystem.h @@ -1,98 +1,98 @@ -// -// Subsystem.h -// -// Library: Util -// Package: Application -// Module: Subsystem -// -// Definition of the Subsystem class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// SPDX-License-Identifier: BSL-1.0 -// - - -#ifndef Util_Subsystem_INCLUDED -#define Util_Subsystem_INCLUDED - - -#include "Poco/Util/Util.h" -#include "Poco/RefCountedObject.h" - - -namespace Poco { -namespace Util { - - -class Application; -class OptionSet; - - -class Util_API Subsystem: public Poco::RefCountedObject - /// Subsystems extend an application in a modular way. - /// - /// The Subsystem class provides a common interface - /// for subsystems so that subsystems can be automatically - /// initialized at startup and uninitialized at shutdown. - /// - /// Subsystems should also support dynamic reconfiguration, - /// so that they can be reconfigured anytime during the - /// life of a running application. - /// - /// The degree to which dynamic reconfiguration is supported - /// is up to the actual subsystem implementation. It can - /// range from ignoring the reconfiguration request (not - /// recommended), to changing certain settings that affect - /// the performance, to a complete reinitialization. -{ -public: - Subsystem(); - /// Creates the Subsystem. - - virtual const char* name() const = 0; - /// Returns the name of the subsystem. - /// Must be implemented by subclasses. - -protected: - virtual void initialize(Application& app) = 0; - /// Initializes the subsystem. - - virtual void uninitialize() = 0; - /// Uninitializes the subsystem. - - virtual void reinitialize(Application& app); - /// Re-initializes the subsystem. - /// - /// The default implementation just calls - /// uninitialize() followed by initialize(). - /// Actual implementations might want to use a - /// less radical and possibly more performant - /// approach. - - virtual void defineOptions(OptionSet& options); - /// Called before the Application's command line processing begins. - /// If a subsystem wants to support command line arguments, - /// it must override this method. - /// The default implementation does not define any options. - /// - /// To effectively handle options, a subsystem should either bind - /// the option to a configuration property or specify a callback - /// to handle the option. - - virtual ~Subsystem(); - /// Destroys the Subsystem. - - friend class Application; - -private: - Subsystem(const Subsystem&); - Subsystem& operator = (const Subsystem&); -}; - - -} } // namespace Poco::Util - - -#endif // Util_Subsystem_INCLUDED +// +// Subsystem.h +// +// Library: Util +// Package: Application +// Module: Subsystem +// +// Definition of the Subsystem class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Util_Subsystem_INCLUDED +#define Util_Subsystem_INCLUDED + + +#include "Poco/Util/Util.h" +#include "Poco/RefCountedObject.h" + + +namespace Poco { +namespace Util { + + +class Application; +class OptionSet; + + +class Util_API Subsystem: public Poco::RefCountedObject + /// Subsystems extend an application in a modular way. + /// + /// The Subsystem class provides a common interface + /// for subsystems so that subsystems can be automatically + /// initialized at startup and uninitialized at shutdown. + /// + /// Subsystems should also support dynamic reconfiguration, + /// so that they can be reconfigured anytime during the + /// life of a running application. + /// + /// The degree to which dynamic reconfiguration is supported + /// is up to the actual subsystem implementation. It can + /// range from ignoring the reconfiguration request (not + /// recommended), to changing certain settings that affect + /// the performance, to a complete reinitialization. +{ +public: + Subsystem(); + /// Creates the Subsystem. + + virtual const char* name() const = 0; + /// Returns the name of the subsystem. + /// Must be implemented by subclasses. + +protected: + virtual void initialize(Application& app) = 0; + /// Initializes the subsystem. + + virtual void uninitialize() = 0; + /// Uninitializes the subsystem. + + virtual void reinitialize(Application& app); + /// Re-initializes the subsystem. + /// + /// The default implementation just calls + /// uninitialize() followed by initialize(). + /// Actual implementations might want to use a + /// less radical and possibly more performant + /// approach. + + virtual void defineOptions(OptionSet& options); + /// Called before the Application's command line processing begins. + /// If a subsystem wants to support command line arguments, + /// it must override this method. + /// The default implementation does not define any options. + /// + /// To effectively handle options, a subsystem should either bind + /// the option to a configuration property or specify a callback + /// to handle the option. + + virtual ~Subsystem(); + /// Destroys the Subsystem. + + friend class Application; + +private: + Subsystem(const Subsystem&); + Subsystem& operator = (const Subsystem&); +}; + + +} } // namespace Poco::Util + + +#endif // Util_Subsystem_INCLUDED diff --git a/contrib/libs/poco/Util/include/Poco/Util/SystemConfiguration.h b/contrib/libs/poco/Util/include/Poco/Util/SystemConfiguration.h index 7b77af0316..e80dc6ef2f 100644 --- a/contrib/libs/poco/Util/include/Poco/Util/SystemConfiguration.h +++ b/contrib/libs/poco/Util/include/Poco/Util/SystemConfiguration.h @@ -1,99 +1,99 @@ -// -// SystemConfiguration.h -// -// Library: Util -// Package: Configuration -// Module: SystemConfiguration -// -// Definition of the SystemConfiguration class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// SPDX-License-Identifier: BSL-1.0 -// - - -#ifndef Util_SystemConfiguration_INCLUDED -#define Util_SystemConfiguration_INCLUDED - - -#include "Poco/Util/Util.h" -#include "Poco/Util/AbstractConfiguration.h" - - -namespace Poco { -namespace Util { - - -class Util_API SystemConfiguration: public AbstractConfiguration - /// This class implements a Configuration interface to - /// various system properties and environment variables. +// +// SystemConfiguration.h +// +// Library: Util +// Package: Configuration +// Module: SystemConfiguration +// +// Definition of the SystemConfiguration class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Util_SystemConfiguration_INCLUDED +#define Util_SystemConfiguration_INCLUDED + + +#include "Poco/Util/Util.h" +#include "Poco/Util/AbstractConfiguration.h" + + +namespace Poco { +namespace Util { + + +class Util_API SystemConfiguration: public AbstractConfiguration + /// This class implements a Configuration interface to + /// various system properties and environment variables. + /// + /// The following properties are supported: + /// - system.osName: the operating system name + /// - system.osVersion: the operating system version + /// - system.osArchitecture: the operating system architecture + /// - system.nodeName: the node (or host) name + /// - system.nodeId: system ID, based on the Ethernet address (format "xxxxxxxxxxxx") + /// of the first Ethernet adapter found on the system. + /// - system.currentDir: the current working directory + /// - system.homeDir: the user's home directory + /// - system.configHomeDir: the base directory relative to which user specific configuration files should be stored + /// - system.cacheHomeDir: the base directory relative to which user specific non-essential data files should be stored + /// - system.dataHomeDir: the base directory relative to which user specific data files should be stored + /// - system.tempHomeDir: the base directory relative to which user-specific temporary files and other file objects should be placed + /// - system.tempDir: the system's temporary directory + /// - system.configDir: the system's configuration directory + /// - system.dateTime: the current UTC date and time, formatted in ISO 8601 format. + /// - system.pid: the current process ID. + /// - system.env.<NAME>: the environment variable with the given <NAME>. + /// + /// An attempt to set a system variable will result in an + /// InvalidAccessException being thrown. /// - /// The following properties are supported: - /// - system.osName: the operating system name - /// - system.osVersion: the operating system version - /// - system.osArchitecture: the operating system architecture - /// - system.nodeName: the node (or host) name - /// - system.nodeId: system ID, based on the Ethernet address (format "xxxxxxxxxxxx") - /// of the first Ethernet adapter found on the system. - /// - system.currentDir: the current working directory - /// - system.homeDir: the user's home directory - /// - system.configHomeDir: the base directory relative to which user specific configuration files should be stored - /// - system.cacheHomeDir: the base directory relative to which user specific non-essential data files should be stored - /// - system.dataHomeDir: the base directory relative to which user specific data files should be stored - /// - system.tempHomeDir: the base directory relative to which user-specific temporary files and other file objects should be placed - /// - system.tempDir: the system's temporary directory - /// - system.configDir: the system's configuration directory - /// - system.dateTime: the current UTC date and time, formatted in ISO 8601 format. - /// - system.pid: the current process ID. - /// - system.env.<NAME>: the environment variable with the given <NAME>. - /// - /// An attempt to set a system variable will result in an - /// InvalidAccessException being thrown. - /// - /// Enumerating environment variables is not supported. - /// An attempt to call keys("system.env") will return an empty range. - /// - /// Removing key is not supported. An attempt to remove a key results - /// in a NotImplementedException being thrown. -{ -public: - SystemConfiguration(); - /// Creates the SystemConfiguration. - -protected: - bool getRaw(const std::string& key, std::string& value) const; - void setRaw(const std::string& key, const std::string& value); - void enumerate(const std::string& key, Keys& range) const; - void removeRaw(const std::string& key); - ~SystemConfiguration(); - -private: - static bool getEnv(const std::string& name, std::string& value); - - static const std::string OSNAME; - static const std::string OSVERSION; - static const std::string OSARCHITECTURE; - static const std::string NODENAME; - static const std::string NODEID; - static const std::string CURRENTDIR; - static const std::string HOMEDIR; - static const std::string CONFIGHOMEDIR; - static const std::string CACHEHOMEDIR; - static const std::string DATAHOMEDIR; - static const std::string TEMPHOMEDIR; - static const std::string TEMPDIR; - static const std::string CONFIGDIR; - static const std::string DATETIME; -#if !defined(POCO_VXWORKS) - static const std::string PID; -#endif - static const std::string ENV; -}; - - -} } // namespace Poco::Util - - -#endif // Util_SystemConfiguration_INCLUDED + /// Enumerating environment variables is not supported. + /// An attempt to call keys("system.env") will return an empty range. + /// + /// Removing key is not supported. An attempt to remove a key results + /// in a NotImplementedException being thrown. +{ +public: + SystemConfiguration(); + /// Creates the SystemConfiguration. + +protected: + bool getRaw(const std::string& key, std::string& value) const; + void setRaw(const std::string& key, const std::string& value); + void enumerate(const std::string& key, Keys& range) const; + void removeRaw(const std::string& key); + ~SystemConfiguration(); + +private: + static bool getEnv(const std::string& name, std::string& value); + + static const std::string OSNAME; + static const std::string OSVERSION; + static const std::string OSARCHITECTURE; + static const std::string NODENAME; + static const std::string NODEID; + static const std::string CURRENTDIR; + static const std::string HOMEDIR; + static const std::string CONFIGHOMEDIR; + static const std::string CACHEHOMEDIR; + static const std::string DATAHOMEDIR; + static const std::string TEMPHOMEDIR; + static const std::string TEMPDIR; + static const std::string CONFIGDIR; + static const std::string DATETIME; +#if !defined(POCO_VXWORKS) + static const std::string PID; +#endif + static const std::string ENV; +}; + + +} } // namespace Poco::Util + + +#endif // Util_SystemConfiguration_INCLUDED diff --git a/contrib/libs/poco/Util/include/Poco/Util/Timer.h b/contrib/libs/poco/Util/include/Poco/Util/Timer.h index edfeca2efc..a3edd47608 100644 --- a/contrib/libs/poco/Util/include/Poco/Util/Timer.h +++ b/contrib/libs/poco/Util/include/Poco/Util/Timer.h @@ -1,169 +1,169 @@ -// -// Timer.h -// -// Library: Util -// Package: Timer -// Module: Timer -// -// Definition of the Timer class. -// -// Copyright (c) 2009, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// SPDX-License-Identifier: BSL-1.0 -// - - -#ifndef Util_Timer_INCLUDED -#define Util_Timer_INCLUDED - - -#include "Poco/Util/Util.h" -#include "Poco/Util/TimerTask.h" -#include "Poco/TimedNotificationQueue.h" -#include "Poco/Thread.h" -#include "Poco/Runnable.h" - - -namespace Poco { -namespace Util { - - -class Util_API Timer: protected Poco::Runnable - /// A Timer allows to schedule tasks (TimerTask objects) for future execution - /// in a background thread. Tasks may be scheduled for one-time execution, - /// or for repeated execution at regular intervals. - /// - /// The Timer object creates a thread that executes all scheduled tasks - /// sequentially. Therefore, tasks should complete their work as quickly - /// as possible, otherwise subsequent tasks may be delayed. - /// - /// Timer is safe for multithreaded use - multiple threads can schedule - /// new tasks simultaneously. - /// - /// Acknowledgement: The interface of this class has been inspired by - /// the java.util.Timer class from Java 1.3. -{ -public: - Timer(); - /// Creates the Timer. - - explicit Timer(Poco::Thread::Priority priority); - /// Creates the Timer, using a timer thread with - /// the given priority. - - ~Timer(); - /// Destroys the Timer, cancelling all pending tasks. - - void cancel(bool wait = false); - /// Cancels all pending tasks. - /// - /// If a task is currently running, it is allowed to finish. - /// - /// Task cancellation is done asynchronously. If wait - /// is false, cancel() returns immediately and the - /// task queue will be purged as soon as the currently - /// running task finishes. If wait is true, waits - /// until the queue has been purged. - - void schedule(TimerTask::Ptr pTask, Poco::Timestamp time); - /// Schedules a task for execution at the specified time. - /// - /// If the time lies in the past, the task is executed - /// immediately. - /// - /// Note: the relative time the task will be executed - /// won't change if the system's time changes. If the - /// given time is 10 seconds in the future at the point - /// schedule() is called, the task will be executed 10 - /// seconds later, even if the system time changes in - /// between. - - void schedule(TimerTask::Ptr pTask, Poco::Clock clock); - /// Schedules a task for execution at the specified time. - /// - /// If the time lies in the past, the task is executed - /// immediately. - - void schedule(TimerTask::Ptr pTask, long delay, long interval); - /// Schedules a task for periodic execution. - /// - /// The task is first executed after the given delay. - /// Subsequently, the task is executed periodically with - /// the given interval in milliseconds between invocations. - - void schedule(TimerTask::Ptr pTask, Poco::Timestamp time, long interval); - /// Schedules a task for periodic execution. - /// - /// The task is first executed at the given time. - /// Subsequently, the task is executed periodically with - /// the given interval in milliseconds between invocations. - /// - /// Note: the relative time the task will be executed - /// won't change if the system's time changes. If the - /// given time is 10 seconds in the future at the point - /// schedule() is called, the task will be executed 10 - /// seconds later, even if the system time changes in - /// between. - - void schedule(TimerTask::Ptr pTask, Poco::Clock clock, long interval); - /// Schedules a task for periodic execution. - /// - /// The task is first executed at the given time. - /// Subsequently, the task is executed periodically with - /// the given interval in milliseconds between invocations. - - void scheduleAtFixedRate(TimerTask::Ptr pTask, long delay, long interval); - /// Schedules a task for periodic execution at a fixed rate. - /// - /// The task is first executed after the given delay. - /// Subsequently, the task is executed periodically - /// every number of milliseconds specified by interval. - /// - /// If task execution takes longer than the given interval, - /// further executions are delayed. - - void scheduleAtFixedRate(TimerTask::Ptr pTask, Poco::Timestamp time, long interval); - /// Schedules a task for periodic execution at a fixed rate. - /// - /// The task is first executed at the given time. - /// Subsequently, the task is executed periodically - /// every number of milliseconds specified by interval. - /// - /// If task execution takes longer than the given interval, - /// further executions are delayed. - /// - /// Note: the relative time the task will be executed - /// won't change if the system's time changes. If the - /// given time is 10 seconds in the future at the point - /// scheduleAtFixedRate() is called, the task will be executed 10 - /// seconds later, even if the system time changes in - /// between. - - void scheduleAtFixedRate(TimerTask::Ptr pTask, Poco::Clock clock, long interval); - /// Schedules a task for periodic execution at a fixed rate. - /// - /// The task is first executed at the given time. - /// Subsequently, the task is executed periodically - /// every number of milliseconds specified by interval. - /// - /// If task execution takes longer than the given interval, - /// further executions are delayed. - -protected: - void run(); - static void validateTask(const TimerTask::Ptr& pTask); - -private: - Timer(const Timer&); - Timer& operator = (const Timer&); - - Poco::TimedNotificationQueue _queue; - Poco::Thread _thread; -}; - - -} } // namespace Poco::Util - - -#endif // Util_Timer_INCLUDED +// +// Timer.h +// +// Library: Util +// Package: Timer +// Module: Timer +// +// Definition of the Timer class. +// +// Copyright (c) 2009, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Util_Timer_INCLUDED +#define Util_Timer_INCLUDED + + +#include "Poco/Util/Util.h" +#include "Poco/Util/TimerTask.h" +#include "Poco/TimedNotificationQueue.h" +#include "Poco/Thread.h" +#include "Poco/Runnable.h" + + +namespace Poco { +namespace Util { + + +class Util_API Timer: protected Poco::Runnable + /// A Timer allows to schedule tasks (TimerTask objects) for future execution + /// in a background thread. Tasks may be scheduled for one-time execution, + /// or for repeated execution at regular intervals. + /// + /// The Timer object creates a thread that executes all scheduled tasks + /// sequentially. Therefore, tasks should complete their work as quickly + /// as possible, otherwise subsequent tasks may be delayed. + /// + /// Timer is safe for multithreaded use - multiple threads can schedule + /// new tasks simultaneously. + /// + /// Acknowledgement: The interface of this class has been inspired by + /// the java.util.Timer class from Java 1.3. +{ +public: + Timer(); + /// Creates the Timer. + + explicit Timer(Poco::Thread::Priority priority); + /// Creates the Timer, using a timer thread with + /// the given priority. + + ~Timer(); + /// Destroys the Timer, cancelling all pending tasks. + + void cancel(bool wait = false); + /// Cancels all pending tasks. + /// + /// If a task is currently running, it is allowed to finish. + /// + /// Task cancellation is done asynchronously. If wait + /// is false, cancel() returns immediately and the + /// task queue will be purged as soon as the currently + /// running task finishes. If wait is true, waits + /// until the queue has been purged. + + void schedule(TimerTask::Ptr pTask, Poco::Timestamp time); + /// Schedules a task for execution at the specified time. + /// + /// If the time lies in the past, the task is executed + /// immediately. + /// + /// Note: the relative time the task will be executed + /// won't change if the system's time changes. If the + /// given time is 10 seconds in the future at the point + /// schedule() is called, the task will be executed 10 + /// seconds later, even if the system time changes in + /// between. + + void schedule(TimerTask::Ptr pTask, Poco::Clock clock); + /// Schedules a task for execution at the specified time. + /// + /// If the time lies in the past, the task is executed + /// immediately. + + void schedule(TimerTask::Ptr pTask, long delay, long interval); + /// Schedules a task for periodic execution. + /// + /// The task is first executed after the given delay. + /// Subsequently, the task is executed periodically with + /// the given interval in milliseconds between invocations. + + void schedule(TimerTask::Ptr pTask, Poco::Timestamp time, long interval); + /// Schedules a task for periodic execution. + /// + /// The task is first executed at the given time. + /// Subsequently, the task is executed periodically with + /// the given interval in milliseconds between invocations. + /// + /// Note: the relative time the task will be executed + /// won't change if the system's time changes. If the + /// given time is 10 seconds in the future at the point + /// schedule() is called, the task will be executed 10 + /// seconds later, even if the system time changes in + /// between. + + void schedule(TimerTask::Ptr pTask, Poco::Clock clock, long interval); + /// Schedules a task for periodic execution. + /// + /// The task is first executed at the given time. + /// Subsequently, the task is executed periodically with + /// the given interval in milliseconds between invocations. + + void scheduleAtFixedRate(TimerTask::Ptr pTask, long delay, long interval); + /// Schedules a task for periodic execution at a fixed rate. + /// + /// The task is first executed after the given delay. + /// Subsequently, the task is executed periodically + /// every number of milliseconds specified by interval. + /// + /// If task execution takes longer than the given interval, + /// further executions are delayed. + + void scheduleAtFixedRate(TimerTask::Ptr pTask, Poco::Timestamp time, long interval); + /// Schedules a task for periodic execution at a fixed rate. + /// + /// The task is first executed at the given time. + /// Subsequently, the task is executed periodically + /// every number of milliseconds specified by interval. + /// + /// If task execution takes longer than the given interval, + /// further executions are delayed. + /// + /// Note: the relative time the task will be executed + /// won't change if the system's time changes. If the + /// given time is 10 seconds in the future at the point + /// scheduleAtFixedRate() is called, the task will be executed 10 + /// seconds later, even if the system time changes in + /// between. + + void scheduleAtFixedRate(TimerTask::Ptr pTask, Poco::Clock clock, long interval); + /// Schedules a task for periodic execution at a fixed rate. + /// + /// The task is first executed at the given time. + /// Subsequently, the task is executed periodically + /// every number of milliseconds specified by interval. + /// + /// If task execution takes longer than the given interval, + /// further executions are delayed. + +protected: + void run(); + static void validateTask(const TimerTask::Ptr& pTask); + +private: + Timer(const Timer&); + Timer& operator = (const Timer&); + + Poco::TimedNotificationQueue _queue; + Poco::Thread _thread; +}; + + +} } // namespace Poco::Util + + +#endif // Util_Timer_INCLUDED diff --git a/contrib/libs/poco/Util/include/Poco/Util/TimerTask.h b/contrib/libs/poco/Util/include/Poco/Util/TimerTask.h index 6b3f1ff1f8..05263f6afe 100644 --- a/contrib/libs/poco/Util/include/Poco/Util/TimerTask.h +++ b/contrib/libs/poco/Util/include/Poco/Util/TimerTask.h @@ -1,98 +1,98 @@ -// -// TimerTask.h -// -// Library: Util -// Package: Timer -// Module: TimerTask -// -// Definition of the TimerTask class. -// -// Copyright (c) 2009, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// SPDX-License-Identifier: BSL-1.0 -// - - -#ifndef Util_TimerTask_INCLUDED -#define Util_TimerTask_INCLUDED - - -#include "Poco/Util/Util.h" -#include "Poco/Runnable.h" -#include "Poco/RefCountedObject.h" -#include "Poco/AutoPtr.h" -#include "Poco/Timestamp.h" - - -namespace Poco { -namespace Util { - - -class Util_API TimerTask: public Poco::RefCountedObject, public Poco::Runnable - /// A task that can be scheduled for one-time or - /// repeated execution by a Timer. - /// - /// This is an abstract class. Subclasses must override the run() member - /// function to implement the actual task logic. -{ -public: - typedef Poco::AutoPtr<TimerTask> Ptr; - - TimerTask(); - /// Creates the TimerTask. - - void cancel(); - /// Cancels the execution of the timer. - /// If the task has been scheduled for one-time execution and has - /// not yet run, or has not yet been scheduled, it will never run. - /// If the task has been scheduled for repeated execution, it will never - /// run again. If the task is running when this call occurs, the task - /// will run to completion, but will never run again. - /// - /// Warning: A TimerTask that has been cancelled must not be scheduled again. - /// An attempt to do so results in a Poco::Util::IllegalStateException being thrown. - - bool isCancelled() const; - /// Returns true iff the TimerTask has been cancelled by a call - /// to cancel(). - - Poco::Timestamp lastExecution() const; - /// Returns the time of the last execution of the timer task. - /// - /// Returns 0 if the timer has never been executed. - -protected: - ~TimerTask(); - /// Destroys the TimerTask. - -private: - TimerTask(const TimerTask&); - TimerTask& operator = (const TimerTask&); - - Poco::Timestamp _lastExecution; - bool _isCancelled; - - friend class TaskNotification; -}; - - -// -// inlines -// -inline bool TimerTask::isCancelled() const -{ - return _isCancelled; -} - - -inline Poco::Timestamp TimerTask::lastExecution() const -{ - return _lastExecution; -} - - -} } // namespace Poco::Util - - -#endif // Util_TimerTask_INCLUDED +// +// TimerTask.h +// +// Library: Util +// Package: Timer +// Module: TimerTask +// +// Definition of the TimerTask class. +// +// Copyright (c) 2009, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Util_TimerTask_INCLUDED +#define Util_TimerTask_INCLUDED + + +#include "Poco/Util/Util.h" +#include "Poco/Runnable.h" +#include "Poco/RefCountedObject.h" +#include "Poco/AutoPtr.h" +#include "Poco/Timestamp.h" + + +namespace Poco { +namespace Util { + + +class Util_API TimerTask: public Poco::RefCountedObject, public Poco::Runnable + /// A task that can be scheduled for one-time or + /// repeated execution by a Timer. + /// + /// This is an abstract class. Subclasses must override the run() member + /// function to implement the actual task logic. +{ +public: + typedef Poco::AutoPtr<TimerTask> Ptr; + + TimerTask(); + /// Creates the TimerTask. + + void cancel(); + /// Cancels the execution of the timer. + /// If the task has been scheduled for one-time execution and has + /// not yet run, or has not yet been scheduled, it will never run. + /// If the task has been scheduled for repeated execution, it will never + /// run again. If the task is running when this call occurs, the task + /// will run to completion, but will never run again. + /// + /// Warning: A TimerTask that has been cancelled must not be scheduled again. + /// An attempt to do so results in a Poco::Util::IllegalStateException being thrown. + + bool isCancelled() const; + /// Returns true iff the TimerTask has been cancelled by a call + /// to cancel(). + + Poco::Timestamp lastExecution() const; + /// Returns the time of the last execution of the timer task. + /// + /// Returns 0 if the timer has never been executed. + +protected: + ~TimerTask(); + /// Destroys the TimerTask. + +private: + TimerTask(const TimerTask&); + TimerTask& operator = (const TimerTask&); + + Poco::Timestamp _lastExecution; + bool _isCancelled; + + friend class TaskNotification; +}; + + +// +// inlines +// +inline bool TimerTask::isCancelled() const +{ + return _isCancelled; +} + + +inline Poco::Timestamp TimerTask::lastExecution() const +{ + return _lastExecution; +} + + +} } // namespace Poco::Util + + +#endif // Util_TimerTask_INCLUDED diff --git a/contrib/libs/poco/Util/include/Poco/Util/TimerTaskAdapter.h b/contrib/libs/poco/Util/include/Poco/Util/TimerTaskAdapter.h index 66a507f7a3..32ff3b981a 100644 --- a/contrib/libs/poco/Util/include/Poco/Util/TimerTaskAdapter.h +++ b/contrib/libs/poco/Util/include/Poco/Util/TimerTaskAdapter.h @@ -1,69 +1,69 @@ -// -// TimerTaskAdapter.h -// -// Library: Util -// Package: Timer -// Module: TimerTaskAdapter -// -// Definition of the TimerTaskAdapter class template. -// -// Copyright (c) 2009, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// SPDX-License-Identifier: BSL-1.0 -// - - -#ifndef Util_TimerTaskAdapter_INCLUDED -#define Util_TimerTaskAdapter_INCLUDED - - -#include "Poco/Util/Util.h" -#include "Poco/Util/TimerTask.h" - - -namespace Poco { -namespace Util { - - -template <class C> -class TimerTaskAdapter: public TimerTask - /// This class template simplifies the implementation - /// of TimerTask objects by allowing a member function - /// of an object to be called as task. -{ -public: - typedef void (C::*Callback)(TimerTask&); - - TimerTaskAdapter(C& object, Callback method): _pObject(&object), _method(method) - /// Creates the TimerTaskAdapter, using the given - /// object and its member function as task target. - /// - /// The member function must accept one argument, - /// a reference to a TimerTask object. - { - } - - void run() - { - (_pObject->*_method)(*this); - } - -protected: - ~TimerTaskAdapter() - /// Destroys the TimerTaskAdapter. - { - } - -private: - TimerTaskAdapter(); - - C* _pObject; - Callback _method; -}; - - -} } // namespace Poco::Util - - -#endif // Util_TimerTaskAdapter_INCLUDED +// +// TimerTaskAdapter.h +// +// Library: Util +// Package: Timer +// Module: TimerTaskAdapter +// +// Definition of the TimerTaskAdapter class template. +// +// Copyright (c) 2009, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Util_TimerTaskAdapter_INCLUDED +#define Util_TimerTaskAdapter_INCLUDED + + +#include "Poco/Util/Util.h" +#include "Poco/Util/TimerTask.h" + + +namespace Poco { +namespace Util { + + +template <class C> +class TimerTaskAdapter: public TimerTask + /// This class template simplifies the implementation + /// of TimerTask objects by allowing a member function + /// of an object to be called as task. +{ +public: + typedef void (C::*Callback)(TimerTask&); + + TimerTaskAdapter(C& object, Callback method): _pObject(&object), _method(method) + /// Creates the TimerTaskAdapter, using the given + /// object and its member function as task target. + /// + /// The member function must accept one argument, + /// a reference to a TimerTask object. + { + } + + void run() + { + (_pObject->*_method)(*this); + } + +protected: + ~TimerTaskAdapter() + /// Destroys the TimerTaskAdapter. + { + } + +private: + TimerTaskAdapter(); + + C* _pObject; + Callback _method; +}; + + +} } // namespace Poco::Util + + +#endif // Util_TimerTaskAdapter_INCLUDED diff --git a/contrib/libs/poco/Util/include/Poco/Util/Units.h b/contrib/libs/poco/Util/include/Poco/Util/Units.h index 382b402f15..e7f3869dda 100644 --- a/contrib/libs/poco/Util/include/Poco/Util/Units.h +++ b/contrib/libs/poco/Util/include/Poco/Util/Units.h @@ -1,1298 +1,1298 @@ -// -// Units.h -// -// Library: Util -// Package: Units -// Module: Units -// -// Definitions for the C++ Units library. -// -// Copyright (c) 2007-2010, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// SPDX-License-Identifier: BSL-1.0 -// -// Adapted for POCO from the following source: -// -// C++ Units by Calum Grant -// -// Written by Calum Grant -// Copyright (C) Calum Grant 2007 -// -// Home page: http://calumgrant.net/units -// File location: http://calumgrant.net/units/units.hpp -// Manual: http://calumgrant.net/units/units.html -// -// Copying permitted under the terms of the Boost software license. -// - - -#ifndef Util_Units_INCLUDED -#define Util_Units_INCLUDED - - -#include "Poco/Util/Util.h" -#include <cmath> - - -namespace Poco { -namespace Util { -namespace Units { - - -namespace Internal -{ - template <typename T1, typename T2> struct Convert; - struct None; - template <int Num, int Den, int Div=Num/Den, int Mod=Num%Den> - struct FixedPower; -} - - -template <typename Unit1, typename Unit2> -struct Compose; - /// Construct a unit equivalent to Unit1*Unit2 - - -template <typename U, int Num, int Den = 1> -struct Scale; - /// Constructs a unit equivalent to U*Num/Den - - -template <typename U, int Num, int Den = 1> -struct Translate; - /// Constructs a Unit equivalent to U+Num/Den - - -template <typename U, int Num, int Den = 1> -struct Power; - /// Constructs a Unit equivalent to U^(Num/Den) - - -typedef Power<Internal::None, 0> Unit; - /// A unit which is effectively no units at all. - - -template <typename V, typename U> -class Value - /// A Value with a unit. - /// - V is the type you are storing - /// - U is the unit of the Value - /// - /// This class is usually not used directly; - /// client code should use the typedef'd - /// instantiations defined in the Values and - /// Constants namespace. - /// - /// Example: - /// - /// using namespace Poco::Util::Units::Values; - /// - /// std::cout << "One mile is " << km(mile(1)) << std::endl; - /// // Output: One mile is 1.60934 km - /// - /// std::cout << "Flow rate is " << m3(mile(1)*inch(80)*foot(9))/s(minute(5)); - /// // Output: Flow rate is 29.9026 (m)^3.(s)^-1 - /// - /// hours h; - /// h = cm(3); // Compile-time error: incompatible units - /// h = 4; // Compile-time error: 4 of what? - /// h = days(4); // Ok: h is 96 hours -{ -public: - typedef V ValueType; - typedef U Unit; - - Value(): _rep() - { - } - - explicit Value(const ValueType& v): _rep(v) - { - } - - template <typename OV, typename OU> - Value(const Value<OV, OU>& v): - _rep(Internal::Convert<OU, U>::fn(v.get())) - { - } - - const ValueType& get() const - { - return _rep; - } - - template <typename OV, typename OU> - Value& operator = (const Value<OV, OU>& other) +// +// Units.h +// +// Library: Util +// Package: Units +// Module: Units +// +// Definitions for the C++ Units library. +// +// Copyright (c) 2007-2010, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// +// Adapted for POCO from the following source: +// +// C++ Units by Calum Grant +// +// Written by Calum Grant +// Copyright (C) Calum Grant 2007 +// +// Home page: http://calumgrant.net/units +// File location: http://calumgrant.net/units/units.hpp +// Manual: http://calumgrant.net/units/units.html +// +// Copying permitted under the terms of the Boost software license. +// + + +#ifndef Util_Units_INCLUDED +#define Util_Units_INCLUDED + + +#include "Poco/Util/Util.h" +#include <cmath> + + +namespace Poco { +namespace Util { +namespace Units { + + +namespace Internal +{ + template <typename T1, typename T2> struct Convert; + struct None; + template <int Num, int Den, int Div=Num/Den, int Mod=Num%Den> + struct FixedPower; +} + + +template <typename Unit1, typename Unit2> +struct Compose; + /// Construct a unit equivalent to Unit1*Unit2 + + +template <typename U, int Num, int Den = 1> +struct Scale; + /// Constructs a unit equivalent to U*Num/Den + + +template <typename U, int Num, int Den = 1> +struct Translate; + /// Constructs a Unit equivalent to U+Num/Den + + +template <typename U, int Num, int Den = 1> +struct Power; + /// Constructs a Unit equivalent to U^(Num/Den) + + +typedef Power<Internal::None, 0> Unit; + /// A unit which is effectively no units at all. + + +template <typename V, typename U> +class Value + /// A Value with a unit. + /// - V is the type you are storing + /// - U is the unit of the Value + /// + /// This class is usually not used directly; + /// client code should use the typedef'd + /// instantiations defined in the Values and + /// Constants namespace. + /// + /// Example: + /// + /// using namespace Poco::Util::Units::Values; + /// + /// std::cout << "One mile is " << km(mile(1)) << std::endl; + /// // Output: One mile is 1.60934 km + /// + /// std::cout << "Flow rate is " << m3(mile(1)*inch(80)*foot(9))/s(minute(5)); + /// // Output: Flow rate is 29.9026 (m)^3.(s)^-1 + /// + /// hours h; + /// h = cm(3); // Compile-time error: incompatible units + /// h = 4; // Compile-time error: 4 of what? + /// h = days(4); // Ok: h is 96 hours +{ +public: + typedef V ValueType; + typedef U Unit; + + Value(): _rep() { - _rep = Value(other).get(); - return *this; - } - - template <typename OV, typename OU> - Value operator + (const Value<OV, OU>& other) const + } + + explicit Value(const ValueType& v): _rep(v) { - return Value(get() + Value(other).get()); - } - - template <typename OV, typename OU> - Value& operator += (const Value<OV, OU>& other) + } + + template <typename OV, typename OU> + Value(const Value<OV, OU>& v): + _rep(Internal::Convert<OU, U>::fn(v.get())) + { + } + + const ValueType& get() const { - _rep += Value(other).get(); - return *this; - } - - template <typename OV, typename OU> - Value& operator -= (const Value<OV, OU>& other) - { - _rep -= Value(other).get(); - return *this; - } - - template <typename OV, typename OU> - Value operator - (const Value<OV, OU>& other) const - { - return Value(get() - Value(other).get()); - } - - Value operator - () const - { - return Value(-get()); - } - - template <typename OV, typename OU> - Value<V, Compose<U, OU> > - operator * (const Value<OV, OU>& other) const - { - return Value<V, Compose<U, OU> >(get() * other.get()); - } - - Value operator * (const ValueType& v) const - { - return Value(get() * v); - } - - Value& operator *= (const ValueType& v) + return _rep; + } + + template <typename OV, typename OU> + Value& operator = (const Value<OV, OU>& other) + { + _rep = Value(other).get(); + return *this; + } + + template <typename OV, typename OU> + Value operator + (const Value<OV, OU>& other) const + { + return Value(get() + Value(other).get()); + } + + template <typename OV, typename OU> + Value& operator += (const Value<OV, OU>& other) + { + _rep += Value(other).get(); + return *this; + } + + template <typename OV, typename OU> + Value& operator -= (const Value<OV, OU>& other) + { + _rep -= Value(other).get(); + return *this; + } + + template <typename OV, typename OU> + Value operator - (const Value<OV, OU>& other) const + { + return Value(get() - Value(other).get()); + } + + Value operator - () const + { + return Value(-get()); + } + + template <typename OV, typename OU> + Value<V, Compose<U, OU> > + operator * (const Value<OV, OU>& other) const + { + return Value<V, Compose<U, OU> >(get() * other.get()); + } + + Value operator * (const ValueType& v) const + { + return Value(get() * v); + } + + Value& operator *= (const ValueType& v) + { + _rep *= v; + return *this; + } + + template <typename OV, typename OU> + Value<V, Compose<U, Power<OU, -1> > > operator / (const Value<OV, OU>& other) const + { + return Value<V, Compose<U, Power<OU, -1> > >(get() / other.get()); + } + + Value operator / (const ValueType& v) const + { + return Value(get() / v); + } + + Value& operator /= (const ValueType& v) + { + _rep /= v; + return *this; + } + + template <typename OV, typename OU> + bool operator == (const Value<OV, OU>& other) const + { + return get() == Value(other).get(); + } + + template <typename OV, typename OU> + bool operator != (const Value<OV, OU>& other) const + { + return get() != Value(other).get(); + } + + template <typename OV, typename OU> + bool operator < (const Value<OV, OU>& other) const + { + return get() < Value(other).get(); + } + + template <typename OV, typename OU> + bool operator <= (const Value<OV, OU>& other) const + { + return get() <= Value(other).get(); + } + + template <typename OV, typename OU> + bool operator > (const Value<OV, OU>& other) const + { + return get() > Value(other).get(); + } + + template <typename OV, typename OU> + bool operator >= (const Value<OV, OU>& other) const + { + return get() >= Value(other).get(); + } + + Value& operator ++ () { - _rep *= v; + ++_rep; return *this; - } - - template <typename OV, typename OU> - Value<V, Compose<U, Power<OU, -1> > > operator / (const Value<OV, OU>& other) const - { - return Value<V, Compose<U, Power<OU, -1> > >(get() / other.get()); - } - - Value operator / (const ValueType& v) const + } + + Value operator ++ (int) { - return Value(get() / v); - } - - Value& operator /= (const ValueType& v) + Value v = *this; + ++_rep; + return v; + } + + Value& operator -- () { - _rep /= v; + --_rep; return *this; - } - - template <typename OV, typename OU> - bool operator == (const Value<OV, OU>& other) const - { - return get() == Value(other).get(); - } - - template <typename OV, typename OU> - bool operator != (const Value<OV, OU>& other) const + } + + Value operator -- (int) { - return get() != Value(other).get(); - } - - template <typename OV, typename OU> - bool operator < (const Value<OV, OU>& other) const - { - return get() < Value(other).get(); - } - - template <typename OV, typename OU> - bool operator <= (const Value<OV, OU>& other) const - { - return get() <= Value(other).get(); - } - - template <typename OV, typename OU> - bool operator > (const Value<OV, OU>& other) const - { - return get() > Value(other).get(); - } - - template <typename OV, typename OU> - bool operator >= (const Value<OV, OU>& other) const - { - return get() >= Value(other).get(); - } - - Value& operator ++ () - { - ++_rep; - return *this; - } - - Value operator ++ (int) - { - Value v = *this; - ++_rep; - return v; - } - - Value& operator -- () - { - --_rep; - return *this; - } - - Value operator -- (int) - { - Value v = *this; - --_rep; - return v; - } - -private: - ValueType _rep; -}; - - -template <typename V, typename U> -Value<V, Power<U, -1> > operator / (const V& a, const Value<V, U>& b) -{ - return Value<V, Power<U, -1> >(a / b.get()); -} - - -template <typename V, typename U> -Value<V, U > operator * (const V& a, const Value<V, U>& b) -{ - return Value<V, U>(a * b.get()); -} - - -template <typename V, typename U> -Value<V, Power<U, 1, 2> > sqrt(const Value<V, U>& a) -{ - return Value<V, Power<U, 1, 2> >(std::sqrt(a.get())); -} - - -template <typename V, typename U> -Value<V, Power<U, 2, 1> > square(const Value<V, U>& a) -{ - return Value<V, Power<U, 2, 1> >(std::pow(a.get(), 2)); -} - - -template <typename V, typename U> -Value<V, Power<U, 3, 1> > cube(const Value<V, U>& a) -{ - return Value<V, Power<U, 3, 1> >(std::pow(a.get(), 3)); -} - - -template <int Num, int Den, typename V, typename U> -Value<V, Power<U, Num, Den> > raise(const Value<V, U>& a) -{ - return Value<V, Power<U, Num, Den> >(Internal::FixedPower<Num, Den>::Power(a.get())); -} - - -namespace Internal -{ + Value v = *this; + --_rep; + return v; + } + +private: + ValueType _rep; +}; + + +template <typename V, typename U> +Value<V, Power<U, -1> > operator / (const V& a, const Value<V, U>& b) +{ + return Value<V, Power<U, -1> >(a / b.get()); +} + + +template <typename V, typename U> +Value<V, U > operator * (const V& a, const Value<V, U>& b) +{ + return Value<V, U>(a * b.get()); +} + + +template <typename V, typename U> +Value<V, Power<U, 1, 2> > sqrt(const Value<V, U>& a) +{ + return Value<V, Power<U, 1, 2> >(std::sqrt(a.get())); +} + + +template <typename V, typename U> +Value<V, Power<U, 2, 1> > square(const Value<V, U>& a) +{ + return Value<V, Power<U, 2, 1> >(std::pow(a.get(), 2)); +} + + +template <typename V, typename U> +Value<V, Power<U, 3, 1> > cube(const Value<V, U>& a) +{ + return Value<V, Power<U, 3, 1> >(std::pow(a.get(), 3)); +} + + +template <int Num, int Den, typename V, typename U> +Value<V, Power<U, Num, Den> > raise(const Value<V, U>& a) +{ + return Value<V, Power<U, Num, Den> >(Internal::FixedPower<Num, Den>::Power(a.get())); +} + + +namespace Internal +{ + template <typename T1, typename T2> + struct Convertible; + + template <typename U> + struct ScalingFactor; + template <typename T1, typename T2> - struct Convertible; - - template <typename U> - struct ScalingFactor; - - template <typename T1, typename T2> - struct Convert3 - /// Converts T1 to T2. - /// Stage 3 - performed after Stage 1 and Stage 2. - /// The reason we perform Convert in stages is so that the compiler - /// can resolve templates in the order we want it to. - { - template <typename V> - static V fn(const V& v) - /// The default implementation assumes that the two quantities are in compatible - /// Units up to some scaling factor. Find the scaling factor and apply it. - { - return v * ScalingFactor<T2>::template fn<V>() / ScalingFactor<T1>::template fn<V>(); - } - }; - - template <typename T1, typename T2> - struct Convert2 - /// Converts T1 to T2. - /// Template matches the first argument (T1), - /// this is the fall-through to Convert3. - { - template <typename V> - static V fn(const V& v) - { - return Convert3<T1,T2>::fn(v); - } - }; - - template <typename T1, typename T2> - struct Convert - /// Converts T1 to T2. - /// If you really want to implement your own conversion routine, - /// specialize this template. - /// The default implementation falls through to Convert2. - { - /// If this fails, then T1 is not Convertible to T2: - poco_static_assert ((Convertible<T1,T2>::Value)); - - template <typename V> - static V fn(const V& v) - { - return Convert2<T1,T2>::fn(v); - } - }; - - template <typename T> - struct Convert<T, T> - // Trivial conversion to the same type. - { - template <typename U> - static const U& fn(const U& u) { return u; } - }; - - template <typename T> - struct Convert3<T, T> - // Convert to same type. - { - template <typename U> - static const U& fn(const U& u) { return u; } - }; - - template <typename T, typename U, int Num, int Den> - struct Convert2<Scale<T, Num, Den>, U> - // Convert from a scaled Unit. - { - template <typename V> - static V fn(const V& v) - { - return Convert<T, U>::fn((v * Den)/Num); - } - }; - - template <typename T, typename U, int Num, int Den> - struct Convert3<T, Scale<U, Num, Den> > - // Convert to a scaled Unit. - { - template <typename V> - static V fn(const V& v) - { - return (Convert<T, U>::fn(v) * Num)/ Den; - } - }; - - template <typename T, typename U, int Num, int Den> - struct Convert2<Translate<T, Num, Den>, U> - // Convert from a translated Unit. - { - template <typename V> - static V fn(const V& v) - { - return Convert<T, U>::fn(v - static_cast<V>(Num) / static_cast<V>(Den)); - } - }; - - template <typename T, typename U, int Num, int Den> - struct Convert3<T, Translate<U, Num, Den> > - // Convert to a translated Unit. - { - template <typename V> - static V fn(const V& v) - { - return Convert<T, U>::fn(v) + static_cast<V>(Num) / static_cast<V>(Den); - } - }; - - template <typename Term, typename List> - struct CountTerms - /// Count the power to which Unit Term is raised in the Unit List. - /// Returns a rational num/den of the power of term Term in List. - /// The default assumes that Term is not found (num/den=0). - { - static const int num = 0; - static const int den = 1; - }; - - template <typename Term> - struct CountTerms<Term, Term> - { - static const int num = 1; - static const int den = 1; - }; - - template <typename Term, typename U, int N, int D> - struct CountTerms<Term, Scale<U, N, D> > - // CountTerms ignores scaling factors - that is taken care of by ScalingFactor. - { - typedef CountTerms<Term, U> result; - static const int num = result::num; - static const int den = result::den; - }; - - template <typename Term, typename U, int N, int D> - struct CountTerms<Term, Translate<U, N, D> > - // CountTerms ignores translation. - { - typedef CountTerms<Term, U> result; - static const int num = result::num; - static const int den = result::den; - }; - - template <typename Term, typename T1, typename T2> - struct CountTerms<Term, Compose<T1,T2> > - // Addition of fractions. - { - typedef CountTerms<Term, T1> result1; - typedef CountTerms<Term, T2> result2; - static const int num = result1::num * result2::den + result1::den * result2::num; - static const int den = result1::den * result2::den; - }; - - template <typename Term, typename U, int N, int D> - struct CountTerms<Term, Power<U, N, D> > - // Multiplication of fractions. - { - typedef CountTerms<Term, U> result; - static const int num = N * result::num; - static const int den = D * result::den; - }; - - template <typename Term, typename T1, typename T2> - struct CheckTermsEqual - /// Counts the power of the Unit Term in Units T1 and T2. - /// Reports if they are equal, using equality of fractions. - /// Does a depth-first search of the Unit "Term", - /// or counts the terms in the default case. - { - typedef CountTerms<Term, T1> count1; - typedef CountTerms<Term, T2> count2; - - static const bool Value = - count1::num * count2::den == - count1::den * count2::num; - }; - - template <typename U, int N, int D, typename T1, typename T2> - struct CheckTermsEqual<Power<U, N, D>, T1, T2 > - { - static const bool Value = CheckTermsEqual<U, T1, T2>::Value; - }; - - template <typename U, int N, int D, typename T1, typename T2> - struct CheckTermsEqual<Scale<U, N, D>, T1, T2 > - { - static const bool Value = CheckTermsEqual<U, T1, T2>::Value; - }; - - template <typename U, int N, int D, typename T1, typename T2> - struct CheckTermsEqual<Translate<U, N, D>, T1, T2 > - { - static const bool Value = CheckTermsEqual<U, T1, T2>::Value; - }; - - template <typename T1, typename T2, typename T3, typename T4> - struct CheckTermsEqual<Compose<T1,T2>,T3,T4> - { - static const bool Value = - CheckTermsEqual<T1, T3, T4>::Value && - CheckTermsEqual<T2, T3, T4>::Value; - }; - + struct Convert3 + /// Converts T1 to T2. + /// Stage 3 - performed after Stage 1 and Stage 2. + /// The reason we perform Convert in stages is so that the compiler + /// can resolve templates in the order we want it to. + { + template <typename V> + static V fn(const V& v) + /// The default implementation assumes that the two quantities are in compatible + /// Units up to some scaling factor. Find the scaling factor and apply it. + { + return v * ScalingFactor<T2>::template fn<V>() / ScalingFactor<T1>::template fn<V>(); + } + }; + template <typename T1, typename T2> - struct Convertible - /// Determines whether two types are Convertible. - /// Counts the powers in the LHS and RHS and ensures they are equal. - { - static const bool Value = - CheckTermsEqual<T1,T1,T2>::Value && - CheckTermsEqual<T2,T1,T2>::Value; - }; - - template <int Num, int Den, int Div, int Mod> - struct FixedPower - /// A functor that raises a Value to the power Num/Den. - /// The template is specialised for efficiency - /// so that we don't always have to call the std::power function. - { - template <typename T> static T Power(const T& t) - { - return std::pow(t, static_cast<T>(Num)/static_cast<T>(Den)); - } - }; - - template <int N, int D> - struct FixedPower<N, D, 1, 0> - { - template <typename T> static const T& Power(const T& t) - { - return t; - } - }; - - template <int N, int D> - struct FixedPower<N, D, 2, 0> - { - template <typename T> static T Power(const T& t) - { - return t*t; - } - }; - - template <int N, int D> - struct FixedPower<N, D, 3, 0> - { - template <typename T> static T Power(const T& t) - { - return t*t*t; - } - }; - - template <int N, int D> - struct FixedPower<N, D, 4, 0> - { - template <typename T> static const T& Power(const T& t) - { - T u = t*t; - return u*u; - } - }; - - template <int N, int D> - struct FixedPower<N, D, -1, 0> - { - template <typename T> static T Power(const T& t) - { - return 1/t; - } - }; - - template <int N, int D> - struct FixedPower<N, D, -2, 0> - { - template <typename T> static T Power(const T& t) - { - return 1/(t*t); - } - }; - - template <int N, int D> - struct FixedPower<N, D, 0, 0> - { - template <typename T> static T Power(const T& t) - { - return 1; - } - }; - - template <typename U> - struct ScalingFactor - /// Determine the scaling factor of a Unit in relation to its "base" Units. - /// Default is that U is a primitive Unit and is not scaled. - { - template <typename T> - static T fn() { return 1; } - }; - - template <typename U1, typename U2> - struct ScalingFactor< Compose<U1, U2> > - { - template <typename T> - static T fn() - { - return - ScalingFactor<U1>::template fn<T>() * - ScalingFactor<U2>::template fn<T>(); - } - }; - - template <typename U, int N, int D> - struct ScalingFactor< Scale<U, N, D> > - { - template <typename T> - static T fn() - { - return - ScalingFactor<U>::template fn<T>() * - static_cast<T>(N) / static_cast<T>(D); - } - }; - - template <typename U, int N, int D> - struct ScalingFactor< Power<U, N, D> > - { - template <typename T> - static T fn() - { - return FixedPower<N, D>::Power(ScalingFactor<U>::template fn<T>()); - } + struct Convert2 + /// Converts T1 to T2. + /// Template matches the first argument (T1), + /// this is the fall-through to Convert3. + { + template <typename V> + static V fn(const V& v) + { + return Convert3<T1,T2>::fn(v); + } + }; + + template <typename T1, typename T2> + struct Convert + /// Converts T1 to T2. + /// If you really want to implement your own conversion routine, + /// specialize this template. + /// The default implementation falls through to Convert2. + { + /// If this fails, then T1 is not Convertible to T2: + poco_static_assert ((Convertible<T1,T2>::Value)); + + template <typename V> + static V fn(const V& v) + { + return Convert2<T1,T2>::fn(v); + } + }; + + template <typename T> + struct Convert<T, T> + // Trivial conversion to the same type. + { + template <typename U> + static const U& fn(const U& u) { return u; } + }; + + template <typename T> + struct Convert3<T, T> + // Convert to same type. + { + template <typename U> + static const U& fn(const U& u) { return u; } + }; + + template <typename T, typename U, int Num, int Den> + struct Convert2<Scale<T, Num, Den>, U> + // Convert from a scaled Unit. + { + template <typename V> + static V fn(const V& v) + { + return Convert<T, U>::fn((v * Den)/Num); + } + }; + + template <typename T, typename U, int Num, int Den> + struct Convert3<T, Scale<U, Num, Den> > + // Convert to a scaled Unit. + { + template <typename V> + static V fn(const V& v) + { + return (Convert<T, U>::fn(v) * Num)/ Den; + } + }; + + template <typename T, typename U, int Num, int Den> + struct Convert2<Translate<T, Num, Den>, U> + // Convert from a translated Unit. + { + template <typename V> + static V fn(const V& v) + { + return Convert<T, U>::fn(v - static_cast<V>(Num) / static_cast<V>(Den)); + } + }; + + template <typename T, typename U, int Num, int Den> + struct Convert3<T, Translate<U, Num, Den> > + // Convert to a translated Unit. + { + template <typename V> + static V fn(const V& v) + { + return Convert<T, U>::fn(v) + static_cast<V>(Num) / static_cast<V>(Den); + } + }; + + template <typename Term, typename List> + struct CountTerms + /// Count the power to which Unit Term is raised in the Unit List. + /// Returns a rational num/den of the power of term Term in List. + /// The default assumes that Term is not found (num/den=0). + { + static const int num = 0; + static const int den = 1; + }; + + template <typename Term> + struct CountTerms<Term, Term> + { + static const int num = 1; + static const int den = 1; }; - template <typename U, int N, int D> - struct ScalingFactor< Translate<U, N, D> > - { - template <typename T> - static T fn() + template <typename Term, typename U, int N, int D> + struct CountTerms<Term, Scale<U, N, D> > + // CountTerms ignores scaling factors - that is taken care of by ScalingFactor. + { + typedef CountTerms<Term, U> result; + static const int num = result::num; + static const int den = result::den; + }; + + template <typename Term, typename U, int N, int D> + struct CountTerms<Term, Translate<U, N, D> > + // CountTerms ignores translation. + { + typedef CountTerms<Term, U> result; + static const int num = result::num; + static const int den = result::den; + }; + + template <typename Term, typename T1, typename T2> + struct CountTerms<Term, Compose<T1,T2> > + // Addition of fractions. + { + typedef CountTerms<Term, T1> result1; + typedef CountTerms<Term, T2> result2; + static const int num = result1::num * result2::den + result1::den * result2::num; + static const int den = result1::den * result2::den; + }; + + template <typename Term, typename U, int N, int D> + struct CountTerms<Term, Power<U, N, D> > + // Multiplication of fractions. + { + typedef CountTerms<Term, U> result; + static const int num = N * result::num; + static const int den = D * result::den; + }; + + template <typename Term, typename T1, typename T2> + struct CheckTermsEqual + /// Counts the power of the Unit Term in Units T1 and T2. + /// Reports if they are equal, using equality of fractions. + /// Does a depth-first search of the Unit "Term", + /// or counts the terms in the default case. + { + typedef CountTerms<Term, T1> count1; + typedef CountTerms<Term, T2> count2; + + static const bool Value = + count1::num * count2::den == + count1::den * count2::num; + }; + + template <typename U, int N, int D, typename T1, typename T2> + struct CheckTermsEqual<Power<U, N, D>, T1, T2 > + { + static const bool Value = CheckTermsEqual<U, T1, T2>::Value; + }; + + template <typename U, int N, int D, typename T1, typename T2> + struct CheckTermsEqual<Scale<U, N, D>, T1, T2 > + { + static const bool Value = CheckTermsEqual<U, T1, T2>::Value; + }; + + template <typename U, int N, int D, typename T1, typename T2> + struct CheckTermsEqual<Translate<U, N, D>, T1, T2 > + { + static const bool Value = CheckTermsEqual<U, T1, T2>::Value; + }; + + template <typename T1, typename T2, typename T3, typename T4> + struct CheckTermsEqual<Compose<T1,T2>,T3,T4> + { + static const bool Value = + CheckTermsEqual<T1, T3, T4>::Value && + CheckTermsEqual<T2, T3, T4>::Value; + }; + + template <typename T1, typename T2> + struct Convertible + /// Determines whether two types are Convertible. + /// Counts the powers in the LHS and RHS and ensures they are equal. + { + static const bool Value = + CheckTermsEqual<T1,T1,T2>::Value && + CheckTermsEqual<T2,T1,T2>::Value; + }; + + template <int Num, int Den, int Div, int Mod> + struct FixedPower + /// A functor that raises a Value to the power Num/Den. + /// The template is specialised for efficiency + /// so that we don't always have to call the std::power function. + { + template <typename T> static T Power(const T& t) + { + return std::pow(t, static_cast<T>(Num)/static_cast<T>(Den)); + } + }; + + template <int N, int D> + struct FixedPower<N, D, 1, 0> + { + template <typename T> static const T& Power(const T& t) + { + return t; + } + }; + + template <int N, int D> + struct FixedPower<N, D, 2, 0> + { + template <typename T> static T Power(const T& t) + { + return t*t; + } + }; + + template <int N, int D> + struct FixedPower<N, D, 3, 0> + { + template <typename T> static T Power(const T& t) + { + return t*t*t; + } + }; + + template <int N, int D> + struct FixedPower<N, D, 4, 0> + { + template <typename T> static const T& Power(const T& t) + { + T u = t*t; + return u*u; + } + }; + + template <int N, int D> + struct FixedPower<N, D, -1, 0> + { + template <typename T> static T Power(const T& t) + { + return 1/t; + } + }; + + template <int N, int D> + struct FixedPower<N, D, -2, 0> + { + template <typename T> static T Power(const T& t) + { + return 1/(t*t); + } + }; + + template <int N, int D> + struct FixedPower<N, D, 0, 0> + { + template <typename T> static T Power(const T& t) + { + return 1; + } + }; + + template <typename U> + struct ScalingFactor + /// Determine the scaling factor of a Unit in relation to its "base" Units. + /// Default is that U is a primitive Unit and is not scaled. + { + template <typename T> + static T fn() { return 1; } + }; + + template <typename U1, typename U2> + struct ScalingFactor< Compose<U1, U2> > + { + template <typename T> + static T fn() + { + return + ScalingFactor<U1>::template fn<T>() * + ScalingFactor<U2>::template fn<T>(); + } + }; + + template <typename U, int N, int D> + struct ScalingFactor< Scale<U, N, D> > + { + template <typename T> + static T fn() + { + return + ScalingFactor<U>::template fn<T>() * + static_cast<T>(N) / static_cast<T>(D); + } + }; + + template <typename U, int N, int D> + struct ScalingFactor< Power<U, N, D> > + { + template <typename T> + static T fn() + { + return FixedPower<N, D>::Power(ScalingFactor<U>::template fn<T>()); + } + }; + + template <typename U, int N, int D> + struct ScalingFactor< Translate<U, N, D> > + { + template <typename T> + static T fn() + { + return ScalingFactor<U>::template fn<T>(); + } + }; +} // namespace Internal + + +/// +/// Display +/// + + +#define UNIT_DISPLAY_NAME(Unit, string) \ + template <> \ + struct OutputUnit<Unit> \ + { \ + template <typename Stream> \ + static void fn(Stream& os) \ + { \ + os << string; \ + } \ + } + + +namespace Internal +{ + template <typename U> + struct OutputUnit2 + /// The default Unit formatting mechanism. + { + template <typename Stream> + static void fn(Stream &os) + { + os << "Units"; + } + }; +} + + +template <typename U> +struct OutputUnit + /// Functor to write Unit text to stream. +{ + template <typename Stream> + static void fn(Stream &os) + { + Internal::OutputUnit2<U>::fn(os); + } +}; + + +UNIT_DISPLAY_NAME(Unit, "1"); + + +namespace Internal +{ + template <typename U1, typename U2> + struct OutputUnit2< Compose<U1,U2> > + { + template <typename Stream> + static void fn(Stream &os) { - return ScalingFactor<U>::template fn<T>(); - } - }; -} // namespace Internal - - -/// -/// Display -/// - - -#define UNIT_DISPLAY_NAME(Unit, string) \ - template <> \ - struct OutputUnit<Unit> \ - { \ - template <typename Stream> \ - static void fn(Stream& os) \ - { \ - os << string; \ - } \ - } - - -namespace Internal -{ - template <typename U> - struct OutputUnit2 - /// The default Unit formatting mechanism. - { - template <typename Stream> - static void fn(Stream &os) + OutputUnit<U1>::fn(os); + os << '.'; + OutputUnit<U2>::fn(os); + } + }; + + template <typename U, int Num, int Den> + struct OutputUnit2< Power<U, Num, Den > > + { + template <typename Stream> + static void fn(Stream &os) { - os << "Units"; - } - }; -} - - -template <typename U> -struct OutputUnit - /// Functor to write Unit text to stream. -{ - template <typename Stream> - static void fn(Stream &os) - { - Internal::OutputUnit2<U>::fn(os); - } -}; - - -UNIT_DISPLAY_NAME(Unit, "1"); - - -namespace Internal -{ - template <typename U1, typename U2> - struct OutputUnit2< Compose<U1,U2> > - { - template <typename Stream> - static void fn(Stream &os) - { - OutputUnit<U1>::fn(os); - os << '.'; - OutputUnit<U2>::fn(os); - } - }; - - template <typename U, int Num, int Den> - struct OutputUnit2< Power<U, Num, Den > > - { - template <typename Stream> - static void fn(Stream &os) - { - if(Num!=Den) os << '('; - OutputUnit<U>::fn(os); - if(Num!=Den) - { - os << ')'; - os << '^' << Num; - if(Num%Den) - { - os << '/' << Den; - } - } - } - }; - - template <typename U, int Num, int Den> - struct OutputUnit2< Translate<U, Num, Den > > - { - template <typename Stream> - static void fn(Stream &os) - { - os << '('; - OutputUnit<U>::fn(os); - os << '+' << Num; - if(Den!=1) os << '/' << Den; - os << ')'; - } - }; - - template <typename U, int Num, int Den> - struct OutputUnit2< Scale<U, Num, Den > > - { - template <typename Stream> - static void fn(Stream &os) - { - os << Den; - if(Num != 1) - os << '/' << Num; - os << '.'; - OutputUnit<U>::fn(os); - } - }; -} // namespace Internal - - -template <typename Str, typename V, typename U> -Str& operator << (Str& os, const Value<V, U>& value) -{ - os << value.get() << ' '; - OutputUnit<U>::fn(os); - return os; -} - - -/// -/// Additional Units -/// - - -namespace Units -{ - typedef Poco::Util::Units::Unit Unit; - - // SI base Units: - - struct m; /// meter - struct kg; /// kilogram - struct s; /// second - struct K; /// Kelvin - struct A; /// Ampere - struct mol; /// mole - struct cd; /// candela -} - - -UNIT_DISPLAY_NAME(Units::m, "m"); -UNIT_DISPLAY_NAME(Units::kg, "kg"); -UNIT_DISPLAY_NAME(Units::s, "s"); -UNIT_DISPLAY_NAME(Units::K, "K"); -UNIT_DISPLAY_NAME(Units::A, "A"); -UNIT_DISPLAY_NAME(Units::mol, "mol"); -UNIT_DISPLAY_NAME(Units::cd, "cd"); - - -namespace Units -{ - // SI derived Units: - typedef Compose<m, Power<m, -1> > rad; - typedef Compose<Power<m, 2>, Power<m, -2> > sr; - typedef Power<s, -1> Hz; - typedef Compose<m, Compose<kg, Power<s, -2> > > N; - typedef Compose<N, Power<m, -2> > Pa; - typedef Compose<N, m> J; - typedef Compose<J, Power<s, -1> > W; - typedef Compose<s, A> C; - typedef Compose<W, Power<A, -1> > V; - typedef Compose<C, Power<V, -1> > F; - typedef Compose<V, Power<A, -1> > Ohm; - typedef Compose<A, Power<V, -1> > S; - typedef Compose<V, s> Wb; - typedef Compose<Wb, Power<m, -2> > T; - typedef Compose<Wb, Power<A, -1> > H; - typedef cd lm; - typedef Compose<lm, Power<m, -2> > lx; - typedef Power<s, -1> Bq; - typedef Compose<J, Power<kg, -1> > Gy; - typedef Gy Sv; - typedef Compose<Power<s, -1>,mol> kat; -} - - -UNIT_DISPLAY_NAME(Units::rad, "rad"); -UNIT_DISPLAY_NAME(Units::sr, "sr"); -// UNIT_DISPLAY_NAME(Units::Hz, "Hz"); // Too problematic -UNIT_DISPLAY_NAME(Units::N, "N"); -UNIT_DISPLAY_NAME(Units::Pa, "Pa"); -UNIT_DISPLAY_NAME(Units::J, "J"); -UNIT_DISPLAY_NAME(Units::W, "W"); -UNIT_DISPLAY_NAME(Units::C, "C"); -UNIT_DISPLAY_NAME(Units::V, "V"); -UNIT_DISPLAY_NAME(Units::F, "F"); -UNIT_DISPLAY_NAME(Units::Ohm, "Ohm"); -UNIT_DISPLAY_NAME(Units::S, "S"); -UNIT_DISPLAY_NAME(Units::Wb, "Wb"); -UNIT_DISPLAY_NAME(Units::T, "T"); -UNIT_DISPLAY_NAME(Units::H, "H"); -UNIT_DISPLAY_NAME(Units::lx, "lx"); -UNIT_DISPLAY_NAME(Units::Gy, "Gy"); -UNIT_DISPLAY_NAME(Units::kat, "kat"); - - -namespace Units -{ - // SI prefixes: - template <typename U> struct deca { typedef Scale<U, 1, 10> type; }; - template <typename U> struct hecto { typedef Scale<U, 1, 100> type; }; - template <typename U> struct kilo { typedef Scale<U, 1, 1000> type; }; - template <typename U> struct mega { typedef Scale<typename kilo<U>::type, 1, 1000> type; }; - template <typename U> struct giga { typedef Scale<typename mega<U>::type, 1, 1000> type; }; - template <typename U> struct tera { typedef Scale<typename giga<U>::type, 1, 1000> type; }; - template <typename U> struct peta { typedef Scale<typename tera<U>::type, 1, 1000> type; }; - template <typename U> struct exa { typedef Scale<typename peta<U>::type, 1, 1000> type; }; - template <typename U> struct zetta { typedef Scale<typename exa<U>::type, 1, 1000> type; }; - template <typename U> struct yotta { typedef Scale<typename zetta<U>::type, 1, 1000> type; }; - - template <typename U> struct deci { typedef Scale<U, 10> type; }; - template <typename U> struct centi { typedef Scale<U, 100> type; }; - template <typename U> struct milli { typedef Scale<U, 1000> type; }; - template <typename U> struct micro { typedef Scale<typename milli<U>::type, 1000> type; }; - template <typename U> struct nano { typedef Scale<typename micro<U>::type, 1000> type; }; - template <typename U> struct pico { typedef Scale<typename nano<U>::type, 1000> type; }; - template <typename U> struct femto { typedef Scale<typename pico<U>::type, 1000> type; }; - template <typename U> struct atto { typedef Scale<typename femto<U>::type, 1000> type; }; - template <typename U> struct zepto { typedef Scale<typename atto<U>::type, 1000> type; }; - template <typename U> struct yocto { typedef Scale<typename zepto<U>::type, 1000> type; }; - - - // Some prefixed SI Units: - typedef centi<m>::type cm; - typedef milli<m>::type mm; - typedef kilo<m>::type km; - typedef milli<kg>::type g; - typedef milli<g>::type mg; - typedef milli<s>::type ms; - - - class Prefix - /// Parent class for unit prefixes. - /// Use classes inheriting from this class to scale - /// the values. - { - public: - template <typename T> - Prefix(const T& val, double multiplier = 1, const std::string& prefix = ""): - _pHolder(new Holder<T>(val)), - _multiplier(multiplier), - _prefix(prefix) - { - } - - double value() const - { - return _pHolder->get() * _multiplier; - } - - void addPrefix(std::ostream& os) const + if(Num!=Den) os << '('; + OutputUnit<U>::fn(os); + if(Num!=Den) + { + os << ')'; + os << '^' << Num; + if(Num%Den) + { + os << '/' << Den; + } + } + } + }; + + template <typename U, int Num, int Den> + struct OutputUnit2< Translate<U, Num, Den > > + { + template <typename Stream> + static void fn(Stream &os) { - os << _prefix; - } - - void addUnit(std::ostream& os) const + os << '('; + OutputUnit<U>::fn(os); + os << '+' << Num; + if(Den!=1) os << '/' << Den; + os << ')'; + } + }; + + template <typename U, int Num, int Den> + struct OutputUnit2< Scale<U, Num, Den > > + { + template <typename Stream> + static void fn(Stream &os) { - _pHolder->appendUnit(os); - } - - private: - Prefix(); - - class Placeholder + os << Den; + if(Num != 1) + os << '/' << Num; + os << '.'; + OutputUnit<U>::fn(os); + } + }; +} // namespace Internal + + +template <typename Str, typename V, typename U> +Str& operator << (Str& os, const Value<V, U>& value) +{ + os << value.get() << ' '; + OutputUnit<U>::fn(os); + return os; +} + + +/// +/// Additional Units +/// + + +namespace Units +{ + typedef Poco::Util::Units::Unit Unit; + + // SI base Units: + + struct m; /// meter + struct kg; /// kilogram + struct s; /// second + struct K; /// Kelvin + struct A; /// Ampere + struct mol; /// mole + struct cd; /// candela +} + + +UNIT_DISPLAY_NAME(Units::m, "m"); +UNIT_DISPLAY_NAME(Units::kg, "kg"); +UNIT_DISPLAY_NAME(Units::s, "s"); +UNIT_DISPLAY_NAME(Units::K, "K"); +UNIT_DISPLAY_NAME(Units::A, "A"); +UNIT_DISPLAY_NAME(Units::mol, "mol"); +UNIT_DISPLAY_NAME(Units::cd, "cd"); + + +namespace Units +{ + // SI derived Units: + typedef Compose<m, Power<m, -1> > rad; + typedef Compose<Power<m, 2>, Power<m, -2> > sr; + typedef Power<s, -1> Hz; + typedef Compose<m, Compose<kg, Power<s, -2> > > N; + typedef Compose<N, Power<m, -2> > Pa; + typedef Compose<N, m> J; + typedef Compose<J, Power<s, -1> > W; + typedef Compose<s, A> C; + typedef Compose<W, Power<A, -1> > V; + typedef Compose<C, Power<V, -1> > F; + typedef Compose<V, Power<A, -1> > Ohm; + typedef Compose<A, Power<V, -1> > S; + typedef Compose<V, s> Wb; + typedef Compose<Wb, Power<m, -2> > T; + typedef Compose<Wb, Power<A, -1> > H; + typedef cd lm; + typedef Compose<lm, Power<m, -2> > lx; + typedef Power<s, -1> Bq; + typedef Compose<J, Power<kg, -1> > Gy; + typedef Gy Sv; + typedef Compose<Power<s, -1>,mol> kat; +} + + +UNIT_DISPLAY_NAME(Units::rad, "rad"); +UNIT_DISPLAY_NAME(Units::sr, "sr"); +// UNIT_DISPLAY_NAME(Units::Hz, "Hz"); // Too problematic +UNIT_DISPLAY_NAME(Units::N, "N"); +UNIT_DISPLAY_NAME(Units::Pa, "Pa"); +UNIT_DISPLAY_NAME(Units::J, "J"); +UNIT_DISPLAY_NAME(Units::W, "W"); +UNIT_DISPLAY_NAME(Units::C, "C"); +UNIT_DISPLAY_NAME(Units::V, "V"); +UNIT_DISPLAY_NAME(Units::F, "F"); +UNIT_DISPLAY_NAME(Units::Ohm, "Ohm"); +UNIT_DISPLAY_NAME(Units::S, "S"); +UNIT_DISPLAY_NAME(Units::Wb, "Wb"); +UNIT_DISPLAY_NAME(Units::T, "T"); +UNIT_DISPLAY_NAME(Units::H, "H"); +UNIT_DISPLAY_NAME(Units::lx, "lx"); +UNIT_DISPLAY_NAME(Units::Gy, "Gy"); +UNIT_DISPLAY_NAME(Units::kat, "kat"); + + +namespace Units +{ + // SI prefixes: + template <typename U> struct deca { typedef Scale<U, 1, 10> type; }; + template <typename U> struct hecto { typedef Scale<U, 1, 100> type; }; + template <typename U> struct kilo { typedef Scale<U, 1, 1000> type; }; + template <typename U> struct mega { typedef Scale<typename kilo<U>::type, 1, 1000> type; }; + template <typename U> struct giga { typedef Scale<typename mega<U>::type, 1, 1000> type; }; + template <typename U> struct tera { typedef Scale<typename giga<U>::type, 1, 1000> type; }; + template <typename U> struct peta { typedef Scale<typename tera<U>::type, 1, 1000> type; }; + template <typename U> struct exa { typedef Scale<typename peta<U>::type, 1, 1000> type; }; + template <typename U> struct zetta { typedef Scale<typename exa<U>::type, 1, 1000> type; }; + template <typename U> struct yotta { typedef Scale<typename zetta<U>::type, 1, 1000> type; }; + + template <typename U> struct deci { typedef Scale<U, 10> type; }; + template <typename U> struct centi { typedef Scale<U, 100> type; }; + template <typename U> struct milli { typedef Scale<U, 1000> type; }; + template <typename U> struct micro { typedef Scale<typename milli<U>::type, 1000> type; }; + template <typename U> struct nano { typedef Scale<typename micro<U>::type, 1000> type; }; + template <typename U> struct pico { typedef Scale<typename nano<U>::type, 1000> type; }; + template <typename U> struct femto { typedef Scale<typename pico<U>::type, 1000> type; }; + template <typename U> struct atto { typedef Scale<typename femto<U>::type, 1000> type; }; + template <typename U> struct zepto { typedef Scale<typename atto<U>::type, 1000> type; }; + template <typename U> struct yocto { typedef Scale<typename zepto<U>::type, 1000> type; }; + + + // Some prefixed SI Units: + typedef centi<m>::type cm; + typedef milli<m>::type mm; + typedef kilo<m>::type km; + typedef milli<kg>::type g; + typedef milli<g>::type mg; + typedef milli<s>::type ms; + + + class Prefix + /// Parent class for unit prefixes. + /// Use classes inheriting from this class to scale + /// the values. + { + public: + template <typename T> + Prefix(const T& val, double multiplier = 1, const std::string& prefix = ""): + _pHolder(new Holder<T>(val)), + _multiplier(multiplier), + _prefix(prefix) { - public: - virtual ~Placeholder() { } - virtual double get() const = 0; - virtual void appendUnit(std::ostream& os) const = 0; - }; - - template <typename U> - struct Holder : public Placeholder + } + + double value() const { - typedef Value<typename U::ValueType, typename U::Unit> ValueType; - - Holder (const U& val): _val(ValueType(val)) - { - } - - double get() const - { - return _val.get(); - } - - void appendUnit(std::ostream& os) const - { - OutputUnit<typename U::Unit>::fn(os); - } - - ValueType _val; - }; - - Placeholder* _pHolder; - double _multiplier; - std::string _prefix; - }; -} - - -template <typename Str> -Str& streamOp (Str& os, const Units::Prefix& val) -{ - os << val.value() << ' '; - val.addPrefix(os); - val.addUnit(os); - return os; -} - - -template <typename Str> -Str& operator << (Str& os, const Units::Prefix& val) - /// Streaming operator for prefixed values. -{ - return streamOp(os, val); -} - - -UNIT_DISPLAY_NAME(Units::cm, "cm"); -UNIT_DISPLAY_NAME(Units::mm, "mm"); -UNIT_DISPLAY_NAME(Units::km, "km"); -UNIT_DISPLAY_NAME(Units::g, "g"); -UNIT_DISPLAY_NAME(Units::mg, "mg"); -UNIT_DISPLAY_NAME(Units::ms, "ms"); - - -namespace Units -{ - // Non-SI mass - typedef Scale<kg, 22046223, 10000000> lb; - typedef Scale<lb, 16> oz; - typedef Scale<kg, 1, 1000> tonne; - - // Non-SI temperature - typedef Translate<K, -27315, 100> Celsius; - typedef Translate<Scale<Celsius, 9, 5>, 32> Fahrenheit; - - // Non-SI time - typedef Scale<s, 1, 60> minute; - typedef Scale<minute, 1, 60> hour; - typedef Scale<hour, 1, 24> day; - typedef Scale<day, 1, 7> week; - struct month; // No fixed ratio with week - typedef Scale<month, 1, 12> year; - typedef Scale<year, 1, 100> century; - typedef Scale<year, 1, 1000> millennium; - - // Non-SI length - typedef Scale<cm, 100, 254> inch; - typedef Scale<inch, 1, 12> foot; - typedef Scale<inch, 1, 36> yard; - typedef Scale<yard, 1, 1760> mile; - typedef Scale<m, 1, 1852> nautical_mile; - - // Non-SI area - typedef Power<m, 2> m2; - typedef Power<mm, 2> mm2; - typedef Scale<m2, 1, 10000> hectare; - typedef Scale<m2, 1, 100> are; - typedef Power<inch, 2> inch2; - typedef Scale<hectare, 24710538, 10000000> acre; - - // Non-SI volume - typedef Power<cm, 3> cm3; - typedef cm3 ml; - typedef Scale<ml, 1, 1000> liter; - typedef Scale<liter, 10> dl; - typedef Scale<liter, 100> cl; - typedef Power<m, 3> m3; - - // Non-SI velocity - typedef Compose<mile, Power<hour, -1> > mph; - typedef Compose<km, Power<hour, -1> > kph; - typedef Compose<m, Power<s, -1> > meters_per_second; - typedef Compose<nautical_mile, Power<hour, -1> > knot; - typedef Scale<meters_per_second, 100, 34029> mach; - - // Angles - typedef Scale<rad, 180000000, 3141593> degree; - typedef Scale<rad, 200000000, 3141593> grad; - typedef Scale< degree, 60 > degree_minute; - typedef Scale< degree_minute, 60 > degree_second; - - // Pressure - typedef Scale<Pa, 1, 1000> kPa; - typedef Scale<kPa, 1450377, 10000000> psi; - typedef Scale<kPa, 10> millibar; - - // Other - typedef Scale<Hz, 60> rpm; - typedef Scale<Unit, 100> percent; - typedef Scale<Unit, 1, 12> dozen; - typedef Scale<Unit, 1, 13> bakers_dozen; -} - - -UNIT_DISPLAY_NAME(Units::lb, "lb"); -UNIT_DISPLAY_NAME(Units::oz, "oz"); -UNIT_DISPLAY_NAME(Units::tonne, "tonnes"); -UNIT_DISPLAY_NAME(Units::Celsius, "'C"); -UNIT_DISPLAY_NAME(Units::Fahrenheit, "'F"); -UNIT_DISPLAY_NAME(Units::minute, "minutes"); -UNIT_DISPLAY_NAME(Units::hour, "hours"); -UNIT_DISPLAY_NAME(Units::day, "days"); -UNIT_DISPLAY_NAME(Units::week, "weeks"); -UNIT_DISPLAY_NAME(Units::month, "months"); -UNIT_DISPLAY_NAME(Units::year, "years"); -UNIT_DISPLAY_NAME(Units::century, "centuries"); -UNIT_DISPLAY_NAME(Units::millennium, "millennia"); -UNIT_DISPLAY_NAME(Units::inch, "inches"); -UNIT_DISPLAY_NAME(Units::foot, "foot"); -UNIT_DISPLAY_NAME(Units::yard, "yards"); -UNIT_DISPLAY_NAME(Units::mile, "miles"); -UNIT_DISPLAY_NAME(Units::nautical_mile, "nautical miles"); -UNIT_DISPLAY_NAME(Units::hectare, "ha"); -UNIT_DISPLAY_NAME(Units::are, "are"); -UNIT_DISPLAY_NAME(Units::acre, "acres"); -UNIT_DISPLAY_NAME(Units::ml, "ml"); -UNIT_DISPLAY_NAME(Units::liter, "l"); -UNIT_DISPLAY_NAME(Units::dl, "dl"); -UNIT_DISPLAY_NAME(Units::cl, "cl"); -UNIT_DISPLAY_NAME(Units::mph, "mph"); -UNIT_DISPLAY_NAME(Units::kph, "km/h"); -UNIT_DISPLAY_NAME(Units::knot, "knots"); -UNIT_DISPLAY_NAME(Units::mach, "mach"); -UNIT_DISPLAY_NAME(Units::degree, "deg"); -UNIT_DISPLAY_NAME(Units::grad, "grad"); -UNIT_DISPLAY_NAME(Units::degree_minute, "'"); -UNIT_DISPLAY_NAME(Units::degree_second, "\""); -UNIT_DISPLAY_NAME(Units::kPa, "kPa"); -UNIT_DISPLAY_NAME(Units::psi, "PSI"); -UNIT_DISPLAY_NAME(Units::millibar, "millibars"); -UNIT_DISPLAY_NAME(Units::percent, "%"); -UNIT_DISPLAY_NAME(Units::rpm, "rpm"); -UNIT_DISPLAY_NAME(Units::dozen, "dozen"); -UNIT_DISPLAY_NAME(Units::bakers_dozen, "bakers dozen"); - - -namespace Values -{ - typedef Value<double, Units::Unit> Unit; - - // SI Units - typedef Value<double, Units::m> m; - typedef Value<double, Units::kg> kg; - typedef Value<double, Units::s> s; - typedef Value<double, Units::K> K; - typedef Value<double, Units::A> A; - typedef Value<double, Units::mol> mol; - typedef Value<double, Units::cd> cd; - - // SI derived - typedef Value<double, Units::rad> rad; - typedef Value<double, Units::sr> sr; - typedef Value<double, Units::Hz> Hz; - typedef Value<double, Units::N> N; - typedef Value<double, Units::Pa> Pa; - typedef Value<double, Units::J> J; - typedef Value<double, Units::W> W; - typedef Value<double, Units::C> C; - typedef Value<double, Units::V> V; - typedef Value<double, Units::F> F; - typedef Value<double, Units::Ohm> Ohm; - typedef Value<double, Units::S> S; - typedef Value<double, Units::Wb> Wb; - typedef Value<double, Units::T> T; - typedef Value<double, Units::H> H; - typedef Value<double, Units::lm> lm; - typedef Value<double, Units::lx> lx; - typedef Value<double, Units::Bq> Bq; - typedef Value<double, Units::Gy> Gy; - typedef Value<double, Units::Sv> Sv; - typedef Value<double, Units::kat> kat; - - // Prefixed Units - typedef Value<double, Units::cm> cm; - typedef Value<double, Units::mm> mm; - typedef Value<double, Units::km> km; - typedef Value<double, Units::g> g; - typedef Value<double, Units::mg> mg; - typedef Value<double, Units::ms> ms; - - // Non-SI - typedef Value<double, Units::lb> lb; - typedef Value<double, Units::oz> oz; - typedef Value<double, Units::tonne> tonne; - - typedef Value<double, Units::Celsius> Celsius; - typedef Value<double, Units::Fahrenheit> Fahrenheit; - - typedef Value<double, Units::minute> minute; - typedef Value<double, Units::hour> hour; - typedef Value<double, Units::day> day; - typedef Value<double, Units::week> week; - typedef Value<double, Units::month> month; - typedef Value<double, Units::year> year; - typedef Value<double, Units::century> century; - typedef Value<double, Units::millennium> millennium; - - typedef Value<double, Units::inch> inch; - typedef Value<double, Units::foot> foot; - typedef Value<double, Units::yard> yard; - typedef Value<double, Units::mile> mile; - typedef Value<double, Units::nautical_mile> nautical_mile; - - typedef Value<double, Units::m2> m2; - typedef Value<double, Units::mm2> mm2; - typedef Value<double, Units::hectare> hectare; - typedef Value<double, Units::are> are; - typedef Value<double, Units::inch2> inch2; - typedef Value<double, Units::acre> acre; - - typedef Value<double, Units::cm3> cm3; - typedef Value<double, Units::ml> ml; - typedef Value<double, Units::cl> cl; - typedef Value<double, Units::liter> liter; - typedef Value<double, Units::dl> dl; - typedef Value<double, Units::m3> m3; - - typedef Value<double, Units::mph> mph; - typedef Value<double, Units::kph> kph; - typedef Value<double, Units::meters_per_second> meters_per_second; - typedef Value<double, Units::knot> knot; - typedef Value<double, Units::mach> mach; - - typedef Value<double, Units::degree> degree; - typedef Value<double, Units::grad> grad; - typedef Value<double, Units::degree_minute> degree_minute; - typedef Value<double, Units::degree_second> degree_second; - - typedef Value<double, Units::kPa> kPa; - typedef Value<double, Units::psi> psi; - typedef Value<double, Units::millibar> millibar; - - typedef Value<double, Units::percent> percent; - typedef Value<double, Units::rpm> rpm; - typedef Value<double, Units::dozen> dozen; - typedef Value<double, Units::bakers_dozen> bakers_dozen; - - #define DEFINE_PREFIX_CLASS(name, scale, prefix) \ - struct name: public Units::Prefix \ - { \ - template <typename T> \ - name(const T& val): Prefix(val, scale, prefix) \ - { \ - } \ - }; \ - template <typename Str> \ - Str& operator << (Str& os, const name& val) \ - { \ - return streamOp<Str>(os, val); \ - } - - DEFINE_PREFIX_CLASS (deca, .1, "da") - DEFINE_PREFIX_CLASS (hecto, .01, "h") - DEFINE_PREFIX_CLASS (kilo, .001, "k") - DEFINE_PREFIX_CLASS (mega, 1e-6, "M") - DEFINE_PREFIX_CLASS (giga, 1e-9, "G") - DEFINE_PREFIX_CLASS (tera, 1e-12, "T") - DEFINE_PREFIX_CLASS (peta, 1e-15, "P") - DEFINE_PREFIX_CLASS (exa, 1e-18, "E") - DEFINE_PREFIX_CLASS (zetta, 1e-21, "Z") - DEFINE_PREFIX_CLASS (yotta, 1e-24, "Y") - - DEFINE_PREFIX_CLASS (deci, 10, "d") - DEFINE_PREFIX_CLASS (centi, 100, "c") - DEFINE_PREFIX_CLASS (milli, 1000, "m") - DEFINE_PREFIX_CLASS (micro, 1e6, "u") - DEFINE_PREFIX_CLASS (nano, 1e9, "n") - DEFINE_PREFIX_CLASS (pico, 1e12, "p") - DEFINE_PREFIX_CLASS (femto, 1e15, "f") - DEFINE_PREFIX_CLASS (atto, 1e18, "a") - DEFINE_PREFIX_CLASS (zepto, 1e21, "z") - DEFINE_PREFIX_CLASS (yocto, 1e24, "y") -} - - -namespace Constants -{ - // Physical constants: - const Value<double, Compose<Units::J, Power<Units::K, -1> > > k (1.3806504e-23); - const Value<double, Units::kg> mu (1.660538782e-27); - const Value<double, Power<Units::mol, -1> > NA (6.02214179e23); - const Value<double, Units::s> G0 (7.7480917004e-5); - const Value<double, Compose<Units::F, Power<Units::m, -1> > > e0 (8.854187817e-12); - const Value<double, Units::kg> me (9.10938215e-31); - const Value<double, Units::J> eV (1.602176487e-19); - const Value<double, Units::C> e (1.602176487e-19); - const Value<double, Units::F> F (96485.3399); - const Value<double, Units::Unit> alpha (7.2973525376e-3); - const Value<double, Units::Unit> inv_alpha (137.035999679); - const Value<double, Compose<Units::N, Power<Units::A, -2> > > u0 (12.566370614); - const Value<double, Units::Wb> phi0 (2.067833667e-15); // ?? - const Value<double, Compose<Units::J, Compose<Power<Units::mol, -1>, Power<Units::kg, -1> > > > R (8.314472); - const Value<double, Compose< Power<Units::m, 3>, Compose<Power<Units::kg, -1>, Power<Units::s, -2> > > > G (6.67428e-11); - const Value<double, Compose< Units::J, Units::s > > h (6.62606896e-34); - const Value<double, Compose< Units::J, Units::s > > h_bar (1.054571628e-34); - const Value<double, Units::kg> mp (1.672621637e-27); - const Value<double, Unit> mpme (1836.15267247); - const Value<double, Power<Units::m, -1> > Rinf (10973731.568527); - const Value<double, Compose<Units::m, Power<Units::s, -1> > > c (299792458); - const Value<double, Compose<Units::W, Compose< Power<Units::m, -1>, Power<Units::K, -4> > > > rho (5.6704e-8); - - // Other constants: - const Value<double, Units::rad> pi (3.141592653589793); - const Value<double, Units::m> lightyear (9.4605284e15); - const Value<double, Units::km> AU(149597871); - const Value<double, Compose<Units::m, Power<Units::s, -2> > > g (9.80665); -} - - -// -// Trigonometry -// - - -template <typename V, typename U> -V sin(const Value<V, U>& angle) -{ - return std::sin(Value<V, Units::rad>(angle).get()); -} - - -template <typename V, typename U> -V cos(const Value<V, U>& angle) -{ - return std::cos(Value<V, Units::rad>(angle).get()); -} - - -template <typename V, typename U> -V tan(const Value<V, U>& angle) -{ - return std::tan(Value<V, Units::rad>(angle).get()); -} - - -} } } // namespace Poco::Util::Units - - -#endif // Util_Units_INCLUDED + return _pHolder->get() * _multiplier; + } + + void addPrefix(std::ostream& os) const + { + os << _prefix; + } + + void addUnit(std::ostream& os) const + { + _pHolder->appendUnit(os); + } + + private: + Prefix(); + + class Placeholder + { + public: + virtual ~Placeholder() { } + virtual double get() const = 0; + virtual void appendUnit(std::ostream& os) const = 0; + }; + + template <typename U> + struct Holder : public Placeholder + { + typedef Value<typename U::ValueType, typename U::Unit> ValueType; + + Holder (const U& val): _val(ValueType(val)) + { + } + + double get() const + { + return _val.get(); + } + + void appendUnit(std::ostream& os) const + { + OutputUnit<typename U::Unit>::fn(os); + } + + ValueType _val; + }; + + Placeholder* _pHolder; + double _multiplier; + std::string _prefix; + }; +} + + +template <typename Str> +Str& streamOp (Str& os, const Units::Prefix& val) +{ + os << val.value() << ' '; + val.addPrefix(os); + val.addUnit(os); + return os; +} + + +template <typename Str> +Str& operator << (Str& os, const Units::Prefix& val) + /// Streaming operator for prefixed values. +{ + return streamOp(os, val); +} + + +UNIT_DISPLAY_NAME(Units::cm, "cm"); +UNIT_DISPLAY_NAME(Units::mm, "mm"); +UNIT_DISPLAY_NAME(Units::km, "km"); +UNIT_DISPLAY_NAME(Units::g, "g"); +UNIT_DISPLAY_NAME(Units::mg, "mg"); +UNIT_DISPLAY_NAME(Units::ms, "ms"); + + +namespace Units +{ + // Non-SI mass + typedef Scale<kg, 22046223, 10000000> lb; + typedef Scale<lb, 16> oz; + typedef Scale<kg, 1, 1000> tonne; + + // Non-SI temperature + typedef Translate<K, -27315, 100> Celsius; + typedef Translate<Scale<Celsius, 9, 5>, 32> Fahrenheit; + + // Non-SI time + typedef Scale<s, 1, 60> minute; + typedef Scale<minute, 1, 60> hour; + typedef Scale<hour, 1, 24> day; + typedef Scale<day, 1, 7> week; + struct month; // No fixed ratio with week + typedef Scale<month, 1, 12> year; + typedef Scale<year, 1, 100> century; + typedef Scale<year, 1, 1000> millennium; + + // Non-SI length + typedef Scale<cm, 100, 254> inch; + typedef Scale<inch, 1, 12> foot; + typedef Scale<inch, 1, 36> yard; + typedef Scale<yard, 1, 1760> mile; + typedef Scale<m, 1, 1852> nautical_mile; + + // Non-SI area + typedef Power<m, 2> m2; + typedef Power<mm, 2> mm2; + typedef Scale<m2, 1, 10000> hectare; + typedef Scale<m2, 1, 100> are; + typedef Power<inch, 2> inch2; + typedef Scale<hectare, 24710538, 10000000> acre; + + // Non-SI volume + typedef Power<cm, 3> cm3; + typedef cm3 ml; + typedef Scale<ml, 1, 1000> liter; + typedef Scale<liter, 10> dl; + typedef Scale<liter, 100> cl; + typedef Power<m, 3> m3; + + // Non-SI velocity + typedef Compose<mile, Power<hour, -1> > mph; + typedef Compose<km, Power<hour, -1> > kph; + typedef Compose<m, Power<s, -1> > meters_per_second; + typedef Compose<nautical_mile, Power<hour, -1> > knot; + typedef Scale<meters_per_second, 100, 34029> mach; + + // Angles + typedef Scale<rad, 180000000, 3141593> degree; + typedef Scale<rad, 200000000, 3141593> grad; + typedef Scale< degree, 60 > degree_minute; + typedef Scale< degree_minute, 60 > degree_second; + + // Pressure + typedef Scale<Pa, 1, 1000> kPa; + typedef Scale<kPa, 1450377, 10000000> psi; + typedef Scale<kPa, 10> millibar; + + // Other + typedef Scale<Hz, 60> rpm; + typedef Scale<Unit, 100> percent; + typedef Scale<Unit, 1, 12> dozen; + typedef Scale<Unit, 1, 13> bakers_dozen; +} + + +UNIT_DISPLAY_NAME(Units::lb, "lb"); +UNIT_DISPLAY_NAME(Units::oz, "oz"); +UNIT_DISPLAY_NAME(Units::tonne, "tonnes"); +UNIT_DISPLAY_NAME(Units::Celsius, "'C"); +UNIT_DISPLAY_NAME(Units::Fahrenheit, "'F"); +UNIT_DISPLAY_NAME(Units::minute, "minutes"); +UNIT_DISPLAY_NAME(Units::hour, "hours"); +UNIT_DISPLAY_NAME(Units::day, "days"); +UNIT_DISPLAY_NAME(Units::week, "weeks"); +UNIT_DISPLAY_NAME(Units::month, "months"); +UNIT_DISPLAY_NAME(Units::year, "years"); +UNIT_DISPLAY_NAME(Units::century, "centuries"); +UNIT_DISPLAY_NAME(Units::millennium, "millennia"); +UNIT_DISPLAY_NAME(Units::inch, "inches"); +UNIT_DISPLAY_NAME(Units::foot, "foot"); +UNIT_DISPLAY_NAME(Units::yard, "yards"); +UNIT_DISPLAY_NAME(Units::mile, "miles"); +UNIT_DISPLAY_NAME(Units::nautical_mile, "nautical miles"); +UNIT_DISPLAY_NAME(Units::hectare, "ha"); +UNIT_DISPLAY_NAME(Units::are, "are"); +UNIT_DISPLAY_NAME(Units::acre, "acres"); +UNIT_DISPLAY_NAME(Units::ml, "ml"); +UNIT_DISPLAY_NAME(Units::liter, "l"); +UNIT_DISPLAY_NAME(Units::dl, "dl"); +UNIT_DISPLAY_NAME(Units::cl, "cl"); +UNIT_DISPLAY_NAME(Units::mph, "mph"); +UNIT_DISPLAY_NAME(Units::kph, "km/h"); +UNIT_DISPLAY_NAME(Units::knot, "knots"); +UNIT_DISPLAY_NAME(Units::mach, "mach"); +UNIT_DISPLAY_NAME(Units::degree, "deg"); +UNIT_DISPLAY_NAME(Units::grad, "grad"); +UNIT_DISPLAY_NAME(Units::degree_minute, "'"); +UNIT_DISPLAY_NAME(Units::degree_second, "\""); +UNIT_DISPLAY_NAME(Units::kPa, "kPa"); +UNIT_DISPLAY_NAME(Units::psi, "PSI"); +UNIT_DISPLAY_NAME(Units::millibar, "millibars"); +UNIT_DISPLAY_NAME(Units::percent, "%"); +UNIT_DISPLAY_NAME(Units::rpm, "rpm"); +UNIT_DISPLAY_NAME(Units::dozen, "dozen"); +UNIT_DISPLAY_NAME(Units::bakers_dozen, "bakers dozen"); + + +namespace Values +{ + typedef Value<double, Units::Unit> Unit; + + // SI Units + typedef Value<double, Units::m> m; + typedef Value<double, Units::kg> kg; + typedef Value<double, Units::s> s; + typedef Value<double, Units::K> K; + typedef Value<double, Units::A> A; + typedef Value<double, Units::mol> mol; + typedef Value<double, Units::cd> cd; + + // SI derived + typedef Value<double, Units::rad> rad; + typedef Value<double, Units::sr> sr; + typedef Value<double, Units::Hz> Hz; + typedef Value<double, Units::N> N; + typedef Value<double, Units::Pa> Pa; + typedef Value<double, Units::J> J; + typedef Value<double, Units::W> W; + typedef Value<double, Units::C> C; + typedef Value<double, Units::V> V; + typedef Value<double, Units::F> F; + typedef Value<double, Units::Ohm> Ohm; + typedef Value<double, Units::S> S; + typedef Value<double, Units::Wb> Wb; + typedef Value<double, Units::T> T; + typedef Value<double, Units::H> H; + typedef Value<double, Units::lm> lm; + typedef Value<double, Units::lx> lx; + typedef Value<double, Units::Bq> Bq; + typedef Value<double, Units::Gy> Gy; + typedef Value<double, Units::Sv> Sv; + typedef Value<double, Units::kat> kat; + + // Prefixed Units + typedef Value<double, Units::cm> cm; + typedef Value<double, Units::mm> mm; + typedef Value<double, Units::km> km; + typedef Value<double, Units::g> g; + typedef Value<double, Units::mg> mg; + typedef Value<double, Units::ms> ms; + + // Non-SI + typedef Value<double, Units::lb> lb; + typedef Value<double, Units::oz> oz; + typedef Value<double, Units::tonne> tonne; + + typedef Value<double, Units::Celsius> Celsius; + typedef Value<double, Units::Fahrenheit> Fahrenheit; + + typedef Value<double, Units::minute> minute; + typedef Value<double, Units::hour> hour; + typedef Value<double, Units::day> day; + typedef Value<double, Units::week> week; + typedef Value<double, Units::month> month; + typedef Value<double, Units::year> year; + typedef Value<double, Units::century> century; + typedef Value<double, Units::millennium> millennium; + + typedef Value<double, Units::inch> inch; + typedef Value<double, Units::foot> foot; + typedef Value<double, Units::yard> yard; + typedef Value<double, Units::mile> mile; + typedef Value<double, Units::nautical_mile> nautical_mile; + + typedef Value<double, Units::m2> m2; + typedef Value<double, Units::mm2> mm2; + typedef Value<double, Units::hectare> hectare; + typedef Value<double, Units::are> are; + typedef Value<double, Units::inch2> inch2; + typedef Value<double, Units::acre> acre; + + typedef Value<double, Units::cm3> cm3; + typedef Value<double, Units::ml> ml; + typedef Value<double, Units::cl> cl; + typedef Value<double, Units::liter> liter; + typedef Value<double, Units::dl> dl; + typedef Value<double, Units::m3> m3; + + typedef Value<double, Units::mph> mph; + typedef Value<double, Units::kph> kph; + typedef Value<double, Units::meters_per_second> meters_per_second; + typedef Value<double, Units::knot> knot; + typedef Value<double, Units::mach> mach; + + typedef Value<double, Units::degree> degree; + typedef Value<double, Units::grad> grad; + typedef Value<double, Units::degree_minute> degree_minute; + typedef Value<double, Units::degree_second> degree_second; + + typedef Value<double, Units::kPa> kPa; + typedef Value<double, Units::psi> psi; + typedef Value<double, Units::millibar> millibar; + + typedef Value<double, Units::percent> percent; + typedef Value<double, Units::rpm> rpm; + typedef Value<double, Units::dozen> dozen; + typedef Value<double, Units::bakers_dozen> bakers_dozen; + + #define DEFINE_PREFIX_CLASS(name, scale, prefix) \ + struct name: public Units::Prefix \ + { \ + template <typename T> \ + name(const T& val): Prefix(val, scale, prefix) \ + { \ + } \ + }; \ + template <typename Str> \ + Str& operator << (Str& os, const name& val) \ + { \ + return streamOp<Str>(os, val); \ + } + + DEFINE_PREFIX_CLASS (deca, .1, "da") + DEFINE_PREFIX_CLASS (hecto, .01, "h") + DEFINE_PREFIX_CLASS (kilo, .001, "k") + DEFINE_PREFIX_CLASS (mega, 1e-6, "M") + DEFINE_PREFIX_CLASS (giga, 1e-9, "G") + DEFINE_PREFIX_CLASS (tera, 1e-12, "T") + DEFINE_PREFIX_CLASS (peta, 1e-15, "P") + DEFINE_PREFIX_CLASS (exa, 1e-18, "E") + DEFINE_PREFIX_CLASS (zetta, 1e-21, "Z") + DEFINE_PREFIX_CLASS (yotta, 1e-24, "Y") + + DEFINE_PREFIX_CLASS (deci, 10, "d") + DEFINE_PREFIX_CLASS (centi, 100, "c") + DEFINE_PREFIX_CLASS (milli, 1000, "m") + DEFINE_PREFIX_CLASS (micro, 1e6, "u") + DEFINE_PREFIX_CLASS (nano, 1e9, "n") + DEFINE_PREFIX_CLASS (pico, 1e12, "p") + DEFINE_PREFIX_CLASS (femto, 1e15, "f") + DEFINE_PREFIX_CLASS (atto, 1e18, "a") + DEFINE_PREFIX_CLASS (zepto, 1e21, "z") + DEFINE_PREFIX_CLASS (yocto, 1e24, "y") +} + + +namespace Constants +{ + // Physical constants: + const Value<double, Compose<Units::J, Power<Units::K, -1> > > k (1.3806504e-23); + const Value<double, Units::kg> mu (1.660538782e-27); + const Value<double, Power<Units::mol, -1> > NA (6.02214179e23); + const Value<double, Units::s> G0 (7.7480917004e-5); + const Value<double, Compose<Units::F, Power<Units::m, -1> > > e0 (8.854187817e-12); + const Value<double, Units::kg> me (9.10938215e-31); + const Value<double, Units::J> eV (1.602176487e-19); + const Value<double, Units::C> e (1.602176487e-19); + const Value<double, Units::F> F (96485.3399); + const Value<double, Units::Unit> alpha (7.2973525376e-3); + const Value<double, Units::Unit> inv_alpha (137.035999679); + const Value<double, Compose<Units::N, Power<Units::A, -2> > > u0 (12.566370614); + const Value<double, Units::Wb> phi0 (2.067833667e-15); // ?? + const Value<double, Compose<Units::J, Compose<Power<Units::mol, -1>, Power<Units::kg, -1> > > > R (8.314472); + const Value<double, Compose< Power<Units::m, 3>, Compose<Power<Units::kg, -1>, Power<Units::s, -2> > > > G (6.67428e-11); + const Value<double, Compose< Units::J, Units::s > > h (6.62606896e-34); + const Value<double, Compose< Units::J, Units::s > > h_bar (1.054571628e-34); + const Value<double, Units::kg> mp (1.672621637e-27); + const Value<double, Unit> mpme (1836.15267247); + const Value<double, Power<Units::m, -1> > Rinf (10973731.568527); + const Value<double, Compose<Units::m, Power<Units::s, -1> > > c (299792458); + const Value<double, Compose<Units::W, Compose< Power<Units::m, -1>, Power<Units::K, -4> > > > rho (5.6704e-8); + + // Other constants: + const Value<double, Units::rad> pi (3.141592653589793); + const Value<double, Units::m> lightyear (9.4605284e15); + const Value<double, Units::km> AU(149597871); + const Value<double, Compose<Units::m, Power<Units::s, -2> > > g (9.80665); +} + + +// +// Trigonometry +// + + +template <typename V, typename U> +V sin(const Value<V, U>& angle) +{ + return std::sin(Value<V, Units::rad>(angle).get()); +} + + +template <typename V, typename U> +V cos(const Value<V, U>& angle) +{ + return std::cos(Value<V, Units::rad>(angle).get()); +} + + +template <typename V, typename U> +V tan(const Value<V, U>& angle) +{ + return std::tan(Value<V, Units::rad>(angle).get()); +} + + +} } } // namespace Poco::Util::Units + + +#endif // Util_Units_INCLUDED diff --git a/contrib/libs/poco/Util/include/Poco/Util/Util.h b/contrib/libs/poco/Util/include/Poco/Util/Util.h index baba0467d3..f567243fb1 100644 --- a/contrib/libs/poco/Util/include/Poco/Util/Util.h +++ b/contrib/libs/poco/Util/include/Poco/Util/Util.h @@ -1,62 +1,62 @@ -// -// Util.h -// -// Library: Util -// Package: Util -// Module: Util -// -// Basic definitions for the Poco Util library. -// This file must be the first file included by every other Util -// header file. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// SPDX-License-Identifier: BSL-1.0 -// - - -#ifndef Util_Util_INCLUDED -#define Util_Util_INCLUDED - - -#include "Poco/Foundation.h" - - -// -// 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 Util_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 -// Util_API functions as being imported from a DLL, whereas this DLL sees symbols -// defined with this macro as being exported. -// -#if defined(_WIN32) && defined(POCO_DLL) - #if defined(Util_EXPORTS) - #define Util_API __declspec(dllexport) - #else - #define Util_API __declspec(dllimport) - #endif -#endif - - -#if !defined(Util_API) - #if !defined(POCO_NO_GCC_API_ATTRIBUTE) && defined (__GNUC__) && (__GNUC__ >= 4) - #define Util_API __attribute__ ((visibility ("default"))) - #else - #define Util_API - #endif -#endif - - -// -// Automatically link Util library. -// -#if defined(_MSC_VER) - #if !defined(POCO_NO_AUTOMATIC_LIBS) && !defined(Util_EXPORTS) - #pragma comment(lib, "PocoUtil" POCO_LIB_SUFFIX) - #endif -#endif - - -#endif // Util_Util_INCLUDED +// +// Util.h +// +// Library: Util +// Package: Util +// Module: Util +// +// Basic definitions for the Poco Util library. +// This file must be the first file included by every other Util +// header file. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Util_Util_INCLUDED +#define Util_Util_INCLUDED + + +#include "Poco/Foundation.h" + + +// +// 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 Util_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 +// Util_API functions as being imported from a DLL, whereas this DLL sees symbols +// defined with this macro as being exported. +// +#if defined(_WIN32) && defined(POCO_DLL) + #if defined(Util_EXPORTS) + #define Util_API __declspec(dllexport) + #else + #define Util_API __declspec(dllimport) + #endif +#endif + + +#if !defined(Util_API) + #if !defined(POCO_NO_GCC_API_ATTRIBUTE) && defined (__GNUC__) && (__GNUC__ >= 4) + #define Util_API __attribute__ ((visibility ("default"))) + #else + #define Util_API + #endif +#endif + + +// +// Automatically link Util library. +// +#if defined(_MSC_VER) + #if !defined(POCO_NO_AUTOMATIC_LIBS) && !defined(Util_EXPORTS) + #pragma comment(lib, "PocoUtil" POCO_LIB_SUFFIX) + #endif +#endif + + +#endif // Util_Util_INCLUDED diff --git a/contrib/libs/poco/Util/include/Poco/Util/Validator.h b/contrib/libs/poco/Util/include/Poco/Util/Validator.h index 1370c3c2e6..38cbc4c3fc 100644 --- a/contrib/libs/poco/Util/include/Poco/Util/Validator.h +++ b/contrib/libs/poco/Util/include/Poco/Util/Validator.h @@ -1,57 +1,57 @@ -// -// Validator.h -// -// Library: Util -// Package: Options -// Module: Validator -// -// Definition of the Validator class. -// -// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// SPDX-License-Identifier: BSL-1.0 -// - - -#ifndef Util_Validator_INCLUDED -#define Util_Validator_INCLUDED - - -#include "Poco/Util/Util.h" -#include "Poco/RefCountedObject.h" - - -namespace Poco { -namespace Util { - - -class Option; - - -class Util_API Validator: public Poco::RefCountedObject - /// Validator specifies the interface for option validators. - /// - /// Option validators provide a simple way for the automatic - /// validation of command line argument values. -{ -public: - virtual void validate(const Option& option, const std::string& value) = 0; - /// Validates the value for the given option. - /// Does nothing if the value is valid. - /// - /// Throws an OptionException otherwise. - -protected: - Validator(); - /// Creates the Validator. - - virtual ~Validator(); - /// Destroys the Validator. -}; - - -} } // namespace Poco::Util - - -#endif // Util_Validator_INCLUDED +// +// Validator.h +// +// Library: Util +// Package: Options +// Module: Validator +// +// Definition of the Validator class. +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Util_Validator_INCLUDED +#define Util_Validator_INCLUDED + + +#include "Poco/Util/Util.h" +#include "Poco/RefCountedObject.h" + + +namespace Poco { +namespace Util { + + +class Option; + + +class Util_API Validator: public Poco::RefCountedObject + /// Validator specifies the interface for option validators. + /// + /// Option validators provide a simple way for the automatic + /// validation of command line argument values. +{ +public: + virtual void validate(const Option& option, const std::string& value) = 0; + /// Validates the value for the given option. + /// Does nothing if the value is valid. + /// + /// Throws an OptionException otherwise. + +protected: + Validator(); + /// Creates the Validator. + + virtual ~Validator(); + /// Destroys the Validator. +}; + + +} } // namespace Poco::Util + + +#endif // Util_Validator_INCLUDED diff --git a/contrib/libs/poco/Util/include/Poco/Util/WinRegistryConfiguration.h b/contrib/libs/poco/Util/include/Poco/Util/WinRegistryConfiguration.h index c60f38dac9..e7e49fc9e9 100644 --- a/contrib/libs/poco/Util/include/Poco/Util/WinRegistryConfiguration.h +++ b/contrib/libs/poco/Util/include/Poco/Util/WinRegistryConfiguration.h @@ -1,71 +1,71 @@ -// -// WinRegistryConfiguration.h -// -// Library: Util -// Package: Windows -// Module: WinRegistryConfiguration -// -// Definition of the WinRegistryConfiguration class. -// -// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// SPDX-License-Identifier: BSL-1.0 -// - - -#ifndef Util_WinRegistryConfiguration_INCLUDED -#define Util_WinRegistryConfiguration_INCLUDED - - -#include "Poco/Util/Util.h" -#include "Poco/Util/AbstractConfiguration.h" -#include "Poco/String.h" - - -namespace Poco { -namespace Util { - - -class Util_API WinRegistryConfiguration: public AbstractConfiguration - /// An implementation of AbstractConfiguration that stores configuration data - /// in the Windows registry. - /// - /// Removing key is not supported. An attempt to remove a key results - /// in a NotImplementedException being thrown. -{ -public: - WinRegistryConfiguration(const std::string& rootPath, REGSAM extraSam = 0); - /// Creates the WinRegistryConfiguration. - /// The rootPath must start with one of the root key names - /// like HKEY_CLASSES_ROOT, e.g. HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services. - /// All further keys are relative to the root path and can be - /// dot separated, e.g. the path MyService.ServiceName will be converted to - /// HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\MyService\ServiceName. - /// The extraSam parameter will be passed along to WinRegistryKey, to control - /// registry virtualization for example. - -protected: - ~WinRegistryConfiguration(); - /// Destroys the WinRegistryConfiguration. - - bool getRaw(const std::string& key, std::string& value) const; - void setRaw(const std::string& key, const std::string& value); - void enumerate(const std::string& key, Keys& range) const; - void removeRaw(const std::string& key); - - std::string convertToRegFormat(const std::string& key, std::string& keyName) const; - /// Takes a key in the format of A.B.C and converts it to - /// registry format A\B\C, the last entry is the keyName, the rest is returned as path - - friend class WinConfigurationTest; -private: - std::string _rootPath; - REGSAM _extraSam; -}; - - -} } // namespace Poco::Util - - -#endif // Util_WinRegistryConfiguration_INCLUDED +// +// WinRegistryConfiguration.h +// +// Library: Util +// Package: Windows +// Module: WinRegistryConfiguration +// +// Definition of the WinRegistryConfiguration class. +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Util_WinRegistryConfiguration_INCLUDED +#define Util_WinRegistryConfiguration_INCLUDED + + +#include "Poco/Util/Util.h" +#include "Poco/Util/AbstractConfiguration.h" +#include "Poco/String.h" + + +namespace Poco { +namespace Util { + + +class Util_API WinRegistryConfiguration: public AbstractConfiguration + /// An implementation of AbstractConfiguration that stores configuration data + /// in the Windows registry. + /// + /// Removing key is not supported. An attempt to remove a key results + /// in a NotImplementedException being thrown. +{ +public: + WinRegistryConfiguration(const std::string& rootPath, REGSAM extraSam = 0); + /// Creates the WinRegistryConfiguration. + /// The rootPath must start with one of the root key names + /// like HKEY_CLASSES_ROOT, e.g. HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services. + /// All further keys are relative to the root path and can be + /// dot separated, e.g. the path MyService.ServiceName will be converted to + /// HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\MyService\ServiceName. + /// The extraSam parameter will be passed along to WinRegistryKey, to control + /// registry virtualization for example. + +protected: + ~WinRegistryConfiguration(); + /// Destroys the WinRegistryConfiguration. + + bool getRaw(const std::string& key, std::string& value) const; + void setRaw(const std::string& key, const std::string& value); + void enumerate(const std::string& key, Keys& range) const; + void removeRaw(const std::string& key); + + std::string convertToRegFormat(const std::string& key, std::string& keyName) const; + /// Takes a key in the format of A.B.C and converts it to + /// registry format A\B\C, the last entry is the keyName, the rest is returned as path + + friend class WinConfigurationTest; +private: + std::string _rootPath; + REGSAM _extraSam; +}; + + +} } // namespace Poco::Util + + +#endif // Util_WinRegistryConfiguration_INCLUDED diff --git a/contrib/libs/poco/Util/include/Poco/Util/WinRegistryKey.h b/contrib/libs/poco/Util/include/Poco/Util/WinRegistryKey.h index d16070dcdf..ca1f9fa95c 100644 --- a/contrib/libs/poco/Util/include/Poco/Util/WinRegistryKey.h +++ b/contrib/libs/poco/Util/include/Poco/Util/WinRegistryKey.h @@ -1,198 +1,198 @@ -// -// WinRegistryKey.h -// -// Library: Util -// Package: Windows -// Module: WinRegistryKey -// -// Definition of the WinRegistryKey class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// SPDX-License-Identifier: BSL-1.0 -// - - -#ifndef Util_WinRegistryKey_INCLUDED -#define Util_WinRegistryKey_INCLUDED - - -#include "Poco/Util/Util.h" -#include "Poco/UnWindows.h" -#include <vector> - - -namespace Poco { -namespace Util { - - -class Util_API WinRegistryKey - /// This class implements a convenient interface to the - /// Windows Registry. - /// - /// This class is only available on Windows platforms. -{ -public: - typedef std::vector<std::string> Keys; - typedef std::vector<std::string> Values; - - enum Type - { - REGT_NONE = 0, - REGT_STRING = 1, - REGT_STRING_EXPAND = 2, - REGT_BINARY = 3, - REGT_DWORD = 4, - REGT_DWORD_BIG_ENDIAN = 5, - REGT_LINK = 6, - REGT_MULTI_STRING = 7, - REGT_RESOURCE_LIST = 8, - REGT_FULL_RESOURCE_DESCRIPTOR = 9, - REGT_RESOURCE_REQUIREMENTS_LIST = 10, - REGT_QWORD = 11 - }; - - WinRegistryKey(const std::string& key, bool readOnly = false, REGSAM extraSam = 0); - /// Creates the WinRegistryKey. - /// - /// The key must start with one of the root key names - /// like HKEY_CLASSES_ROOT, e.g. HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services. - /// - /// If readOnly is true, then only read access to the registry - /// is available and any attempt to write to the registry will - /// result in an exception. - /// - /// extraSam is used to pass extra flags (in addition to KEY_READ and KEY_WRITE) - /// to the samDesired argument of RegOpenKeyEx() or RegCreateKeyEx(). - - WinRegistryKey(HKEY hRootKey, const std::string& subKey, bool readOnly = false, REGSAM extraSam = 0); - /// Creates the WinRegistryKey. - /// - /// If readOnly is true, then only read access to the registry - /// is available and any attempt to write to the registry will - /// result in an exception. - /// - /// extraSam is used to pass extra flags (in addition to KEY_READ and KEY_WRITE) - /// to the samDesired argument of RegOpenKeyEx() or RegCreateKeyEx(). - - ~WinRegistryKey(); - /// Destroys the WinRegistryKey. - - void setString(const std::string& name, const std::string& value); - /// Sets the string value (REG_SZ) with the given name. - /// An empty name denotes the default value. - - std::string getString(const std::string& name); - /// Returns the string value (REG_SZ) with the given name. - /// An empty name denotes the default value. - /// - /// Throws a NotFoundException if the value does not exist. - - void setStringExpand(const std::string& name, const std::string& value); - /// Sets the expandable string value (REG_EXPAND_SZ) with the given name. - /// An empty name denotes the default value. - - std::string getStringExpand(const std::string& name); - /// Returns the string value (REG_EXPAND_SZ) with the given name. - /// An empty name denotes the default value. - /// All references to environment variables (%VAR%) in the string - /// are expanded. - /// - /// Throws a NotFoundException if the value does not exist. - - void setBinary(const std::string& name, const std::vector<char>& value); - /// Sets the string value (REG_BINARY) with the given name. - /// An empty name denotes the default value. - - std::vector<char> getBinary(const std::string& name); - /// Returns the string value (REG_BINARY) with the given name. - /// An empty name denotes the default value. - /// - /// Throws a NotFoundException if the value does not exist. - - void setInt(const std::string& name, int value); - /// Sets the numeric (REG_DWORD) value with the given name. - /// An empty name denotes the default value. - - int getInt(const std::string& name); - /// Returns the numeric value (REG_DWORD) with the given name. - /// An empty name denotes the default value. - /// - /// Throws a NotFoundException if the value does not exist. - -#if defined(POCO_HAVE_INT64) - - void setInt64(const std::string& name, Poco::Int64 value); - /// Sets the numeric (REG_QWORD) value with the given name. - /// An empty name denotes the default value. - - Poco::Int64 getInt64(const std::string& name); - /// Returns the numeric value (REG_QWORD) with the given name. - /// An empty name denotes the default value. - /// - /// Throws a NotFoundException if the value does not exist. - -#endif // POCO_HAVE_INT64 - - void deleteValue(const std::string& name); - /// Deletes the value with the given name. - /// - /// Throws a NotFoundException if the value does not exist. - - void deleteKey(); - /// Recursively deletes the key and all subkeys. - - bool exists(); - /// Returns true iff the key exists. - - Type type(const std::string& name); - /// Returns the type of the key value. - - bool exists(const std::string& name); - /// Returns true iff the given value exists under that key. - - void subKeys(Keys& keys); - /// Appends all subKey names to keys. - - void values(Values& vals); - /// Appends all value names to vals; - - bool isReadOnly() const; - /// Returns true iff the key has been opened for read-only access only. - -protected: - void open(); - void close(); - std::string key() const; - std::string key(const std::string& valueName) const; - HKEY handle(); - void handleSetError(const std::string& name); - static HKEY handleFor(const std::string& rootKey); - -private: - WinRegistryKey(); - WinRegistryKey(const WinRegistryKey&); - WinRegistryKey& operator = (const WinRegistryKey&); - - HKEY _hRootKey; - std::string _subKey; - HKEY _hKey; - bool _readOnly; - REGSAM _extraSam; -}; - - -// -// inlines -// -inline bool WinRegistryKey::isReadOnly() const -{ - return _readOnly; -} - - -} } // namespace Poco::Util - - -#endif // Util_WinRegistryKey_INCLUDED +// +// WinRegistryKey.h +// +// Library: Util +// Package: Windows +// Module: WinRegistryKey +// +// Definition of the WinRegistryKey class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Util_WinRegistryKey_INCLUDED +#define Util_WinRegistryKey_INCLUDED + + +#include "Poco/Util/Util.h" +#include "Poco/UnWindows.h" +#include <vector> + + +namespace Poco { +namespace Util { + + +class Util_API WinRegistryKey + /// This class implements a convenient interface to the + /// Windows Registry. + /// + /// This class is only available on Windows platforms. +{ +public: + typedef std::vector<std::string> Keys; + typedef std::vector<std::string> Values; + + enum Type + { + REGT_NONE = 0, + REGT_STRING = 1, + REGT_STRING_EXPAND = 2, + REGT_BINARY = 3, + REGT_DWORD = 4, + REGT_DWORD_BIG_ENDIAN = 5, + REGT_LINK = 6, + REGT_MULTI_STRING = 7, + REGT_RESOURCE_LIST = 8, + REGT_FULL_RESOURCE_DESCRIPTOR = 9, + REGT_RESOURCE_REQUIREMENTS_LIST = 10, + REGT_QWORD = 11 + }; + + WinRegistryKey(const std::string& key, bool readOnly = false, REGSAM extraSam = 0); + /// Creates the WinRegistryKey. + /// + /// The key must start with one of the root key names + /// like HKEY_CLASSES_ROOT, e.g. HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services. + /// + /// If readOnly is true, then only read access to the registry + /// is available and any attempt to write to the registry will + /// result in an exception. + /// + /// extraSam is used to pass extra flags (in addition to KEY_READ and KEY_WRITE) + /// to the samDesired argument of RegOpenKeyEx() or RegCreateKeyEx(). + + WinRegistryKey(HKEY hRootKey, const std::string& subKey, bool readOnly = false, REGSAM extraSam = 0); + /// Creates the WinRegistryKey. + /// + /// If readOnly is true, then only read access to the registry + /// is available and any attempt to write to the registry will + /// result in an exception. + /// + /// extraSam is used to pass extra flags (in addition to KEY_READ and KEY_WRITE) + /// to the samDesired argument of RegOpenKeyEx() or RegCreateKeyEx(). + + ~WinRegistryKey(); + /// Destroys the WinRegistryKey. + + void setString(const std::string& name, const std::string& value); + /// Sets the string value (REG_SZ) with the given name. + /// An empty name denotes the default value. + + std::string getString(const std::string& name); + /// Returns the string value (REG_SZ) with the given name. + /// An empty name denotes the default value. + /// + /// Throws a NotFoundException if the value does not exist. + + void setStringExpand(const std::string& name, const std::string& value); + /// Sets the expandable string value (REG_EXPAND_SZ) with the given name. + /// An empty name denotes the default value. + + std::string getStringExpand(const std::string& name); + /// Returns the string value (REG_EXPAND_SZ) with the given name. + /// An empty name denotes the default value. + /// All references to environment variables (%VAR%) in the string + /// are expanded. + /// + /// Throws a NotFoundException if the value does not exist. + + void setBinary(const std::string& name, const std::vector<char>& value); + /// Sets the string value (REG_BINARY) with the given name. + /// An empty name denotes the default value. + + std::vector<char> getBinary(const std::string& name); + /// Returns the string value (REG_BINARY) with the given name. + /// An empty name denotes the default value. + /// + /// Throws a NotFoundException if the value does not exist. + + void setInt(const std::string& name, int value); + /// Sets the numeric (REG_DWORD) value with the given name. + /// An empty name denotes the default value. + + int getInt(const std::string& name); + /// Returns the numeric value (REG_DWORD) with the given name. + /// An empty name denotes the default value. + /// + /// Throws a NotFoundException if the value does not exist. + +#if defined(POCO_HAVE_INT64) + + void setInt64(const std::string& name, Poco::Int64 value); + /// Sets the numeric (REG_QWORD) value with the given name. + /// An empty name denotes the default value. + + Poco::Int64 getInt64(const std::string& name); + /// Returns the numeric value (REG_QWORD) with the given name. + /// An empty name denotes the default value. + /// + /// Throws a NotFoundException if the value does not exist. + +#endif // POCO_HAVE_INT64 + + void deleteValue(const std::string& name); + /// Deletes the value with the given name. + /// + /// Throws a NotFoundException if the value does not exist. + + void deleteKey(); + /// Recursively deletes the key and all subkeys. + + bool exists(); + /// Returns true iff the key exists. + + Type type(const std::string& name); + /// Returns the type of the key value. + + bool exists(const std::string& name); + /// Returns true iff the given value exists under that key. + + void subKeys(Keys& keys); + /// Appends all subKey names to keys. + + void values(Values& vals); + /// Appends all value names to vals; + + bool isReadOnly() const; + /// Returns true iff the key has been opened for read-only access only. + +protected: + void open(); + void close(); + std::string key() const; + std::string key(const std::string& valueName) const; + HKEY handle(); + void handleSetError(const std::string& name); + static HKEY handleFor(const std::string& rootKey); + +private: + WinRegistryKey(); + WinRegistryKey(const WinRegistryKey&); + WinRegistryKey& operator = (const WinRegistryKey&); + + HKEY _hRootKey; + std::string _subKey; + HKEY _hKey; + bool _readOnly; + REGSAM _extraSam; +}; + + +// +// inlines +// +inline bool WinRegistryKey::isReadOnly() const +{ + return _readOnly; +} + + +} } // namespace Poco::Util + + +#endif // Util_WinRegistryKey_INCLUDED diff --git a/contrib/libs/poco/Util/include/Poco/Util/WinService.h b/contrib/libs/poco/Util/include/Poco/Util/WinService.h index 619f42225a..8a3c49be8d 100644 --- a/contrib/libs/poco/Util/include/Poco/Util/WinService.h +++ b/contrib/libs/poco/Util/include/Poco/Util/WinService.h @@ -1,141 +1,141 @@ -// -// WinService.h -// -// Library: Util -// Package: Windows -// Module: WinService -// -// Definition of the WinService class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// SPDX-License-Identifier: BSL-1.0 -// - - -#ifndef Util_WinService_INCLUDED -#define Util_WinService_INCLUDED - - -#include "Poco/Util/Util.h" -#include "Poco/UnWindows.h" - - -#if defined(POCO_WIN32_UTF8) -#define POCO_LPQUERY_SERVICE_CONFIG LPQUERY_SERVICE_CONFIGW -#else -#define POCO_LPQUERY_SERVICE_CONFIG LPQUERY_SERVICE_CONFIGA -#endif - - -namespace Poco { -namespace Util { - - -class Util_API WinService - /// This class provides an object-oriented interface to - /// the Windows Service Control Manager for registering, - /// unregistering, configuring, starting and stopping - /// services. - /// - /// This class is only available on Windows platforms. -{ -public: - enum Startup - { - SVC_AUTO_START, - SVC_MANUAL_START, - SVC_DISABLED - }; - - WinService(const std::string& name); - /// Creates the WinService, using the given service name. - - ~WinService(); - /// Destroys the WinService. - - const std::string& name() const; - /// Returns the service name. - - std::string displayName() const; - /// Returns the service's display name. - - std::string path() const; - /// Returns the path to the service executable. - /// - /// Throws a NotFoundException if the service has not been registered. - - void registerService(const std::string& path, const std::string& displayName); - /// Creates a Windows service with the executable specified by path - /// and the given displayName. - /// - /// Throws a ExistsException if the service has already been registered. - - void registerService(const std::string& path); - /// Creates a Windows service with the executable specified by path - /// and the given displayName. The service name is used as display name. - /// - /// Throws a ExistsException if the service has already been registered. - - void unregisterService(); - /// Deletes the Windows service. - /// - /// Throws a NotFoundException if the service has not been registered. - - bool isRegistered() const; - /// Returns true if the service has been registered with the Service Control Manager. - - bool isRunning() const; - /// Returns true if the service is currently running. - - void start(); - /// Starts the service. - /// Does nothing if the service is already running. - /// - /// Throws a NotFoundException if the service has not been registered. - - void stop(); - /// Stops the service. - /// Does nothing if the service is not running. - /// - /// Throws a NotFoundException if the service has not been registered. - - void setStartup(Startup startup); - /// Sets the startup mode for the service. - - Startup getStartup() const; - /// Returns the startup mode for the service. - - void setDescription(const std::string& description); - /// Sets the service description in the registry. - - std::string getDescription() const; - /// Returns the service description from the registry. - - static const int STARTUP_TIMEOUT; - -protected: - static const std::string REGISTRY_KEY; - static const std::string REGISTRY_DESCRIPTION; - -private: - void open() const; - bool tryOpen() const; - void close() const; - POCO_LPQUERY_SERVICE_CONFIG config() const; - - WinService(); - WinService(const WinService&); - WinService& operator = (const WinService&); - - std::string _name; - SC_HANDLE _scmHandle; - mutable SC_HANDLE _svcHandle; -}; - - -} } // namespace Poco::Util - - -#endif // Util_WinService_INCLUDED +// +// WinService.h +// +// Library: Util +// Package: Windows +// Module: WinService +// +// Definition of the WinService class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Util_WinService_INCLUDED +#define Util_WinService_INCLUDED + + +#include "Poco/Util/Util.h" +#include "Poco/UnWindows.h" + + +#if defined(POCO_WIN32_UTF8) +#define POCO_LPQUERY_SERVICE_CONFIG LPQUERY_SERVICE_CONFIGW +#else +#define POCO_LPQUERY_SERVICE_CONFIG LPQUERY_SERVICE_CONFIGA +#endif + + +namespace Poco { +namespace Util { + + +class Util_API WinService + /// This class provides an object-oriented interface to + /// the Windows Service Control Manager for registering, + /// unregistering, configuring, starting and stopping + /// services. + /// + /// This class is only available on Windows platforms. +{ +public: + enum Startup + { + SVC_AUTO_START, + SVC_MANUAL_START, + SVC_DISABLED + }; + + WinService(const std::string& name); + /// Creates the WinService, using the given service name. + + ~WinService(); + /// Destroys the WinService. + + const std::string& name() const; + /// Returns the service name. + + std::string displayName() const; + /// Returns the service's display name. + + std::string path() const; + /// Returns the path to the service executable. + /// + /// Throws a NotFoundException if the service has not been registered. + + void registerService(const std::string& path, const std::string& displayName); + /// Creates a Windows service with the executable specified by path + /// and the given displayName. + /// + /// Throws a ExistsException if the service has already been registered. + + void registerService(const std::string& path); + /// Creates a Windows service with the executable specified by path + /// and the given displayName. The service name is used as display name. + /// + /// Throws a ExistsException if the service has already been registered. + + void unregisterService(); + /// Deletes the Windows service. + /// + /// Throws a NotFoundException if the service has not been registered. + + bool isRegistered() const; + /// Returns true if the service has been registered with the Service Control Manager. + + bool isRunning() const; + /// Returns true if the service is currently running. + + void start(); + /// Starts the service. + /// Does nothing if the service is already running. + /// + /// Throws a NotFoundException if the service has not been registered. + + void stop(); + /// Stops the service. + /// Does nothing if the service is not running. + /// + /// Throws a NotFoundException if the service has not been registered. + + void setStartup(Startup startup); + /// Sets the startup mode for the service. + + Startup getStartup() const; + /// Returns the startup mode for the service. + + void setDescription(const std::string& description); + /// Sets the service description in the registry. + + std::string getDescription() const; + /// Returns the service description from the registry. + + static const int STARTUP_TIMEOUT; + +protected: + static const std::string REGISTRY_KEY; + static const std::string REGISTRY_DESCRIPTION; + +private: + void open() const; + bool tryOpen() const; + void close() const; + POCO_LPQUERY_SERVICE_CONFIG config() const; + + WinService(); + WinService(const WinService&); + WinService& operator = (const WinService&); + + std::string _name; + SC_HANDLE _scmHandle; + mutable SC_HANDLE _svcHandle; +}; + + +} } // namespace Poco::Util + + +#endif // Util_WinService_INCLUDED diff --git a/contrib/libs/poco/Util/include/Poco/Util/XMLConfiguration.h b/contrib/libs/poco/Util/include/Poco/Util/XMLConfiguration.h index 31ff867cdf..c47505e67e 100644 --- a/contrib/libs/poco/Util/include/Poco/Util/XMLConfiguration.h +++ b/contrib/libs/poco/Util/include/Poco/Util/XMLConfiguration.h @@ -1,209 +1,209 @@ -// -// XMLConfiguration.h -// -// Library: Util -// Package: Configuration -// Module: XMLConfiguration -// -// Definition of the XMLConfiguration class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// SPDX-License-Identifier: BSL-1.0 -// - - -#ifndef Util_XMLConfiguration_INCLUDED -#define Util_XMLConfiguration_INCLUDED - - -#include "Poco/Util/Util.h" - - -#ifndef POCO_UTIL_NO_XMLCONFIGURATION - - -#include "Poco/Util/MapConfiguration.h" -#include "Poco/DOM/Document.h" -#include "Poco/DOM/AutoPtr.h" -#include "Poco/DOM/DOMWriter.h" -#include "Poco/SAX/InputSource.h" -#include <istream> - - -namespace Poco { -namespace Util { - - -class Util_API XMLConfiguration: public AbstractConfiguration - /// This configuration class extracts configuration properties - /// from an XML document. An XPath-like syntax for property - /// names is supported to allow full access to the XML document. - /// XML namespaces are not supported. The name of the root element - /// of the XML document is not significant and ignored. - /// Periods in tag names are not supported. - /// - /// Given the following XML document as an example: +// +// XMLConfiguration.h +// +// Library: Util +// Package: Configuration +// Module: XMLConfiguration +// +// Definition of the XMLConfiguration class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Util_XMLConfiguration_INCLUDED +#define Util_XMLConfiguration_INCLUDED + + +#include "Poco/Util/Util.h" + + +#ifndef POCO_UTIL_NO_XMLCONFIGURATION + + +#include "Poco/Util/MapConfiguration.h" +#include "Poco/DOM/Document.h" +#include "Poco/DOM/AutoPtr.h" +#include "Poco/DOM/DOMWriter.h" +#include "Poco/SAX/InputSource.h" +#include <istream> + + +namespace Poco { +namespace Util { + + +class Util_API XMLConfiguration: public AbstractConfiguration + /// This configuration class extracts configuration properties + /// from an XML document. An XPath-like syntax for property + /// names is supported to allow full access to the XML document. + /// XML namespaces are not supported. The name of the root element + /// of the XML document is not significant and ignored. + /// Periods in tag names are not supported. /// - /// <config> - /// <prop1>value1</prop1> - /// <prop2>value2</prop2> - /// <prop3> - /// <prop4 attr="value3"/> - /// <prop4 attr="value4"/> - /// </prop3> - /// <prop5 id="first">value5</prop5> - /// <prop5 id="second">value6</prop5> - /// </config> - /// - /// The following property names would be valid and would - /// yield the shown values: - /// - /// prop1 -> value1 - /// prop2 -> value2 - /// prop3.prop4 -> (empty string) - /// prop3.prop4[@attr] -> value3 - /// prop3.prop4[1][@attr] -> value4 - /// prop5[0] -> value5 - /// prop5[1] -> value6 - /// prop5[@id=first] -> value5 - /// prop5[@id='second'] -> value6 - /// - /// Enumerating attributes is not supported. - /// Calling keys("prop3.prop4") will return an empty range. - /// - /// As a special feature, the delimiter character used to delimit - /// property names can be changed to something other than period ('.') by - /// passing the desired character to the constructor. This allows - /// working with XML documents having element names with periods - /// in them. -{ -public: - XMLConfiguration(); - /// Creates an empty XMLConfiguration with a "config" root element. - - XMLConfiguration(char delim); - /// Creates an empty XMLConfiguration with a "config" root element, - /// using the given delimiter char instead of the default '.'. - - XMLConfiguration(Poco::XML::InputSource* pInputSource); - /// Creates an XMLConfiguration and loads the XML document from - /// the given InputSource. - - XMLConfiguration(Poco::XML::InputSource* pInputSource, char delim); - /// Creates an XMLConfiguration and loads the XML document from - /// the given InputSource. Uses the given delimiter char instead - /// of the default '.'. - - XMLConfiguration(std::istream& istr); - /// Creates an XMLConfiguration and loads the XML document from - /// the given stream. - - XMLConfiguration(std::istream& istr, char delim); - /// Creates an XMLConfiguration and loads the XML document from - /// the given stream. Uses the given delimiter char instead - /// of the default '.'. - - XMLConfiguration(const std::string& path); - /// Creates an XMLConfiguration and loads the XML document from - /// the given path. - - XMLConfiguration(const std::string& path, char delim); - /// Creates an XMLConfiguration and loads the XML document from - /// the given path. Uses the given delimiter char instead - /// of the default '.'. - - XMLConfiguration(const Poco::XML::Document* pDocument); - /// Creates the XMLConfiguration using the given XML document. - - XMLConfiguration(const Poco::XML::Document* pDocument, char delim); - /// Creates the XMLConfiguration using the given XML document. - /// Uses the given delimiter char instead of the default '.'. - - XMLConfiguration(const Poco::XML::Node* pNode); - /// Creates the XMLConfiguration using the given XML node. - - XMLConfiguration(const Poco::XML::Node* pNode, char delim); - /// Creates the XMLConfiguration using the given XML node. - /// Uses the given delimiter char instead of the default '.'. - - void load(Poco::XML::InputSource* pInputSource); - /// Loads the XML document containing the configuration data - /// from the given InputSource. - - void load(Poco::XML::InputSource* pInputSource, unsigned long namePoolSize); - /// Loads the XML document containing the configuration data - /// from the given InputSource. Uses the give namePoolSize (which - /// should be a suitable prime like 251, 509, 1021, 4093) for the - /// internal DOM Document's name pool. - - void load(std::istream& istr); - /// Loads the XML document containing the configuration data - /// from the given stream. - - void load(const std::string& path); - /// Loads the XML document containing the configuration data - /// from the given file. - - void load(const Poco::XML::Document* pDocument); - /// Loads the XML document containing the configuration data - /// from the given XML document. - - void load(const Poco::XML::Node* pNode); - /// Loads the XML document containing the configuration data - /// from the given XML node. - - void loadEmpty(const std::string& rootElementName); - /// Loads an empty XML document containing only the - /// root element with the given name. - - void save(const std::string& path) const; - /// Writes the XML document containing the configuration data - /// to the file given by path. - - void save(std::ostream& str) const; - /// Writes the XML document containing the configuration data - /// to the given stream. - - void save(Poco::XML::DOMWriter& writer, const std::string& path) const; - /// Writes the XML document containing the configuration data - /// to the file given by path, using the given DOMWriter. - /// - /// This can be used to use a DOMWriter with custom options. - - void save(Poco::XML::DOMWriter& writer, std::ostream& str) const; - /// Writes the XML document containing the configuration data - /// to the given stream. - /// - /// This can be used to use a DOMWriter with custom options. - -protected: - bool getRaw(const std::string& key, std::string& value) const; - void setRaw(const std::string& key, const std::string& value); - void enumerate(const std::string& key, Keys& range) const; - void removeRaw(const std::string& key); - ~XMLConfiguration(); - -private: - const Poco::XML::Node* findNode(const std::string& key) const; - Poco::XML::Node* findNode(const std::string& key); - Poco::XML::Node* findNode(std::string::const_iterator& it, const std::string::const_iterator& end, Poco::XML::Node* pNode, bool create = false) const; - static Poco::XML::Node* findElement(const std::string& name, Poco::XML::Node* pNode, bool create); - static Poco::XML::Node* findElement(int index, Poco::XML::Node* pNode, bool create); - static Poco::XML::Node* findElement(const std::string& attr, const std::string& value, Poco::XML::Node* pNode); - static Poco::XML::Node* findAttribute(const std::string& name, Poco::XML::Node* pNode, bool create); - - Poco::XML::AutoPtr<Poco::XML::Node> _pRoot; - Poco::XML::AutoPtr<Poco::XML::Document> _pDocument; - char _delim; -}; - - -} } // namespace Poco::Util - - -#endif // POCO_UTIL_NO_XMLCONFIGURATION - - -#endif // Util_XMLConfiguration_INCLUDED + /// Given the following XML document as an example: + /// + /// <config> + /// <prop1>value1</prop1> + /// <prop2>value2</prop2> + /// <prop3> + /// <prop4 attr="value3"/> + /// <prop4 attr="value4"/> + /// </prop3> + /// <prop5 id="first">value5</prop5> + /// <prop5 id="second">value6</prop5> + /// </config> + /// + /// The following property names would be valid and would + /// yield the shown values: + /// + /// prop1 -> value1 + /// prop2 -> value2 + /// prop3.prop4 -> (empty string) + /// prop3.prop4[@attr] -> value3 + /// prop3.prop4[1][@attr] -> value4 + /// prop5[0] -> value5 + /// prop5[1] -> value6 + /// prop5[@id=first] -> value5 + /// prop5[@id='second'] -> value6 + /// + /// Enumerating attributes is not supported. + /// Calling keys("prop3.prop4") will return an empty range. + /// + /// As a special feature, the delimiter character used to delimit + /// property names can be changed to something other than period ('.') by + /// passing the desired character to the constructor. This allows + /// working with XML documents having element names with periods + /// in them. +{ +public: + XMLConfiguration(); + /// Creates an empty XMLConfiguration with a "config" root element. + + XMLConfiguration(char delim); + /// Creates an empty XMLConfiguration with a "config" root element, + /// using the given delimiter char instead of the default '.'. + + XMLConfiguration(Poco::XML::InputSource* pInputSource); + /// Creates an XMLConfiguration and loads the XML document from + /// the given InputSource. + + XMLConfiguration(Poco::XML::InputSource* pInputSource, char delim); + /// Creates an XMLConfiguration and loads the XML document from + /// the given InputSource. Uses the given delimiter char instead + /// of the default '.'. + + XMLConfiguration(std::istream& istr); + /// Creates an XMLConfiguration and loads the XML document from + /// the given stream. + + XMLConfiguration(std::istream& istr, char delim); + /// Creates an XMLConfiguration and loads the XML document from + /// the given stream. Uses the given delimiter char instead + /// of the default '.'. + + XMLConfiguration(const std::string& path); + /// Creates an XMLConfiguration and loads the XML document from + /// the given path. + + XMLConfiguration(const std::string& path, char delim); + /// Creates an XMLConfiguration and loads the XML document from + /// the given path. Uses the given delimiter char instead + /// of the default '.'. + + XMLConfiguration(const Poco::XML::Document* pDocument); + /// Creates the XMLConfiguration using the given XML document. + + XMLConfiguration(const Poco::XML::Document* pDocument, char delim); + /// Creates the XMLConfiguration using the given XML document. + /// Uses the given delimiter char instead of the default '.'. + + XMLConfiguration(const Poco::XML::Node* pNode); + /// Creates the XMLConfiguration using the given XML node. + + XMLConfiguration(const Poco::XML::Node* pNode, char delim); + /// Creates the XMLConfiguration using the given XML node. + /// Uses the given delimiter char instead of the default '.'. + + void load(Poco::XML::InputSource* pInputSource); + /// Loads the XML document containing the configuration data + /// from the given InputSource. + + void load(Poco::XML::InputSource* pInputSource, unsigned long namePoolSize); + /// Loads the XML document containing the configuration data + /// from the given InputSource. Uses the give namePoolSize (which + /// should be a suitable prime like 251, 509, 1021, 4093) for the + /// internal DOM Document's name pool. + + void load(std::istream& istr); + /// Loads the XML document containing the configuration data + /// from the given stream. + + void load(const std::string& path); + /// Loads the XML document containing the configuration data + /// from the given file. + + void load(const Poco::XML::Document* pDocument); + /// Loads the XML document containing the configuration data + /// from the given XML document. + + void load(const Poco::XML::Node* pNode); + /// Loads the XML document containing the configuration data + /// from the given XML node. + + void loadEmpty(const std::string& rootElementName); + /// Loads an empty XML document containing only the + /// root element with the given name. + + void save(const std::string& path) const; + /// Writes the XML document containing the configuration data + /// to the file given by path. + + void save(std::ostream& str) const; + /// Writes the XML document containing the configuration data + /// to the given stream. + + void save(Poco::XML::DOMWriter& writer, const std::string& path) const; + /// Writes the XML document containing the configuration data + /// to the file given by path, using the given DOMWriter. + /// + /// This can be used to use a DOMWriter with custom options. + + void save(Poco::XML::DOMWriter& writer, std::ostream& str) const; + /// Writes the XML document containing the configuration data + /// to the given stream. + /// + /// This can be used to use a DOMWriter with custom options. + +protected: + bool getRaw(const std::string& key, std::string& value) const; + void setRaw(const std::string& key, const std::string& value); + void enumerate(const std::string& key, Keys& range) const; + void removeRaw(const std::string& key); + ~XMLConfiguration(); + +private: + const Poco::XML::Node* findNode(const std::string& key) const; + Poco::XML::Node* findNode(const std::string& key); + Poco::XML::Node* findNode(std::string::const_iterator& it, const std::string::const_iterator& end, Poco::XML::Node* pNode, bool create = false) const; + static Poco::XML::Node* findElement(const std::string& name, Poco::XML::Node* pNode, bool create); + static Poco::XML::Node* findElement(int index, Poco::XML::Node* pNode, bool create); + static Poco::XML::Node* findElement(const std::string& attr, const std::string& value, Poco::XML::Node* pNode); + static Poco::XML::Node* findAttribute(const std::string& name, Poco::XML::Node* pNode, bool create); + + Poco::XML::AutoPtr<Poco::XML::Node> _pRoot; + Poco::XML::AutoPtr<Poco::XML::Document> _pDocument; + char _delim; +}; + + +} } // namespace Poco::Util + + +#endif // POCO_UTIL_NO_XMLCONFIGURATION + + +#endif // Util_XMLConfiguration_INCLUDED diff --git a/contrib/libs/poco/Util/src/AbstractConfiguration.cpp b/contrib/libs/poco/Util/src/AbstractConfiguration.cpp index 7c3dc77b89..2751754a60 100644 --- a/contrib/libs/poco/Util/src/AbstractConfiguration.cpp +++ b/contrib/libs/poco/Util/src/AbstractConfiguration.cpp @@ -1,536 +1,536 @@ -// -// AbstractConfiguration.cpp -// -// Library: Util -// Package: Configuration -// Module: AbstractConfiguration -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// SPDX-License-Identifier: BSL-1.0 -// - - -#include "Poco/Util/AbstractConfiguration.h" -#include "Poco/Util/ConfigurationView.h" -#include "Poco/Exception.h" -#include "Poco/NumberParser.h" -#include "Poco/NumberFormatter.h" -#include "Poco/String.h" - - -using Poco::Mutex; -using Poco::NotFoundException; -using Poco::SyntaxException; -using Poco::CircularReferenceException; -using Poco::NumberParser; -using Poco::NumberFormatter; -using Poco::icompare; - - -namespace Poco { -namespace Util { - - -AbstractConfiguration::AbstractConfiguration(): - _depth(0), - _eventsEnabled(true) -{ -} - - -AbstractConfiguration::~AbstractConfiguration() -{ -} - - -bool AbstractConfiguration::hasProperty(const std::string& key) const -{ - Mutex::ScopedLock lock(_mutex); - - std::string value; - return getRaw(key, value); -} - - -bool AbstractConfiguration::hasOption(const std::string& key) const -{ - return hasProperty(key); -} - - -bool AbstractConfiguration::has(const std::string& key) const -{ - return hasProperty(key); -} - - -std::string AbstractConfiguration::getString(const std::string& key) const -{ - Mutex::ScopedLock lock(_mutex); - - std::string value; - if (getRaw(key, value)) - return internalExpand(value); +// +// AbstractConfiguration.cpp +// +// Library: Util +// Package: Configuration +// Module: AbstractConfiguration +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#include "Poco/Util/AbstractConfiguration.h" +#include "Poco/Util/ConfigurationView.h" +#include "Poco/Exception.h" +#include "Poco/NumberParser.h" +#include "Poco/NumberFormatter.h" +#include "Poco/String.h" + + +using Poco::Mutex; +using Poco::NotFoundException; +using Poco::SyntaxException; +using Poco::CircularReferenceException; +using Poco::NumberParser; +using Poco::NumberFormatter; +using Poco::icompare; + + +namespace Poco { +namespace Util { + + +AbstractConfiguration::AbstractConfiguration(): + _depth(0), + _eventsEnabled(true) +{ +} + + +AbstractConfiguration::~AbstractConfiguration() +{ +} + + +bool AbstractConfiguration::hasProperty(const std::string& key) const +{ + Mutex::ScopedLock lock(_mutex); + + std::string value; + return getRaw(key, value); +} + + +bool AbstractConfiguration::hasOption(const std::string& key) const +{ + return hasProperty(key); +} + + +bool AbstractConfiguration::has(const std::string& key) const +{ + return hasProperty(key); +} + + +std::string AbstractConfiguration::getString(const std::string& key) const +{ + Mutex::ScopedLock lock(_mutex); + + std::string value; + if (getRaw(key, value)) + return internalExpand(value); + else + throw NotFoundException(key); +} + + +std::string AbstractConfiguration::getString(const std::string& key, const std::string& defaultValue) const +{ + Mutex::ScopedLock lock(_mutex); + + std::string value; + if (getRaw(key, value)) + return internalExpand(value); + else + return defaultValue; +} + + +std::string AbstractConfiguration::getRawString(const std::string& key) const +{ + Mutex::ScopedLock lock(_mutex); + + std::string value; + if (getRaw(key, value)) + return value; + else + throw NotFoundException(key); +} + + +std::string AbstractConfiguration::getRawString(const std::string& key, const std::string& defaultValue) const +{ + + Mutex::ScopedLock lock(_mutex); + + std::string value; + if (getRaw(key, value)) + return value; + else + return defaultValue; +} + + +int AbstractConfiguration::getInt(const std::string& key) const +{ + Mutex::ScopedLock lock(_mutex); + + std::string value; + if (getRaw(key, value)) + return parseInt(internalExpand(value)); + else + throw NotFoundException(key); +} + + +int AbstractConfiguration::getInt(const std::string& key, int defaultValue) const +{ + Mutex::ScopedLock lock(_mutex); + + std::string value; + if (getRaw(key, value)) + return parseInt(internalExpand(value)); + else + return defaultValue; +} + + +unsigned AbstractConfiguration::getUInt(const std::string& key) const +{ + Mutex::ScopedLock lock(_mutex); + + std::string value; + if (getRaw(key, value)) + return parseUInt(internalExpand(value)); + else + throw NotFoundException(key); +} + + +unsigned AbstractConfiguration::getUInt(const std::string& key, unsigned defaultValue) const +{ + Mutex::ScopedLock lock(_mutex); + + std::string value; + if (getRaw(key, value)) + return parseUInt(internalExpand(value)); + else + return defaultValue; +} + + +#if defined(POCO_HAVE_INT64) + + +Int64 AbstractConfiguration::getInt64(const std::string& key) const +{ + Mutex::ScopedLock lock(_mutex); + + std::string value; + if (getRaw(key, value)) + return parseInt64(internalExpand(value)); + else + throw NotFoundException(key); +} + + +Int64 AbstractConfiguration::getInt64(const std::string& key, Int64 defaultValue) const +{ + Mutex::ScopedLock lock(_mutex); + + std::string value; + if (getRaw(key, value)) + return parseInt64(internalExpand(value)); + else + return defaultValue; +} + + +UInt64 AbstractConfiguration::getUInt64(const std::string& key) const +{ + Mutex::ScopedLock lock(_mutex); + + std::string value; + if (getRaw(key, value)) + return parseUInt64(internalExpand(value)); + else + throw NotFoundException(key); +} + + +UInt64 AbstractConfiguration::getUInt64(const std::string& key, UInt64 defaultValue) const +{ + Mutex::ScopedLock lock(_mutex); + + std::string value; + if (getRaw(key, value)) + return parseUInt64(internalExpand(value)); + else + return defaultValue; +} + + +#endif // defined(POCO_HAVE_INT64) + + +double AbstractConfiguration::getDouble(const std::string& key) const +{ + Mutex::ScopedLock lock(_mutex); + + std::string value; + if (getRaw(key, value)) + return NumberParser::parseFloat(internalExpand(value)); + else + throw NotFoundException(key); +} + + +double AbstractConfiguration::getDouble(const std::string& key, double defaultValue) const +{ + Mutex::ScopedLock lock(_mutex); + + std::string value; + if (getRaw(key, value)) + return NumberParser::parseFloat(internalExpand(value)); + else + return defaultValue; +} + + +bool AbstractConfiguration::getBool(const std::string& key) const +{ + Mutex::ScopedLock lock(_mutex); + + std::string value; + if (getRaw(key, value)) + return parseBool(internalExpand(value)); + else + throw NotFoundException(key); +} + + +bool AbstractConfiguration::getBool(const std::string& key, bool defaultValue) const +{ + Mutex::ScopedLock lock(_mutex); + + std::string value; + if (getRaw(key, value)) + return parseBool(internalExpand(value)); + else + return defaultValue; +} + + +void AbstractConfiguration::setString(const std::string& key, const std::string& value) +{ + setRawWithEvent(key, value); +} + + +void AbstractConfiguration::setInt(const std::string& key, int value) +{ + setRawWithEvent(key, NumberFormatter::format(value)); +} + + +void AbstractConfiguration::setUInt(const std::string& key, unsigned int value) +{ + setRawWithEvent(key, NumberFormatter::format(value)); +} + + +#if defined(POCO_HAVE_INT64) + + +void AbstractConfiguration::setInt64(const std::string& key, Int64 value) +{ + Mutex::ScopedLock lock(_mutex); + + setRawWithEvent(key, NumberFormatter::format(value)); +} + + +void AbstractConfiguration::setUInt64(const std::string& key, UInt64 value) +{ + Mutex::ScopedLock lock(_mutex); + + setRawWithEvent(key, NumberFormatter::format(value)); +} + + +#endif // defined(POCO_HAVE_INT64) + + +void AbstractConfiguration::setDouble(const std::string& key, double value) +{ + setRawWithEvent(key, NumberFormatter::format(value)); +} + + +void AbstractConfiguration::setBool(const std::string& key, bool value) +{ + setRawWithEvent(key, value ? "true" : "false"); +} + + +void AbstractConfiguration::keys(Keys& range) const +{ + Mutex::ScopedLock lock(_mutex); + + std::string key; + range.clear(); + enumerate(key, range); +} + + +void AbstractConfiguration::keys(const std::string& key, Keys& range) const +{ + Mutex::ScopedLock lock(_mutex); + + range.clear(); + enumerate(key, range); +} + + +const AbstractConfiguration* AbstractConfiguration::createView(const std::string& prefix) const +{ + return new ConfigurationView(prefix, const_cast<AbstractConfiguration*>(this)); +} + + +AbstractConfiguration* AbstractConfiguration::createView(const std::string& prefix) +{ + return new ConfigurationView(prefix, this); +} + + +namespace +{ + class AutoCounter + { + public: + AutoCounter(int& count): _count(count) + { + ++_count; + } + + ~AutoCounter() + { + --_count; + } + + private: + int& _count; + }; +} + + +std::string AbstractConfiguration::expand(const std::string& value) const +{ + Mutex::ScopedLock lock(_mutex); + + return internalExpand(value); +} + + +void AbstractConfiguration::remove(const std::string& key) +{ + if (_eventsEnabled) + { + propertyRemoving(this, key); + } + { + + Mutex::ScopedLock lock(_mutex); + removeRaw(key); + } + if (_eventsEnabled) + { + propertyRemoved(this, key); + } +} + + +void AbstractConfiguration::enableEvents(bool enable) +{ + _eventsEnabled = enable; +} + + +bool AbstractConfiguration::eventsEnabled() const +{ + return _eventsEnabled; +} + + +void AbstractConfiguration::removeRaw(const std::string& /*key*/) +{ + throw Poco::NotImplementedException("removeRaw()"); +} + + +std::string AbstractConfiguration::internalExpand(const std::string& value) const +{ + AutoCounter counter(_depth); + if (_depth > 10) throw CircularReferenceException("Too many property references encountered"); + return uncheckedExpand(value); +} + + +std::string AbstractConfiguration::uncheckedExpand(const std::string& value) const +{ + std::string result; + std::string::const_iterator it = value.begin(); + std::string::const_iterator end = value.end(); + while (it != end) + { + if (*it == '$') + { + ++it; + if (it != end && *it == '{') + { + ++it; + std::string prop; + while (it != end && *it != '}') prop += *it++; + if (it != end) ++it; + std::string rawValue; + if (getRaw(prop, rawValue)) + { + result.append(internalExpand(rawValue)); + } + else + { + result.append("${"); + result.append(prop); + result.append("}"); + } + } + else result += '$'; + } + else result += *it++; + } + return result; +} + + +int AbstractConfiguration::parseInt(const std::string& value) +{ + if ((value.compare(0, 2, "0x") == 0) || (value.compare(0, 2, "0X") == 0)) + return static_cast<int>(NumberParser::parseHex(value)); + else + return NumberParser::parse(value); +} + + +unsigned AbstractConfiguration::parseUInt(const std::string& value) +{ + if ((value.compare(0, 2, "0x") == 0) || (value.compare(0, 2, "0X") == 0)) + return NumberParser::parseHex(value); + else + return NumberParser::parseUnsigned(value); +} + + +Int64 AbstractConfiguration::parseInt64(const std::string& value) +{ + if ((value.compare(0, 2, "0x") == 0) || (value.compare(0, 2, "0X") == 0)) + return static_cast<Int64>(NumberParser::parseHex64(value)); + else + return NumberParser::parse64(value); +} + + +UInt64 AbstractConfiguration::parseUInt64(const std::string& value) +{ + if ((value.compare(0, 2, "0x") == 0) || (value.compare(0, 2, "0X") == 0)) + return NumberParser::parseHex64(value); + else + return NumberParser::parseUnsigned64(value); +} + + +bool AbstractConfiguration::parseBool(const std::string& value) +{ + int n; + if (NumberParser::tryParse(value, n)) + return n != 0; + else if (icompare(value, "true") == 0) + return true; + else if (icompare(value, "yes") == 0) + return true; + else if (icompare(value, "on") == 0) + return true; + else if (icompare(value, "false") == 0) + return false; + else if (icompare(value, "no") == 0) + return false; + else if (icompare(value, "off") == 0) + return false; else - throw NotFoundException(key); -} - - -std::string AbstractConfiguration::getString(const std::string& key, const std::string& defaultValue) const -{ - Mutex::ScopedLock lock(_mutex); - - std::string value; - if (getRaw(key, value)) - return internalExpand(value); - else - return defaultValue; -} - - -std::string AbstractConfiguration::getRawString(const std::string& key) const -{ - Mutex::ScopedLock lock(_mutex); - - std::string value; - if (getRaw(key, value)) - return value; - else - throw NotFoundException(key); -} - - -std::string AbstractConfiguration::getRawString(const std::string& key, const std::string& defaultValue) const -{ - - Mutex::ScopedLock lock(_mutex); - - std::string value; - if (getRaw(key, value)) - return value; - else - return defaultValue; -} - - -int AbstractConfiguration::getInt(const std::string& key) const -{ - Mutex::ScopedLock lock(_mutex); - - std::string value; - if (getRaw(key, value)) - return parseInt(internalExpand(value)); - else - throw NotFoundException(key); -} - - -int AbstractConfiguration::getInt(const std::string& key, int defaultValue) const -{ - Mutex::ScopedLock lock(_mutex); - - std::string value; - if (getRaw(key, value)) - return parseInt(internalExpand(value)); - else - return defaultValue; -} - - -unsigned AbstractConfiguration::getUInt(const std::string& key) const -{ - Mutex::ScopedLock lock(_mutex); - - std::string value; - if (getRaw(key, value)) - return parseUInt(internalExpand(value)); - else - throw NotFoundException(key); -} - - -unsigned AbstractConfiguration::getUInt(const std::string& key, unsigned defaultValue) const -{ - Mutex::ScopedLock lock(_mutex); - - std::string value; - if (getRaw(key, value)) - return parseUInt(internalExpand(value)); - else - return defaultValue; -} - - -#if defined(POCO_HAVE_INT64) - - -Int64 AbstractConfiguration::getInt64(const std::string& key) const -{ - Mutex::ScopedLock lock(_mutex); - - std::string value; - if (getRaw(key, value)) - return parseInt64(internalExpand(value)); - else - throw NotFoundException(key); -} - - -Int64 AbstractConfiguration::getInt64(const std::string& key, Int64 defaultValue) const -{ - Mutex::ScopedLock lock(_mutex); - - std::string value; - if (getRaw(key, value)) - return parseInt64(internalExpand(value)); - else - return defaultValue; -} - - -UInt64 AbstractConfiguration::getUInt64(const std::string& key) const -{ - Mutex::ScopedLock lock(_mutex); - - std::string value; - if (getRaw(key, value)) - return parseUInt64(internalExpand(value)); - else - throw NotFoundException(key); -} - - -UInt64 AbstractConfiguration::getUInt64(const std::string& key, UInt64 defaultValue) const -{ - Mutex::ScopedLock lock(_mutex); - - std::string value; - if (getRaw(key, value)) - return parseUInt64(internalExpand(value)); - else - return defaultValue; -} - - -#endif // defined(POCO_HAVE_INT64) - - -double AbstractConfiguration::getDouble(const std::string& key) const -{ - Mutex::ScopedLock lock(_mutex); - - std::string value; - if (getRaw(key, value)) - return NumberParser::parseFloat(internalExpand(value)); - else - throw NotFoundException(key); -} - - -double AbstractConfiguration::getDouble(const std::string& key, double defaultValue) const -{ - Mutex::ScopedLock lock(_mutex); - - std::string value; - if (getRaw(key, value)) - return NumberParser::parseFloat(internalExpand(value)); - else - return defaultValue; -} - - -bool AbstractConfiguration::getBool(const std::string& key) const -{ - Mutex::ScopedLock lock(_mutex); - - std::string value; - if (getRaw(key, value)) - return parseBool(internalExpand(value)); - else - throw NotFoundException(key); -} - - -bool AbstractConfiguration::getBool(const std::string& key, bool defaultValue) const -{ - Mutex::ScopedLock lock(_mutex); - - std::string value; - if (getRaw(key, value)) - return parseBool(internalExpand(value)); - else - return defaultValue; -} - - -void AbstractConfiguration::setString(const std::string& key, const std::string& value) -{ - setRawWithEvent(key, value); -} - - -void AbstractConfiguration::setInt(const std::string& key, int value) -{ - setRawWithEvent(key, NumberFormatter::format(value)); -} - - -void AbstractConfiguration::setUInt(const std::string& key, unsigned int value) -{ - setRawWithEvent(key, NumberFormatter::format(value)); -} - - -#if defined(POCO_HAVE_INT64) - - -void AbstractConfiguration::setInt64(const std::string& key, Int64 value) -{ - Mutex::ScopedLock lock(_mutex); - - setRawWithEvent(key, NumberFormatter::format(value)); -} - - -void AbstractConfiguration::setUInt64(const std::string& key, UInt64 value) -{ - Mutex::ScopedLock lock(_mutex); - - setRawWithEvent(key, NumberFormatter::format(value)); -} - - -#endif // defined(POCO_HAVE_INT64) - - -void AbstractConfiguration::setDouble(const std::string& key, double value) -{ - setRawWithEvent(key, NumberFormatter::format(value)); -} - - -void AbstractConfiguration::setBool(const std::string& key, bool value) -{ - setRawWithEvent(key, value ? "true" : "false"); -} - - -void AbstractConfiguration::keys(Keys& range) const -{ - Mutex::ScopedLock lock(_mutex); - - std::string key; - range.clear(); - enumerate(key, range); -} - - -void AbstractConfiguration::keys(const std::string& key, Keys& range) const -{ - Mutex::ScopedLock lock(_mutex); - - range.clear(); - enumerate(key, range); -} - - -const AbstractConfiguration* AbstractConfiguration::createView(const std::string& prefix) const -{ - return new ConfigurationView(prefix, const_cast<AbstractConfiguration*>(this)); -} - - -AbstractConfiguration* AbstractConfiguration::createView(const std::string& prefix) -{ - return new ConfigurationView(prefix, this); -} - - -namespace -{ - class AutoCounter - { - public: - AutoCounter(int& count): _count(count) - { - ++_count; - } - - ~AutoCounter() - { - --_count; - } - - private: - int& _count; - }; -} - - -std::string AbstractConfiguration::expand(const std::string& value) const -{ - Mutex::ScopedLock lock(_mutex); - - return internalExpand(value); -} - - -void AbstractConfiguration::remove(const std::string& key) -{ - if (_eventsEnabled) - { - propertyRemoving(this, key); - } - { - - Mutex::ScopedLock lock(_mutex); - removeRaw(key); - } - if (_eventsEnabled) - { - propertyRemoved(this, key); - } -} - - -void AbstractConfiguration::enableEvents(bool enable) -{ - _eventsEnabled = enable; -} - - -bool AbstractConfiguration::eventsEnabled() const -{ - return _eventsEnabled; -} - - -void AbstractConfiguration::removeRaw(const std::string& /*key*/) -{ - throw Poco::NotImplementedException("removeRaw()"); -} - - -std::string AbstractConfiguration::internalExpand(const std::string& value) const -{ - AutoCounter counter(_depth); - if (_depth > 10) throw CircularReferenceException("Too many property references encountered"); - return uncheckedExpand(value); -} - - -std::string AbstractConfiguration::uncheckedExpand(const std::string& value) const -{ - std::string result; - std::string::const_iterator it = value.begin(); - std::string::const_iterator end = value.end(); - while (it != end) - { - if (*it == '$') - { - ++it; - if (it != end && *it == '{') - { - ++it; - std::string prop; - while (it != end && *it != '}') prop += *it++; - if (it != end) ++it; - std::string rawValue; - if (getRaw(prop, rawValue)) - { - result.append(internalExpand(rawValue)); - } - else - { - result.append("${"); - result.append(prop); - result.append("}"); - } - } - else result += '$'; - } - else result += *it++; - } - return result; -} - - -int AbstractConfiguration::parseInt(const std::string& value) -{ - if ((value.compare(0, 2, "0x") == 0) || (value.compare(0, 2, "0X") == 0)) - return static_cast<int>(NumberParser::parseHex(value)); - else - return NumberParser::parse(value); -} - - -unsigned AbstractConfiguration::parseUInt(const std::string& value) -{ - if ((value.compare(0, 2, "0x") == 0) || (value.compare(0, 2, "0X") == 0)) - return NumberParser::parseHex(value); - else - return NumberParser::parseUnsigned(value); -} - - -Int64 AbstractConfiguration::parseInt64(const std::string& value) -{ - if ((value.compare(0, 2, "0x") == 0) || (value.compare(0, 2, "0X") == 0)) - return static_cast<Int64>(NumberParser::parseHex64(value)); - else - return NumberParser::parse64(value); -} - - -UInt64 AbstractConfiguration::parseUInt64(const std::string& value) -{ - if ((value.compare(0, 2, "0x") == 0) || (value.compare(0, 2, "0X") == 0)) - return NumberParser::parseHex64(value); - else - return NumberParser::parseUnsigned64(value); -} - - -bool AbstractConfiguration::parseBool(const std::string& value) -{ - int n; - if (NumberParser::tryParse(value, n)) - return n != 0; - else if (icompare(value, "true") == 0) - return true; - else if (icompare(value, "yes") == 0) - return true; - else if (icompare(value, "on") == 0) - return true; - else if (icompare(value, "false") == 0) - return false; - else if (icompare(value, "no") == 0) - return false; - else if (icompare(value, "off") == 0) - return false; - else - throw SyntaxException("Cannot convert to boolean", value); -} - - -void AbstractConfiguration::setRawWithEvent(const std::string& key, std::string value) -{ - KeyValue kv(key, value); - if (_eventsEnabled) - { - propertyChanging(this, kv); - } - { - Mutex::ScopedLock lock(_mutex); - setRaw(key, value); - } - if (_eventsEnabled) - { - propertyChanged(this, kv); - } -} - - -} } // namespace Poco::Util + throw SyntaxException("Cannot convert to boolean", value); +} + + +void AbstractConfiguration::setRawWithEvent(const std::string& key, std::string value) +{ + KeyValue kv(key, value); + if (_eventsEnabled) + { + propertyChanging(this, kv); + } + { + Mutex::ScopedLock lock(_mutex); + setRaw(key, value); + } + if (_eventsEnabled) + { + propertyChanged(this, kv); + } +} + + +} } // namespace Poco::Util diff --git a/contrib/libs/poco/Util/src/Application.cpp b/contrib/libs/poco/Util/src/Application.cpp index 9ad83f3b67..c584ea7011 100644 --- a/contrib/libs/poco/Util/src/Application.cpp +++ b/contrib/libs/poco/Util/src/Application.cpp @@ -1,568 +1,568 @@ -// -// Application.cpp -// -// Library: Util -// Package: Application -// Module: Application -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// SPDX-License-Identifier: BSL-1.0 -// - - -#include "Poco/Util/Application.h" -#include "Poco/Util/SystemConfiguration.h" -#include "Poco/Util/MapConfiguration.h" -#include "Poco/Util/PropertyFileConfiguration.h" -#include "Poco/Util/IniFileConfiguration.h" -#ifndef POCO_UTIL_NO_XMLCONFIGURATION -#include "Poco/Util/XMLConfiguration.h" -#endif -#ifndef POCO_UTIL_NO_JSONCONFIGURATION -#include "Poco/Util/JSONConfiguration.h" -#endif -#include "Poco/Util/LoggingSubsystem.h" -#include "Poco/Util/Option.h" -#include "Poco/Util/OptionProcessor.h" -#include "Poco/Util/Validator.h" -#include "Poco/Environment.h" -#include "Poco/Exception.h" -#include "Poco/NumberFormatter.h" -#include "Poco/File.h" -#include "Poco/Path.h" -#include "Poco/String.h" -#include "Poco/ConsoleChannel.h" -#include "Poco/AutoPtr.h" -#if defined(POCO_OS_FAMILY_WINDOWS) -#include "Poco/UnWindows.h" -#endif -#if defined(POCO_OS_FAMILY_UNIX) && !defined(POCO_VXWORKS) -#include "Poco/SignalHandler.h" -#endif -#if defined(POCO_WIN32_UTF8) && !defined(POCO_NO_WSTRING) -#include "Poco/UnicodeConverter.h" -#endif - - -using Poco::Logger; -using Poco::Path; -using Poco::File; -using Poco::Environment; -using Poco::SystemException; -using Poco::ConsoleChannel; -using Poco::NumberFormatter; -using Poco::AutoPtr; -using Poco::icompare; - - -namespace Poco { -namespace Util { - - -Application* Application::_pInstance = 0; - - -Application::Application(): - _pConfig(new LayeredConfiguration), - _initialized(false), - _unixOptions(true), - _pLogger(&Logger::get("ApplicationStartup")), - _stopOptionsProcessing(false) -{ - setup(); -} - - -Application::Application(int argc, char* argv[]): - _pConfig(new LayeredConfiguration), - _initialized(false), - _unixOptions(true), - _pLogger(&Logger::get("ApplicationStartup")), - _stopOptionsProcessing(false) -{ - setup(); - init(argc, argv); -} - - -Application::~Application() -{ - _pInstance = 0; -} - - -void Application::setup() -{ - poco_assert (_pInstance == 0); - - _pConfig->add(new SystemConfiguration, PRIO_SYSTEM, false, false); - _pConfig->add(new MapConfiguration, PRIO_APPLICATION, true, false); - - addSubsystem(new LoggingSubsystem); - -#if defined(POCO_OS_FAMILY_UNIX) && !defined(POCO_VXWORKS) - _workingDirAtLaunch = Path::current(); - - #if !defined(_DEBUG) - Poco::SignalHandler::install(); - #endif -#else - setUnixOptions(false); -#endif - - _pInstance = this; - - AutoPtr<ConsoleChannel> pCC = new ConsoleChannel; - Logger::setChannel("", pCC); -} - - -void Application::addSubsystem(Subsystem* pSubsystem) -{ - poco_check_ptr (pSubsystem); - - _subsystems.push_back(pSubsystem); -} - - -void Application::init(int argc, char* argv[]) -{ - setArgs(argc, argv); - init(); -} - - -#if defined(POCO_WIN32_UTF8) && !defined(POCO_NO_WSTRING) -void Application::init(int argc, wchar_t* argv[]) -{ - std::vector<std::string> args; - for (int i = 0; i < argc; ++i) - { - std::string arg; - Poco::UnicodeConverter::toUTF8(argv[i], arg); - args.push_back(arg); - } - init(args); -} -#endif - - -void Application::init(const ArgVec& args) -{ - setArgs(args); - init(); -} - - -void Application::init() -{ - Path appPath; - getApplicationPath(appPath); - _pConfig->setString("application.path", appPath.toString()); - _pConfig->setString("application.name", appPath.getFileName()); - _pConfig->setString("application.baseName", appPath.getBaseName()); - _pConfig->setString("application.dir", appPath.parent().toString()); - _pConfig->setString("application.configDir", Path::configHome() + appPath.getBaseName() + Path::separator()); - _pConfig->setString("application.cacheDir", Path::cacheHome() + appPath.getBaseName() + Path::separator()); - _pConfig->setString("application.tempDir", Path::tempHome() + appPath.getBaseName() + Path::separator()); - _pConfig->setString("application.dataDir", Path::dataHome() + appPath.getBaseName() + Path::separator()); - processOptions(); -} - - -const char* Application::name() const -{ - return "Application"; -} - - -void Application::initialize(Application& self) -{ - for (SubsystemVec::iterator it = _subsystems.begin(); it != _subsystems.end(); ++it) - { - _pLogger->debug(std::string("Initializing subsystem: ") + (*it)->name()); - (*it)->initialize(self); - } - _initialized = true; -} - - -void Application::uninitialize() -{ - if (_initialized) - { - for (SubsystemVec::reverse_iterator it = _subsystems.rbegin(); it != _subsystems.rend(); ++it) - { - _pLogger->debug(std::string("Uninitializing subsystem: ") + (*it)->name()); - (*it)->uninitialize(); - } - _initialized = false; - } -} - - -void Application::reinitialize(Application& self) -{ - for (SubsystemVec::iterator it = _subsystems.begin(); it != _subsystems.end(); ++it) - { - _pLogger->debug(std::string("Re-initializing subsystem: ") + (*it)->name()); - (*it)->reinitialize(self); - } -} - - -void Application::setUnixOptions(bool flag) -{ - _unixOptions = flag; -} - - -int Application::loadConfiguration(int priority) -{ - int n = 0; - Path appPath; - getApplicationPath(appPath); - Path confPath; - if (findAppConfigFile(appPath.getBaseName(), "properties", confPath)) - { - _pConfig->add(new PropertyFileConfiguration(confPath.toString()), priority, false, false); - ++n; - } -#ifndef POCO_UTIL_NO_INIFILECONFIGURATION - if (findAppConfigFile(appPath.getBaseName(), "ini", confPath)) - { - _pConfig->add(new IniFileConfiguration(confPath.toString()), priority, false, false); - ++n; - } -#endif -#ifndef POCO_UTIL_NO_JSONCONFIGURATION - if (findAppConfigFile(appPath.getBaseName(), "json", confPath)) - { - _pConfig->add(new JSONConfiguration(confPath.toString()), priority, false, false); - ++n; - } -#endif -#ifndef POCO_UTIL_NO_XMLCONFIGURATION - if (findAppConfigFile(appPath.getBaseName(), "xml", confPath)) - { - _pConfig->add(new XMLConfiguration(confPath.toString()), priority, false, false); - ++n; - } -#endif - if (n > 0) - { - if (!confPath.isAbsolute()) - _pConfig->setString("application.configDir", confPath.absolute().parent().toString()); - else - _pConfig->setString("application.configDir", confPath.parent().toString()); - } - return n; -} - - -void Application::loadConfiguration(const std::string& path, int priority) -{ - int n = 0; - Path confPath(path); - std::string ext = confPath.getExtension(); - if (icompare(ext, "properties") == 0) - { - _pConfig->add(new PropertyFileConfiguration(confPath.toString()), priority, false, false); - ++n; - } -#ifndef POCO_UTIL_NO_INIFILECONFIGURATION - else if (icompare(ext, "ini") == 0) - { - _pConfig->add(new IniFileConfiguration(confPath.toString()), priority, false, false); - ++n; - } -#endif -#ifndef POCO_UTIL_NO_JSONCONFIGURATION - else if (icompare(ext, "json") == 0) - { - _pConfig->add(new JSONConfiguration(confPath.toString()), priority, false, false); - ++n; - } -#endif -#ifndef POCO_UTIL_NO_XMLCONFIGURATION - else if (icompare(ext, "xml") == 0) - { - _pConfig->add(new XMLConfiguration(confPath.toString()), priority, false, false); - ++n; - } -#endif - else throw Poco::InvalidArgumentException("Unsupported configuration file type", ext); - - if (n > 0 && !_pConfig->has("application.configDir")) - { - if (!confPath.isAbsolute()) - _pConfig->setString("application.configDir", confPath.absolute().parent().toString()); - else - _pConfig->setString("application.configDir", confPath.parent().toString()); - } -} - - -std::string Application::commandName() const -{ - return _pConfig->getString("application.baseName"); -} - - -std::string Application::commandPath() const -{ - return _pConfig->getString("application.path"); -} - - -void Application::stopOptionsProcessing() -{ - _stopOptionsProcessing = true; -} - - -int Application::run() -{ - int rc = EXIT_CONFIG; - initialize(*this); - - try - { - rc = EXIT_SOFTWARE; - rc = main(_unprocessedArgs); - } - catch (Poco::Exception& exc) - { - logger().log(exc); - } - catch (std::exception& exc) - { - logger().error(exc.what()); - } - catch (...) - { - logger().fatal("system exception"); - } - - uninitialize(); - return rc; -} - - -int Application::main(const ArgVec& /*args*/) -{ - return EXIT_OK; -} - - -void Application::setArgs(int argc, char* argv[]) -{ - _command = argv[0]; - _pConfig->setInt("application.argc", argc); - _unprocessedArgs.reserve(argc); - std::string argvKey = "application.argv["; - for (int i = 0; i < argc; ++i) - { - std::string arg(argv[i]); - _pConfig->setString(argvKey + NumberFormatter::format(i) + "]", arg); - _unprocessedArgs.push_back(arg); - } -} - - -void Application::setArgs(const ArgVec& args) -{ - poco_assert (!args.empty()); - - _command = args[0]; - _pConfig->setInt("application.argc", (int) args.size()); - _unprocessedArgs = args; - std::string argvKey = "application.argv["; - for (int i = 0; i < args.size(); ++i) - { - _pConfig->setString(argvKey + NumberFormatter::format(i) + "]", args[i]); - } -} - - -void Application::processOptions() -{ - defineOptions(_options); - OptionProcessor processor(_options); - processor.setUnixStyle(_unixOptions); - _argv = _unprocessedArgs; - _unprocessedArgs.erase(_unprocessedArgs.begin()); - ArgVec::iterator it = _unprocessedArgs.begin(); - while (it != _unprocessedArgs.end() && !_stopOptionsProcessing) - { - std::string name; - std::string value; - if (processor.process(*it, name, value)) - { - if (!name.empty()) // "--" option to end options processing or deferred argument - { - handleOption(name, value); - } - it = _unprocessedArgs.erase(it); - } - else ++it; - } - if (!_stopOptionsProcessing) - processor.checkRequired(); -} - - -void Application::getApplicationPath(Poco::Path& appPath) const -{ -#if defined(POCO_OS_FAMILY_UNIX) && !defined(POCO_VXWORKS) - if (_command.find('/') != std::string::npos) - { - Path path(_command); - if (path.isAbsolute()) - { - appPath = path; - } - else - { - appPath = _workingDirAtLaunch; - appPath.append(path); - } - } - else - { - if (!Path::find(Environment::get("PATH"), _command, appPath)) - appPath = Path(_workingDirAtLaunch, _command); - appPath.makeAbsolute(); - } -#elif defined(POCO_OS_FAMILY_WINDOWS) - #if defined(POCO_WIN32_UTF8) && !defined(POCO_NO_WSTRING) - wchar_t path[1024]; - int n = GetModuleFileNameW(0, path, sizeof(path)/sizeof(wchar_t)); - if (n > 0) - { - std::string p; - Poco::UnicodeConverter::toUTF8(path, p); - appPath = p; - } - else throw SystemException("Cannot get application file name."); - #else - char path[1024]; - int n = GetModuleFileNameA(0, path, sizeof(path)); - if (n > 0) - appPath = path; - else - throw SystemException("Cannot get application file name."); - #endif -#else - appPath = _command; -#endif -} - - -bool Application::findFile(Poco::Path& path) const -{ - if (path.isAbsolute()) return true; - - Path appPath; - getApplicationPath(appPath); - Path base = appPath.parent(); - do - { - Path p(base, path); - File f(p); - if (f.exists()) - { - path = p; - return true; - } - if (base.depth() > 0) base.popDirectory(); - } - while (base.depth() > 0); - return false; -} - - -bool Application::findAppConfigFile(const std::string& appName, const std::string& extension, Path& path) const -{ - poco_assert (!appName.empty()); - - Path p(appName); - p.setExtension(extension); - bool found = findFile(p); - if (!found) - { -#if defined(_DEBUG) - if (appName[appName.length() - 1] == 'd') - { - p.setBaseName(appName.substr(0, appName.length() - 1)); - found = findFile(p); - } -#endif - } - if (found) - path = p; - return found; -} - - -bool Application::findAppConfigFile(const Path& basePath, const std::string& appName, const std::string& extension, Path& path) const -{ - poco_assert (!appName.empty()); - - Path p(basePath,appName); - p.setExtension(extension); - bool found = findFile(p); - if (!found) - { -#if defined(_DEBUG) - if (appName[appName.length() - 1] == 'd') - { - p.setBaseName(appName.substr(0, appName.length() - 1)); - found = findFile(p); - } -#endif - } - if (found) - path = p; - return found; -} - - -void Application::defineOptions(OptionSet& options) -{ - for (SubsystemVec::iterator it = _subsystems.begin(); it != _subsystems.end(); ++it) - { - (*it)->defineOptions(options); - } -} - - -void Application::handleOption(const std::string& name, const std::string& value) -{ - const Option& option = _options.getOption(name); - if (option.validator()) - { - option.validator()->validate(option, value); - } - if (!option.binding().empty()) - { - AbstractConfiguration* pConfig = option.config(); - if (!pConfig) pConfig = &config(); - pConfig->setString(option.binding(), value); - } - if (option.callback()) - { - option.callback()->invoke(name, value); - } -} - - -void Application::setLogger(Logger& logger) -{ - _pLogger = &logger; -} - - -} } // namespace Poco::Util +// +// Application.cpp +// +// Library: Util +// Package: Application +// Module: Application +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#include "Poco/Util/Application.h" +#include "Poco/Util/SystemConfiguration.h" +#include "Poco/Util/MapConfiguration.h" +#include "Poco/Util/PropertyFileConfiguration.h" +#include "Poco/Util/IniFileConfiguration.h" +#ifndef POCO_UTIL_NO_XMLCONFIGURATION +#include "Poco/Util/XMLConfiguration.h" +#endif +#ifndef POCO_UTIL_NO_JSONCONFIGURATION +#include "Poco/Util/JSONConfiguration.h" +#endif +#include "Poco/Util/LoggingSubsystem.h" +#include "Poco/Util/Option.h" +#include "Poco/Util/OptionProcessor.h" +#include "Poco/Util/Validator.h" +#include "Poco/Environment.h" +#include "Poco/Exception.h" +#include "Poco/NumberFormatter.h" +#include "Poco/File.h" +#include "Poco/Path.h" +#include "Poco/String.h" +#include "Poco/ConsoleChannel.h" +#include "Poco/AutoPtr.h" +#if defined(POCO_OS_FAMILY_WINDOWS) +#include "Poco/UnWindows.h" +#endif +#if defined(POCO_OS_FAMILY_UNIX) && !defined(POCO_VXWORKS) +#include "Poco/SignalHandler.h" +#endif +#if defined(POCO_WIN32_UTF8) && !defined(POCO_NO_WSTRING) +#include "Poco/UnicodeConverter.h" +#endif + + +using Poco::Logger; +using Poco::Path; +using Poco::File; +using Poco::Environment; +using Poco::SystemException; +using Poco::ConsoleChannel; +using Poco::NumberFormatter; +using Poco::AutoPtr; +using Poco::icompare; + + +namespace Poco { +namespace Util { + + +Application* Application::_pInstance = 0; + + +Application::Application(): + _pConfig(new LayeredConfiguration), + _initialized(false), + _unixOptions(true), + _pLogger(&Logger::get("ApplicationStartup")), + _stopOptionsProcessing(false) +{ + setup(); +} + + +Application::Application(int argc, char* argv[]): + _pConfig(new LayeredConfiguration), + _initialized(false), + _unixOptions(true), + _pLogger(&Logger::get("ApplicationStartup")), + _stopOptionsProcessing(false) +{ + setup(); + init(argc, argv); +} + + +Application::~Application() +{ + _pInstance = 0; +} + + +void Application::setup() +{ + poco_assert (_pInstance == 0); + + _pConfig->add(new SystemConfiguration, PRIO_SYSTEM, false, false); + _pConfig->add(new MapConfiguration, PRIO_APPLICATION, true, false); + + addSubsystem(new LoggingSubsystem); + +#if defined(POCO_OS_FAMILY_UNIX) && !defined(POCO_VXWORKS) + _workingDirAtLaunch = Path::current(); + + #if !defined(_DEBUG) + Poco::SignalHandler::install(); + #endif +#else + setUnixOptions(false); +#endif + + _pInstance = this; + + AutoPtr<ConsoleChannel> pCC = new ConsoleChannel; + Logger::setChannel("", pCC); +} + + +void Application::addSubsystem(Subsystem* pSubsystem) +{ + poco_check_ptr (pSubsystem); + + _subsystems.push_back(pSubsystem); +} + + +void Application::init(int argc, char* argv[]) +{ + setArgs(argc, argv); + init(); +} + + +#if defined(POCO_WIN32_UTF8) && !defined(POCO_NO_WSTRING) +void Application::init(int argc, wchar_t* argv[]) +{ + std::vector<std::string> args; + for (int i = 0; i < argc; ++i) + { + std::string arg; + Poco::UnicodeConverter::toUTF8(argv[i], arg); + args.push_back(arg); + } + init(args); +} +#endif + + +void Application::init(const ArgVec& args) +{ + setArgs(args); + init(); +} + + +void Application::init() +{ + Path appPath; + getApplicationPath(appPath); + _pConfig->setString("application.path", appPath.toString()); + _pConfig->setString("application.name", appPath.getFileName()); + _pConfig->setString("application.baseName", appPath.getBaseName()); + _pConfig->setString("application.dir", appPath.parent().toString()); + _pConfig->setString("application.configDir", Path::configHome() + appPath.getBaseName() + Path::separator()); + _pConfig->setString("application.cacheDir", Path::cacheHome() + appPath.getBaseName() + Path::separator()); + _pConfig->setString("application.tempDir", Path::tempHome() + appPath.getBaseName() + Path::separator()); + _pConfig->setString("application.dataDir", Path::dataHome() + appPath.getBaseName() + Path::separator()); + processOptions(); +} + + +const char* Application::name() const +{ + return "Application"; +} + + +void Application::initialize(Application& self) +{ + for (SubsystemVec::iterator it = _subsystems.begin(); it != _subsystems.end(); ++it) + { + _pLogger->debug(std::string("Initializing subsystem: ") + (*it)->name()); + (*it)->initialize(self); + } + _initialized = true; +} + + +void Application::uninitialize() +{ + if (_initialized) + { + for (SubsystemVec::reverse_iterator it = _subsystems.rbegin(); it != _subsystems.rend(); ++it) + { + _pLogger->debug(std::string("Uninitializing subsystem: ") + (*it)->name()); + (*it)->uninitialize(); + } + _initialized = false; + } +} + + +void Application::reinitialize(Application& self) +{ + for (SubsystemVec::iterator it = _subsystems.begin(); it != _subsystems.end(); ++it) + { + _pLogger->debug(std::string("Re-initializing subsystem: ") + (*it)->name()); + (*it)->reinitialize(self); + } +} + + +void Application::setUnixOptions(bool flag) +{ + _unixOptions = flag; +} + + +int Application::loadConfiguration(int priority) +{ + int n = 0; + Path appPath; + getApplicationPath(appPath); + Path confPath; + if (findAppConfigFile(appPath.getBaseName(), "properties", confPath)) + { + _pConfig->add(new PropertyFileConfiguration(confPath.toString()), priority, false, false); + ++n; + } +#ifndef POCO_UTIL_NO_INIFILECONFIGURATION + if (findAppConfigFile(appPath.getBaseName(), "ini", confPath)) + { + _pConfig->add(new IniFileConfiguration(confPath.toString()), priority, false, false); + ++n; + } +#endif +#ifndef POCO_UTIL_NO_JSONCONFIGURATION + if (findAppConfigFile(appPath.getBaseName(), "json", confPath)) + { + _pConfig->add(new JSONConfiguration(confPath.toString()), priority, false, false); + ++n; + } +#endif +#ifndef POCO_UTIL_NO_XMLCONFIGURATION + if (findAppConfigFile(appPath.getBaseName(), "xml", confPath)) + { + _pConfig->add(new XMLConfiguration(confPath.toString()), priority, false, false); + ++n; + } +#endif + if (n > 0) + { + if (!confPath.isAbsolute()) + _pConfig->setString("application.configDir", confPath.absolute().parent().toString()); + else + _pConfig->setString("application.configDir", confPath.parent().toString()); + } + return n; +} + + +void Application::loadConfiguration(const std::string& path, int priority) +{ + int n = 0; + Path confPath(path); + std::string ext = confPath.getExtension(); + if (icompare(ext, "properties") == 0) + { + _pConfig->add(new PropertyFileConfiguration(confPath.toString()), priority, false, false); + ++n; + } +#ifndef POCO_UTIL_NO_INIFILECONFIGURATION + else if (icompare(ext, "ini") == 0) + { + _pConfig->add(new IniFileConfiguration(confPath.toString()), priority, false, false); + ++n; + } +#endif +#ifndef POCO_UTIL_NO_JSONCONFIGURATION + else if (icompare(ext, "json") == 0) + { + _pConfig->add(new JSONConfiguration(confPath.toString()), priority, false, false); + ++n; + } +#endif +#ifndef POCO_UTIL_NO_XMLCONFIGURATION + else if (icompare(ext, "xml") == 0) + { + _pConfig->add(new XMLConfiguration(confPath.toString()), priority, false, false); + ++n; + } +#endif + else throw Poco::InvalidArgumentException("Unsupported configuration file type", ext); + + if (n > 0 && !_pConfig->has("application.configDir")) + { + if (!confPath.isAbsolute()) + _pConfig->setString("application.configDir", confPath.absolute().parent().toString()); + else + _pConfig->setString("application.configDir", confPath.parent().toString()); + } +} + + +std::string Application::commandName() const +{ + return _pConfig->getString("application.baseName"); +} + + +std::string Application::commandPath() const +{ + return _pConfig->getString("application.path"); +} + + +void Application::stopOptionsProcessing() +{ + _stopOptionsProcessing = true; +} + + +int Application::run() +{ + int rc = EXIT_CONFIG; + initialize(*this); + + try + { + rc = EXIT_SOFTWARE; + rc = main(_unprocessedArgs); + } + catch (Poco::Exception& exc) + { + logger().log(exc); + } + catch (std::exception& exc) + { + logger().error(exc.what()); + } + catch (...) + { + logger().fatal("system exception"); + } + + uninitialize(); + return rc; +} + + +int Application::main(const ArgVec& /*args*/) +{ + return EXIT_OK; +} + + +void Application::setArgs(int argc, char* argv[]) +{ + _command = argv[0]; + _pConfig->setInt("application.argc", argc); + _unprocessedArgs.reserve(argc); + std::string argvKey = "application.argv["; + for (int i = 0; i < argc; ++i) + { + std::string arg(argv[i]); + _pConfig->setString(argvKey + NumberFormatter::format(i) + "]", arg); + _unprocessedArgs.push_back(arg); + } +} + + +void Application::setArgs(const ArgVec& args) +{ + poco_assert (!args.empty()); + + _command = args[0]; + _pConfig->setInt("application.argc", (int) args.size()); + _unprocessedArgs = args; + std::string argvKey = "application.argv["; + for (int i = 0; i < args.size(); ++i) + { + _pConfig->setString(argvKey + NumberFormatter::format(i) + "]", args[i]); + } +} + + +void Application::processOptions() +{ + defineOptions(_options); + OptionProcessor processor(_options); + processor.setUnixStyle(_unixOptions); + _argv = _unprocessedArgs; + _unprocessedArgs.erase(_unprocessedArgs.begin()); + ArgVec::iterator it = _unprocessedArgs.begin(); + while (it != _unprocessedArgs.end() && !_stopOptionsProcessing) + { + std::string name; + std::string value; + if (processor.process(*it, name, value)) + { + if (!name.empty()) // "--" option to end options processing or deferred argument + { + handleOption(name, value); + } + it = _unprocessedArgs.erase(it); + } + else ++it; + } + if (!_stopOptionsProcessing) + processor.checkRequired(); +} + + +void Application::getApplicationPath(Poco::Path& appPath) const +{ +#if defined(POCO_OS_FAMILY_UNIX) && !defined(POCO_VXWORKS) + if (_command.find('/') != std::string::npos) + { + Path path(_command); + if (path.isAbsolute()) + { + appPath = path; + } + else + { + appPath = _workingDirAtLaunch; + appPath.append(path); + } + } + else + { + if (!Path::find(Environment::get("PATH"), _command, appPath)) + appPath = Path(_workingDirAtLaunch, _command); + appPath.makeAbsolute(); + } +#elif defined(POCO_OS_FAMILY_WINDOWS) + #if defined(POCO_WIN32_UTF8) && !defined(POCO_NO_WSTRING) + wchar_t path[1024]; + int n = GetModuleFileNameW(0, path, sizeof(path)/sizeof(wchar_t)); + if (n > 0) + { + std::string p; + Poco::UnicodeConverter::toUTF8(path, p); + appPath = p; + } + else throw SystemException("Cannot get application file name."); + #else + char path[1024]; + int n = GetModuleFileNameA(0, path, sizeof(path)); + if (n > 0) + appPath = path; + else + throw SystemException("Cannot get application file name."); + #endif +#else + appPath = _command; +#endif +} + + +bool Application::findFile(Poco::Path& path) const +{ + if (path.isAbsolute()) return true; + + Path appPath; + getApplicationPath(appPath); + Path base = appPath.parent(); + do + { + Path p(base, path); + File f(p); + if (f.exists()) + { + path = p; + return true; + } + if (base.depth() > 0) base.popDirectory(); + } + while (base.depth() > 0); + return false; +} + + +bool Application::findAppConfigFile(const std::string& appName, const std::string& extension, Path& path) const +{ + poco_assert (!appName.empty()); + + Path p(appName); + p.setExtension(extension); + bool found = findFile(p); + if (!found) + { +#if defined(_DEBUG) + if (appName[appName.length() - 1] == 'd') + { + p.setBaseName(appName.substr(0, appName.length() - 1)); + found = findFile(p); + } +#endif + } + if (found) + path = p; + return found; +} + + +bool Application::findAppConfigFile(const Path& basePath, const std::string& appName, const std::string& extension, Path& path) const +{ + poco_assert (!appName.empty()); + + Path p(basePath,appName); + p.setExtension(extension); + bool found = findFile(p); + if (!found) + { +#if defined(_DEBUG) + if (appName[appName.length() - 1] == 'd') + { + p.setBaseName(appName.substr(0, appName.length() - 1)); + found = findFile(p); + } +#endif + } + if (found) + path = p; + return found; +} + + +void Application::defineOptions(OptionSet& options) +{ + for (SubsystemVec::iterator it = _subsystems.begin(); it != _subsystems.end(); ++it) + { + (*it)->defineOptions(options); + } +} + + +void Application::handleOption(const std::string& name, const std::string& value) +{ + const Option& option = _options.getOption(name); + if (option.validator()) + { + option.validator()->validate(option, value); + } + if (!option.binding().empty()) + { + AbstractConfiguration* pConfig = option.config(); + if (!pConfig) pConfig = &config(); + pConfig->setString(option.binding(), value); + } + if (option.callback()) + { + option.callback()->invoke(name, value); + } +} + + +void Application::setLogger(Logger& logger) +{ + _pLogger = &logger; +} + + +} } // namespace Poco::Util diff --git a/contrib/libs/poco/Util/src/ConfigurationMapper.cpp b/contrib/libs/poco/Util/src/ConfigurationMapper.cpp index 54e292be9f..d76f9c0b6d 100644 --- a/contrib/libs/poco/Util/src/ConfigurationMapper.cpp +++ b/contrib/libs/poco/Util/src/ConfigurationMapper.cpp @@ -1,101 +1,101 @@ -// -// ConfigurationMapper.cpp -// -// Library: Util -// Package: Configuration -// Module: ConfigurationMapper -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// SPDX-License-Identifier: BSL-1.0 -// - - -#include "Poco/Util/ConfigurationMapper.h" - - -namespace Poco { -namespace Util { - - -ConfigurationMapper::ConfigurationMapper(const std::string& fromPrefix, const std::string& toPrefix, AbstractConfiguration* pConfig): - _fromPrefix(fromPrefix), - _toPrefix(toPrefix), - _pConfig(pConfig) -{ - poco_check_ptr (pConfig); - - if (!_fromPrefix.empty()) _fromPrefix += '.'; - if (!_toPrefix.empty()) _toPrefix += '.'; - - _pConfig->duplicate(); -} - - -ConfigurationMapper::~ConfigurationMapper() -{ - _pConfig->release(); -} - - -bool ConfigurationMapper::getRaw(const std::string& key, std::string& value) const -{ - std::string translatedKey = translateKey(key); - return _pConfig->getRaw(translatedKey, value); -} - - -void ConfigurationMapper::setRaw(const std::string& key, const std::string& value) -{ - std::string translatedKey = translateKey(key); - _pConfig->setRaw(translatedKey, value); -} - - -void ConfigurationMapper::enumerate(const std::string& key, Keys& range) const -{ - std::string cKey(key); - if (!cKey.empty()) cKey += '.'; - std::string::size_type keyLen = cKey.length(); - if (keyLen < _toPrefix.length()) - { - if (_toPrefix.compare(0, keyLen, cKey) == 0) - { - std::string::size_type pos = _toPrefix.find_first_of('.', keyLen); - poco_assert_dbg(pos != std::string::npos); - range.push_back(_toPrefix.substr(keyLen, pos - keyLen)); - } - } - else - { - std::string translatedKey; - if (cKey == _toPrefix) - { - translatedKey = _fromPrefix; - if (!translatedKey.empty()) - translatedKey.resize(translatedKey.length() - 1); - } - else translatedKey = translateKey(key); - _pConfig->enumerate(translatedKey, range); - } -} - - -void ConfigurationMapper::removeRaw(const std::string& key) -{ - std::string translatedKey = translateKey(key); - _pConfig->remove(translatedKey); -} - - -std::string ConfigurationMapper::translateKey(const std::string& key) const -{ - std::string result(key); - if (result.compare(0, _toPrefix.size(), _toPrefix) == 0) - result.replace(0, _toPrefix.size(), _fromPrefix); - return result; -} - - -} } // namespace Poco::Util +// +// ConfigurationMapper.cpp +// +// Library: Util +// Package: Configuration +// Module: ConfigurationMapper +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#include "Poco/Util/ConfigurationMapper.h" + + +namespace Poco { +namespace Util { + + +ConfigurationMapper::ConfigurationMapper(const std::string& fromPrefix, const std::string& toPrefix, AbstractConfiguration* pConfig): + _fromPrefix(fromPrefix), + _toPrefix(toPrefix), + _pConfig(pConfig) +{ + poco_check_ptr (pConfig); + + if (!_fromPrefix.empty()) _fromPrefix += '.'; + if (!_toPrefix.empty()) _toPrefix += '.'; + + _pConfig->duplicate(); +} + + +ConfigurationMapper::~ConfigurationMapper() +{ + _pConfig->release(); +} + + +bool ConfigurationMapper::getRaw(const std::string& key, std::string& value) const +{ + std::string translatedKey = translateKey(key); + return _pConfig->getRaw(translatedKey, value); +} + + +void ConfigurationMapper::setRaw(const std::string& key, const std::string& value) +{ + std::string translatedKey = translateKey(key); + _pConfig->setRaw(translatedKey, value); +} + + +void ConfigurationMapper::enumerate(const std::string& key, Keys& range) const +{ + std::string cKey(key); + if (!cKey.empty()) cKey += '.'; + std::string::size_type keyLen = cKey.length(); + if (keyLen < _toPrefix.length()) + { + if (_toPrefix.compare(0, keyLen, cKey) == 0) + { + std::string::size_type pos = _toPrefix.find_first_of('.', keyLen); + poco_assert_dbg(pos != std::string::npos); + range.push_back(_toPrefix.substr(keyLen, pos - keyLen)); + } + } + else + { + std::string translatedKey; + if (cKey == _toPrefix) + { + translatedKey = _fromPrefix; + if (!translatedKey.empty()) + translatedKey.resize(translatedKey.length() - 1); + } + else translatedKey = translateKey(key); + _pConfig->enumerate(translatedKey, range); + } +} + + +void ConfigurationMapper::removeRaw(const std::string& key) +{ + std::string translatedKey = translateKey(key); + _pConfig->remove(translatedKey); +} + + +std::string ConfigurationMapper::translateKey(const std::string& key) const +{ + std::string result(key); + if (result.compare(0, _toPrefix.size(), _toPrefix) == 0) + result.replace(0, _toPrefix.size(), _fromPrefix); + return result; +} + + +} } // namespace Poco::Util diff --git a/contrib/libs/poco/Util/src/ConfigurationView.cpp b/contrib/libs/poco/Util/src/ConfigurationView.cpp index 1231d242c2..008a24f489 100644 --- a/contrib/libs/poco/Util/src/ConfigurationView.cpp +++ b/contrib/libs/poco/Util/src/ConfigurationView.cpp @@ -1,75 +1,75 @@ -// -// ConfigurationView.cpp -// -// Library: Util -// Package: Configuration -// Module: ConfigurationView -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// SPDX-License-Identifier: BSL-1.0 -// - - -#include "Poco/Util/ConfigurationView.h" - - -namespace Poco { -namespace Util { - - -ConfigurationView::ConfigurationView(const std::string& prefix, AbstractConfiguration* pConfig): - _prefix(prefix), - _pConfig(pConfig) -{ - poco_check_ptr (pConfig); - - _pConfig->duplicate(); -} - - -ConfigurationView::~ConfigurationView() -{ - _pConfig->release(); -} - - -bool ConfigurationView::getRaw(const std::string& key, std::string& value) const -{ - std::string translatedKey = translateKey(key); - return _pConfig->getRaw(translatedKey, value) || _pConfig->getRaw(key, value); -} - - -void ConfigurationView::setRaw(const std::string& key, const std::string& value) -{ - std::string translatedKey = translateKey(key); - _pConfig->setRaw(translatedKey, value); -} - - -void ConfigurationView::enumerate(const std::string& key, Keys& range) const -{ - std::string translatedKey = translateKey(key); - _pConfig->enumerate(translatedKey, range); -} - - -void ConfigurationView::removeRaw(const std::string& key) -{ - std::string translatedKey = translateKey(key); - _pConfig->remove(translatedKey); -} - - -std::string ConfigurationView::translateKey(const std::string& key) const -{ - std::string result = _prefix; - if (!result.empty() && !key.empty() && key[0] != '[') result += '.'; - result += key; - return result; -} - - -} } // namespace Poco::Util +// +// ConfigurationView.cpp +// +// Library: Util +// Package: Configuration +// Module: ConfigurationView +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#include "Poco/Util/ConfigurationView.h" + + +namespace Poco { +namespace Util { + + +ConfigurationView::ConfigurationView(const std::string& prefix, AbstractConfiguration* pConfig): + _prefix(prefix), + _pConfig(pConfig) +{ + poco_check_ptr (pConfig); + + _pConfig->duplicate(); +} + + +ConfigurationView::~ConfigurationView() +{ + _pConfig->release(); +} + + +bool ConfigurationView::getRaw(const std::string& key, std::string& value) const +{ + std::string translatedKey = translateKey(key); + return _pConfig->getRaw(translatedKey, value) || _pConfig->getRaw(key, value); +} + + +void ConfigurationView::setRaw(const std::string& key, const std::string& value) +{ + std::string translatedKey = translateKey(key); + _pConfig->setRaw(translatedKey, value); +} + + +void ConfigurationView::enumerate(const std::string& key, Keys& range) const +{ + std::string translatedKey = translateKey(key); + _pConfig->enumerate(translatedKey, range); +} + + +void ConfigurationView::removeRaw(const std::string& key) +{ + std::string translatedKey = translateKey(key); + _pConfig->remove(translatedKey); +} + + +std::string ConfigurationView::translateKey(const std::string& key) const +{ + std::string result = _prefix; + if (!result.empty() && !key.empty() && key[0] != '[') result += '.'; + result += key; + return result; +} + + +} } // namespace Poco::Util diff --git a/contrib/libs/poco/Util/src/FilesystemConfiguration.cpp b/contrib/libs/poco/Util/src/FilesystemConfiguration.cpp index 8d685143d3..1978694a37 100644 --- a/contrib/libs/poco/Util/src/FilesystemConfiguration.cpp +++ b/contrib/libs/poco/Util/src/FilesystemConfiguration.cpp @@ -1,127 +1,127 @@ -// -// FilesystemConfiguration.cpp -// -// Library: Util -// Package: Configuration -// Module: FilesystemConfiguration -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// SPDX-License-Identifier: BSL-1.0 -// - - -#include "Poco/Util/FilesystemConfiguration.h" -#include "Poco/File.h" -#include "Poco/Path.h" -#include "Poco/DirectoryIterator.h" -#include "Poco/StringTokenizer.h" -#include "Poco/FileStream.h" - - -using Poco::Path; -using Poco::File; -using Poco::DirectoryIterator; -using Poco::StringTokenizer; - - -namespace Poco { -namespace Util { - - -FilesystemConfiguration::FilesystemConfiguration(const std::string& path): - _path(path) -{ - _path.makeDirectory(); -} - - -FilesystemConfiguration::~FilesystemConfiguration() -{ -} - - -void FilesystemConfiguration::clear() -{ - File regDir(_path); - regDir.remove(true); -} - - -bool FilesystemConfiguration::getRaw(const std::string& key, std::string& value) const -{ - Path p(keyToPath(key)); - p.setFileName("data"); - File f(p); - if (f.exists()) - { - value.reserve((std::string::size_type) f.getSize()); - Poco::FileInputStream istr(p.toString()); - int c = istr.get(); - while (c != std::char_traits<char>::eof()) - { - value += (char) c; - c = istr.get(); - } - return true; - } - else return false; -} - - -void FilesystemConfiguration::setRaw(const std::string& key, const std::string& value) -{ - Path p(keyToPath(key)); - File dir(p); - dir.createDirectories(); - p.setFileName("data"); - Poco::FileOutputStream ostr(p.toString()); - ostr.write(value.data(), (std::streamsize) value.length()); -} - - -void FilesystemConfiguration::enumerate(const std::string& key, Keys& range) const -{ - Path p(keyToPath(key)); - File dir(p); - if (!dir.exists()) - { - return; - } - - DirectoryIterator it(p); - DirectoryIterator end; - while (it != end) - { - if (it->isDirectory()) - range.push_back(it.name()); - ++it; - } -} - - -void FilesystemConfiguration::removeRaw(const std::string& key) -{ - Path p(keyToPath(key)); - File dir(p); - if (dir.exists()) - { - dir.remove(true); - } -} - - -Path FilesystemConfiguration::keyToPath(const std::string& key) const -{ - Path result(_path); - StringTokenizer tokenizer(key, ".", StringTokenizer::TOK_IGNORE_EMPTY | StringTokenizer::TOK_TRIM); - for (StringTokenizer::Iterator it = tokenizer.begin(); it != tokenizer.end(); ++it) - { - result.pushDirectory(*it); - } - return result; -} - - -} } // namespace Poco::Util +// +// FilesystemConfiguration.cpp +// +// Library: Util +// Package: Configuration +// Module: FilesystemConfiguration +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#include "Poco/Util/FilesystemConfiguration.h" +#include "Poco/File.h" +#include "Poco/Path.h" +#include "Poco/DirectoryIterator.h" +#include "Poco/StringTokenizer.h" +#include "Poco/FileStream.h" + + +using Poco::Path; +using Poco::File; +using Poco::DirectoryIterator; +using Poco::StringTokenizer; + + +namespace Poco { +namespace Util { + + +FilesystemConfiguration::FilesystemConfiguration(const std::string& path): + _path(path) +{ + _path.makeDirectory(); +} + + +FilesystemConfiguration::~FilesystemConfiguration() +{ +} + + +void FilesystemConfiguration::clear() +{ + File regDir(_path); + regDir.remove(true); +} + + +bool FilesystemConfiguration::getRaw(const std::string& key, std::string& value) const +{ + Path p(keyToPath(key)); + p.setFileName("data"); + File f(p); + if (f.exists()) + { + value.reserve((std::string::size_type) f.getSize()); + Poco::FileInputStream istr(p.toString()); + int c = istr.get(); + while (c != std::char_traits<char>::eof()) + { + value += (char) c; + c = istr.get(); + } + return true; + } + else return false; +} + + +void FilesystemConfiguration::setRaw(const std::string& key, const std::string& value) +{ + Path p(keyToPath(key)); + File dir(p); + dir.createDirectories(); + p.setFileName("data"); + Poco::FileOutputStream ostr(p.toString()); + ostr.write(value.data(), (std::streamsize) value.length()); +} + + +void FilesystemConfiguration::enumerate(const std::string& key, Keys& range) const +{ + Path p(keyToPath(key)); + File dir(p); + if (!dir.exists()) + { + return; + } + + DirectoryIterator it(p); + DirectoryIterator end; + while (it != end) + { + if (it->isDirectory()) + range.push_back(it.name()); + ++it; + } +} + + +void FilesystemConfiguration::removeRaw(const std::string& key) +{ + Path p(keyToPath(key)); + File dir(p); + if (dir.exists()) + { + dir.remove(true); + } +} + + +Path FilesystemConfiguration::keyToPath(const std::string& key) const +{ + Path result(_path); + StringTokenizer tokenizer(key, ".", StringTokenizer::TOK_IGNORE_EMPTY | StringTokenizer::TOK_TRIM); + for (StringTokenizer::Iterator it = tokenizer.begin(); it != tokenizer.end(); ++it) + { + result.pushDirectory(*it); + } + return result; +} + + +} } // namespace Poco::Util diff --git a/contrib/libs/poco/Util/src/HelpFormatter.cpp b/contrib/libs/poco/Util/src/HelpFormatter.cpp index e81a062949..41c8d28720 100644 --- a/contrib/libs/poco/Util/src/HelpFormatter.cpp +++ b/contrib/libs/poco/Util/src/HelpFormatter.cpp @@ -1,296 +1,296 @@ -// -// HelpFormatter.cpp -// -// Library: Util -// Package: Options -// Module: HelpFormatter -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// SPDX-License-Identifier: BSL-1.0 -// - - -#include "Poco/Util/HelpFormatter.h" -#include "Poco/Util/OptionSet.h" -#include "Poco/Util/Option.h" - - -namespace Poco { -namespace Util { - - -const int HelpFormatter::TAB_WIDTH = 4; -const int HelpFormatter::LINE_WIDTH = 78; - - -HelpFormatter::HelpFormatter(const OptionSet& options): - _options(options), - _width(LINE_WIDTH), - _indent(0), - _unixStyle(true) -{ -#if !defined(POCO_OS_FAMILY_UNIX) - _unixStyle = false; -#endif - _indent = calcIndent(); -} - - -HelpFormatter::~HelpFormatter() -{ -} - - -void HelpFormatter::setCommand(const std::string& command) -{ - _command = command; -} - - -void HelpFormatter::setUsage(const std::string& usage) -{ - _usage = usage; -} - - -void HelpFormatter::setHeader(const std::string& header) -{ - _header = header; -} - - -void HelpFormatter::setFooter(const std::string& footer) -{ - _footer = footer; -} - - -void HelpFormatter::format(std::ostream& ostr) const -{ - ostr << "usage: " << _command; - if (!_usage.empty()) - { - ostr << ' '; - formatText(ostr, _usage, (int) _command.length() + 1); - } - ostr << '\n'; - if (!_header.empty()) - { - formatText(ostr, _header, 0); - ostr << "\n\n"; - } - formatOptions(ostr); - if (!_footer.empty()) - { - ostr << '\n'; - formatText(ostr, _footer, 0); - ostr << '\n'; - } -} - - -void HelpFormatter::setWidth(int width) -{ - poco_assert (width > 0); - - _width = width; -} - - -void HelpFormatter::setIndent(int indent) -{ - poco_assert (indent >= 0 && indent < _width); - - _indent = indent; -} - - -void HelpFormatter::setAutoIndent() -{ - _indent = calcIndent(); -} - - -void HelpFormatter::setUnixStyle(bool flag) -{ - _unixStyle = flag; -} - - -int HelpFormatter::calcIndent() const -{ - int indent = 0; - for (OptionSet::Iterator it = _options.begin(); it != _options.end(); ++it) - { - int shortLen = (int) it->shortName().length(); - int fullLen = (int) it->fullName().length(); - int n = 0; - if (_unixStyle && shortLen > 0) - { - n += shortLen + (int) shortPrefix().length(); - if (it->takesArgument()) - n += (int) it->argumentName().length() + (it->argumentRequired() ? 0 : 2); - if (fullLen > 0) n += 2; - } - if (fullLen > 0) - { - n += fullLen + (int) longPrefix().length(); - if (it->takesArgument()) - n += 1 + (int) it->argumentName().length() + (it->argumentRequired() ? 0 : 2); - } - n += 2; - if (n > indent) - indent = n; - } - return indent; -} - - -void HelpFormatter::formatOptions(std::ostream& ostr) const -{ - int optWidth = calcIndent(); - for (OptionSet::Iterator it = _options.begin(); it != _options.end(); ++it) - { - formatOption(ostr, *it, optWidth); - if (_indent < optWidth) - { - ostr << '\n' << std::string(_indent, ' '); - formatText(ostr, it->description(), _indent, _indent); - } +// +// HelpFormatter.cpp +// +// Library: Util +// Package: Options +// Module: HelpFormatter +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#include "Poco/Util/HelpFormatter.h" +#include "Poco/Util/OptionSet.h" +#include "Poco/Util/Option.h" + + +namespace Poco { +namespace Util { + + +const int HelpFormatter::TAB_WIDTH = 4; +const int HelpFormatter::LINE_WIDTH = 78; + + +HelpFormatter::HelpFormatter(const OptionSet& options): + _options(options), + _width(LINE_WIDTH), + _indent(0), + _unixStyle(true) +{ +#if !defined(POCO_OS_FAMILY_UNIX) + _unixStyle = false; +#endif + _indent = calcIndent(); +} + + +HelpFormatter::~HelpFormatter() +{ +} + + +void HelpFormatter::setCommand(const std::string& command) +{ + _command = command; +} + + +void HelpFormatter::setUsage(const std::string& usage) +{ + _usage = usage; +} + + +void HelpFormatter::setHeader(const std::string& header) +{ + _header = header; +} + + +void HelpFormatter::setFooter(const std::string& footer) +{ + _footer = footer; +} + + +void HelpFormatter::format(std::ostream& ostr) const +{ + ostr << "usage: " << _command; + if (!_usage.empty()) + { + ostr << ' '; + formatText(ostr, _usage, (int) _command.length() + 1); + } + ostr << '\n'; + if (!_header.empty()) + { + formatText(ostr, _header, 0); + ostr << "\n\n"; + } + formatOptions(ostr); + if (!_footer.empty()) + { + ostr << '\n'; + formatText(ostr, _footer, 0); + ostr << '\n'; + } +} + + +void HelpFormatter::setWidth(int width) +{ + poco_assert (width > 0); + + _width = width; +} + + +void HelpFormatter::setIndent(int indent) +{ + poco_assert (indent >= 0 && indent < _width); + + _indent = indent; +} + + +void HelpFormatter::setAutoIndent() +{ + _indent = calcIndent(); +} + + +void HelpFormatter::setUnixStyle(bool flag) +{ + _unixStyle = flag; +} + + +int HelpFormatter::calcIndent() const +{ + int indent = 0; + for (OptionSet::Iterator it = _options.begin(); it != _options.end(); ++it) + { + int shortLen = (int) it->shortName().length(); + int fullLen = (int) it->fullName().length(); + int n = 0; + if (_unixStyle && shortLen > 0) + { + n += shortLen + (int) shortPrefix().length(); + if (it->takesArgument()) + n += (int) it->argumentName().length() + (it->argumentRequired() ? 0 : 2); + if (fullLen > 0) n += 2; + } + if (fullLen > 0) + { + n += fullLen + (int) longPrefix().length(); + if (it->takesArgument()) + n += 1 + (int) it->argumentName().length() + (it->argumentRequired() ? 0 : 2); + } + n += 2; + if (n > indent) + indent = n; + } + return indent; +} + + +void HelpFormatter::formatOptions(std::ostream& ostr) const +{ + int optWidth = calcIndent(); + for (OptionSet::Iterator it = _options.begin(); it != _options.end(); ++it) + { + formatOption(ostr, *it, optWidth); + if (_indent < optWidth) + { + ostr << '\n' << std::string(_indent, ' '); + formatText(ostr, it->description(), _indent, _indent); + } + else + { + formatText(ostr, it->description(), _indent, optWidth); + } + ostr << '\n'; + } +} + + +void HelpFormatter::formatOption(std::ostream& ostr, const Option& option, int width) const +{ + int shortLen = (int) option.shortName().length(); + int fullLen = (int) option.fullName().length(); + + int n = 0; + if (_unixStyle && shortLen > 0) + { + ostr << shortPrefix() << option.shortName(); + n += (int) shortPrefix().length() + (int) option.shortName().length(); + if (option.takesArgument()) + { + if (!option.argumentRequired()) { ostr << '['; ++n; } + ostr << option.argumentName(); + n += (int) option.argumentName().length(); + if (!option.argumentRequired()) { ostr << ']'; ++n; } + } + if (fullLen > 0) { ostr << ", "; n += 2; } + } + if (fullLen > 0) + { + ostr << longPrefix() << option.fullName(); + n += (int) longPrefix().length() + (int) option.fullName().length(); + if (option.takesArgument()) + { + if (!option.argumentRequired()) { ostr << '['; ++n; } + ostr << '='; + ++n; + ostr << option.argumentName(); + n += (int) option.argumentName().length(); + if (!option.argumentRequired()) { ostr << ']'; ++n; } + } + } + while (n < width) { ostr << ' '; ++n; } +} + + +void HelpFormatter::formatText(std::ostream& ostr, const std::string& text, int indent) const +{ + formatText(ostr, text, indent, indent); +} + + +void HelpFormatter::formatText(std::ostream& ostr, const std::string& text, int indent, int firstIndent) const +{ + int pos = firstIndent; + int maxWordLen = _width - indent; + std::string word; + for (std::string::const_iterator it = text.begin(); it != text.end(); ++it) + { + if (*it == '\n') + { + clearWord(ostr, pos, word, indent); + ostr << '\n'; + pos = 0; + while (pos < indent) { ostr << ' '; ++pos; } + } + else if (*it == '\t') + { + clearWord(ostr, pos, word, indent); + if (pos < _width) ++pos; + while (pos < _width && pos % TAB_WIDTH != 0) + { + ostr << ' '; + ++pos; + } + } + else if (*it == ' ') + { + clearWord(ostr, pos, word, indent); + if (pos < _width) { ostr << ' '; ++pos; } + } else - { - formatText(ostr, it->description(), _indent, optWidth); - } - ostr << '\n'; - } -} - - -void HelpFormatter::formatOption(std::ostream& ostr, const Option& option, int width) const -{ - int shortLen = (int) option.shortName().length(); - int fullLen = (int) option.fullName().length(); - - int n = 0; - if (_unixStyle && shortLen > 0) - { - ostr << shortPrefix() << option.shortName(); - n += (int) shortPrefix().length() + (int) option.shortName().length(); - if (option.takesArgument()) - { - if (!option.argumentRequired()) { ostr << '['; ++n; } - ostr << option.argumentName(); - n += (int) option.argumentName().length(); - if (!option.argumentRequired()) { ostr << ']'; ++n; } - } - if (fullLen > 0) { ostr << ", "; n += 2; } - } - if (fullLen > 0) - { - ostr << longPrefix() << option.fullName(); - n += (int) longPrefix().length() + (int) option.fullName().length(); - if (option.takesArgument()) - { - if (!option.argumentRequired()) { ostr << '['; ++n; } - ostr << '='; - ++n; - ostr << option.argumentName(); - n += (int) option.argumentName().length(); - if (!option.argumentRequired()) { ostr << ']'; ++n; } - } - } - while (n < width) { ostr << ' '; ++n; } -} - - -void HelpFormatter::formatText(std::ostream& ostr, const std::string& text, int indent) const -{ - formatText(ostr, text, indent, indent); -} - - -void HelpFormatter::formatText(std::ostream& ostr, const std::string& text, int indent, int firstIndent) const -{ - int pos = firstIndent; - int maxWordLen = _width - indent; - std::string word; - for (std::string::const_iterator it = text.begin(); it != text.end(); ++it) - { - if (*it == '\n') - { - clearWord(ostr, pos, word, indent); - ostr << '\n'; - pos = 0; - while (pos < indent) { ostr << ' '; ++pos; } - } - else if (*it == '\t') - { - clearWord(ostr, pos, word, indent); - if (pos < _width) ++pos; - while (pos < _width && pos % TAB_WIDTH != 0) - { - ostr << ' '; - ++pos; - } - } - else if (*it == ' ') - { - clearWord(ostr, pos, word, indent); - if (pos < _width) { ostr << ' '; ++pos; } - } - else - { - if (word.length() == maxWordLen) - { - clearWord(ostr, pos, word, indent); - } - else word += *it; - } - } - clearWord(ostr, pos, word, indent); -} - - -void HelpFormatter::formatWord(std::ostream& ostr, int& pos, const std::string& word, int indent) const -{ - if (pos + word.length() > _width) - { - ostr << '\n'; - pos = 0; - while (pos < indent) { ostr << ' '; ++pos; } - } - ostr << word; - pos += (int) word.length(); -} - - -void HelpFormatter::clearWord(std::ostream& ostr, int& pos, std::string& word, int indent) const -{ - formatWord(ostr, pos, word, indent); - word.clear(); -} - - -std::string HelpFormatter::shortPrefix() const -{ -#if defined(POCO_OS_FAMILY_UNIX) - return "-"; -#else - return _unixStyle ? "-" : "/"; -#endif -} - - -std::string HelpFormatter::longPrefix() const -{ -#if defined(POCO_OS_FAMILY_UNIX) - return "--"; -#else - return _unixStyle ? "--" : "/"; -#endif -} - - -} } // namespace Poco::Util + { + if (word.length() == maxWordLen) + { + clearWord(ostr, pos, word, indent); + } + else word += *it; + } + } + clearWord(ostr, pos, word, indent); +} + + +void HelpFormatter::formatWord(std::ostream& ostr, int& pos, const std::string& word, int indent) const +{ + if (pos + word.length() > _width) + { + ostr << '\n'; + pos = 0; + while (pos < indent) { ostr << ' '; ++pos; } + } + ostr << word; + pos += (int) word.length(); +} + + +void HelpFormatter::clearWord(std::ostream& ostr, int& pos, std::string& word, int indent) const +{ + formatWord(ostr, pos, word, indent); + word.clear(); +} + + +std::string HelpFormatter::shortPrefix() const +{ +#if defined(POCO_OS_FAMILY_UNIX) + return "-"; +#else + return _unixStyle ? "-" : "/"; +#endif +} + + +std::string HelpFormatter::longPrefix() const +{ +#if defined(POCO_OS_FAMILY_UNIX) + return "--"; +#else + return _unixStyle ? "--" : "/"; +#endif +} + + +} } // namespace Poco::Util diff --git a/contrib/libs/poco/Util/src/IniFileConfiguration.cpp b/contrib/libs/poco/Util/src/IniFileConfiguration.cpp index 82c48bd695..76447c10ab 100644 --- a/contrib/libs/poco/Util/src/IniFileConfiguration.cpp +++ b/contrib/libs/poco/Util/src/IniFileConfiguration.cpp @@ -1,190 +1,190 @@ -// -// IniFileConfiguration.cpp -// -// Library: Util -// Package: Configuration -// Module: IniFileConfiguration -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// SPDX-License-Identifier: BSL-1.0 -// - - -#include "Poco/Util/IniFileConfiguration.h" - - -#ifndef POCO_UTIL_NO_INIFILECONFIGURATION - - -#include "Poco/Exception.h" -#include "Poco/String.h" -#include "Poco/Path.h" -#include "Poco/FileStream.h" -#include "Poco/Ascii.h" -#include <set> - - -using Poco::icompare; -using Poco::trim; -using Poco::Path; - - -namespace Poco { -namespace Util { - - -IniFileConfiguration::IniFileConfiguration() -{ -} - - -IniFileConfiguration::IniFileConfiguration(std::istream& istr) -{ - load(istr); -} - - -IniFileConfiguration::IniFileConfiguration(const std::string& path) -{ - load(path); -} - - -IniFileConfiguration::~IniFileConfiguration() -{ -} - - -void IniFileConfiguration::load(std::istream& istr) -{ - _map.clear(); - _sectionKey.clear(); - while (!istr.eof()) - { - parseLine(istr); - } -} - - -void IniFileConfiguration::load(const std::string& path) -{ - Poco::FileInputStream istr(path); - if (istr.good()) - load(istr); - else - throw Poco::OpenFileException(path); -} - - -bool IniFileConfiguration::getRaw(const std::string& key, std::string& value) const -{ - IStringMap::const_iterator it = _map.find(key); - if (it != _map.end()) - { - value = it->second; - return true; - } - else return false; -} - - -void IniFileConfiguration::setRaw(const std::string& key, const std::string& value) -{ - _map[key] = value; -} - - -void IniFileConfiguration::enumerate(const std::string& key, Keys& range) const -{ - std::set<std::string> keys; - std::string prefix = key; - if (!prefix.empty()) prefix += '.'; - std::string::size_type psize = prefix.size(); - for (IStringMap::const_iterator it = _map.begin(); it != _map.end(); ++it) - { - if (icompare(it->first, psize, prefix) == 0) - { - std::string subKey; - std::string::size_type end = it->first.find('.', psize); - if (end == std::string::npos) - subKey = it->first.substr(psize); - else - subKey = it->first.substr(psize, end - psize); - if (keys.find(subKey) == keys.end()) - { - range.push_back(subKey); - keys.insert(subKey); - } - } - } -} - - -void IniFileConfiguration::removeRaw(const std::string& key) -{ - std::string prefix = key; - if (!prefix.empty()) prefix += '.'; - std::string::size_type psize = prefix.size(); - IStringMap::iterator it = _map.begin(); - IStringMap::iterator itCur; - while (it != _map.end()) - { - itCur = it++; - if ((icompare(itCur->first, key) == 0) || (icompare(itCur->first, psize, prefix) == 0)) - { - _map.erase(itCur); - } - } -} - - -bool IniFileConfiguration::ICompare::operator () (const std::string& s1, const std::string& s2) const -{ - return icompare(s1, s2) < 0; -} - - -void IniFileConfiguration::parseLine(std::istream& istr) -{ - static const int eof = std::char_traits<char>::eof(); - - int c = istr.get(); - while (c != eof && Poco::Ascii::isSpace(c)) c = istr.get(); - if (c != eof) - { - if (c == ';') - { - while (c != eof && c != '\n') c = istr.get(); - } - else if (c == '[') - { - std::string key; - c = istr.get(); - while (c != eof && c != ']' && c != '\n') { key += (char) c; c = istr.get(); } - _sectionKey = trim(key); - } - else - { - std::string key; - while (c != eof && c != '=' && c != '\n') { key += (char) c; c = istr.get(); } - std::string value; - if (c == '=') - { - c = istr.get(); - while (c != eof && c != '\n') { value += (char) c; c = istr.get(); } - } - std::string fullKey = _sectionKey; - if (!fullKey.empty()) fullKey += '.'; - fullKey.append(trim(key)); - _map[fullKey] = trim(value); - } - } -} - - -} } // namespace Poco::Util - - -#endif // POCO_UTIL_NO_INIFILECONFIGURATION
\ No newline at end of file +// +// IniFileConfiguration.cpp +// +// Library: Util +// Package: Configuration +// Module: IniFileConfiguration +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#include "Poco/Util/IniFileConfiguration.h" + + +#ifndef POCO_UTIL_NO_INIFILECONFIGURATION + + +#include "Poco/Exception.h" +#include "Poco/String.h" +#include "Poco/Path.h" +#include "Poco/FileStream.h" +#include "Poco/Ascii.h" +#include <set> + + +using Poco::icompare; +using Poco::trim; +using Poco::Path; + + +namespace Poco { +namespace Util { + + +IniFileConfiguration::IniFileConfiguration() +{ +} + + +IniFileConfiguration::IniFileConfiguration(std::istream& istr) +{ + load(istr); +} + + +IniFileConfiguration::IniFileConfiguration(const std::string& path) +{ + load(path); +} + + +IniFileConfiguration::~IniFileConfiguration() +{ +} + + +void IniFileConfiguration::load(std::istream& istr) +{ + _map.clear(); + _sectionKey.clear(); + while (!istr.eof()) + { + parseLine(istr); + } +} + + +void IniFileConfiguration::load(const std::string& path) +{ + Poco::FileInputStream istr(path); + if (istr.good()) + load(istr); + else + throw Poco::OpenFileException(path); +} + + +bool IniFileConfiguration::getRaw(const std::string& key, std::string& value) const +{ + IStringMap::const_iterator it = _map.find(key); + if (it != _map.end()) + { + value = it->second; + return true; + } + else return false; +} + + +void IniFileConfiguration::setRaw(const std::string& key, const std::string& value) +{ + _map[key] = value; +} + + +void IniFileConfiguration::enumerate(const std::string& key, Keys& range) const +{ + std::set<std::string> keys; + std::string prefix = key; + if (!prefix.empty()) prefix += '.'; + std::string::size_type psize = prefix.size(); + for (IStringMap::const_iterator it = _map.begin(); it != _map.end(); ++it) + { + if (icompare(it->first, psize, prefix) == 0) + { + std::string subKey; + std::string::size_type end = it->first.find('.', psize); + if (end == std::string::npos) + subKey = it->first.substr(psize); + else + subKey = it->first.substr(psize, end - psize); + if (keys.find(subKey) == keys.end()) + { + range.push_back(subKey); + keys.insert(subKey); + } + } + } +} + + +void IniFileConfiguration::removeRaw(const std::string& key) +{ + std::string prefix = key; + if (!prefix.empty()) prefix += '.'; + std::string::size_type psize = prefix.size(); + IStringMap::iterator it = _map.begin(); + IStringMap::iterator itCur; + while (it != _map.end()) + { + itCur = it++; + if ((icompare(itCur->first, key) == 0) || (icompare(itCur->first, psize, prefix) == 0)) + { + _map.erase(itCur); + } + } +} + + +bool IniFileConfiguration::ICompare::operator () (const std::string& s1, const std::string& s2) const +{ + return icompare(s1, s2) < 0; +} + + +void IniFileConfiguration::parseLine(std::istream& istr) +{ + static const int eof = std::char_traits<char>::eof(); + + int c = istr.get(); + while (c != eof && Poco::Ascii::isSpace(c)) c = istr.get(); + if (c != eof) + { + if (c == ';') + { + while (c != eof && c != '\n') c = istr.get(); + } + else if (c == '[') + { + std::string key; + c = istr.get(); + while (c != eof && c != ']' && c != '\n') { key += (char) c; c = istr.get(); } + _sectionKey = trim(key); + } + else + { + std::string key; + while (c != eof && c != '=' && c != '\n') { key += (char) c; c = istr.get(); } + std::string value; + if (c == '=') + { + c = istr.get(); + while (c != eof && c != '\n') { value += (char) c; c = istr.get(); } + } + std::string fullKey = _sectionKey; + if (!fullKey.empty()) fullKey += '.'; + fullKey.append(trim(key)); + _map[fullKey] = trim(value); + } + } +} + + +} } // namespace Poco::Util + + +#endif // POCO_UTIL_NO_INIFILECONFIGURATION
\ No newline at end of file diff --git a/contrib/libs/poco/Util/src/IntValidator.cpp b/contrib/libs/poco/Util/src/IntValidator.cpp index 347fde30b8..e5372ee098 100644 --- a/contrib/libs/poco/Util/src/IntValidator.cpp +++ b/contrib/libs/poco/Util/src/IntValidator.cpp @@ -1,54 +1,54 @@ -// -// IntValidator.cpp -// -// Library: Util -// Package: Options -// Module: IntValidator -// -// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// SPDX-License-Identifier: BSL-1.0 -// - - -#include "Poco/Util/IntValidator.h" -#include "Poco/Util/Option.h" -#include "Poco/Util/OptionException.h" -#include "Poco/NumberParser.h" -#include "Poco/Format.h" - - -using Poco::NumberParser; -using Poco::format; - - -namespace Poco { -namespace Util { - - -IntValidator::IntValidator(int min, int max): - _min(min), - _max(max) -{ -} - - -IntValidator::~IntValidator() -{ -} - - -void IntValidator::validate(const Option& option, const std::string& value) -{ - int n; - if (NumberParser::tryParse(value, n)) - { - if (n < _min || n > _max) - throw InvalidArgumentException(format("argument for %s must be in range %d to %d", option.fullName(), _min, _max)); - } - else throw InvalidArgumentException(format("argument for %s must be an integer", option.fullName())); -} - - -} } // namespace Poco::Util +// +// IntValidator.cpp +// +// Library: Util +// Package: Options +// Module: IntValidator +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#include "Poco/Util/IntValidator.h" +#include "Poco/Util/Option.h" +#include "Poco/Util/OptionException.h" +#include "Poco/NumberParser.h" +#include "Poco/Format.h" + + +using Poco::NumberParser; +using Poco::format; + + +namespace Poco { +namespace Util { + + +IntValidator::IntValidator(int min, int max): + _min(min), + _max(max) +{ +} + + +IntValidator::~IntValidator() +{ +} + + +void IntValidator::validate(const Option& option, const std::string& value) +{ + int n; + if (NumberParser::tryParse(value, n)) + { + if (n < _min || n > _max) + throw InvalidArgumentException(format("argument for %s must be in range %d to %d", option.fullName(), _min, _max)); + } + else throw InvalidArgumentException(format("argument for %s must be an integer", option.fullName())); +} + + +} } // namespace Poco::Util diff --git a/contrib/libs/poco/Util/src/JSONConfiguration.cpp b/contrib/libs/poco/Util/src/JSONConfiguration.cpp index f992a61cfb..282ac8ce5e 100644 --- a/contrib/libs/poco/Util/src/JSONConfiguration.cpp +++ b/contrib/libs/poco/Util/src/JSONConfiguration.cpp @@ -1,386 +1,386 @@ -// -// JSONConfiguration.cpp -// -// Library: Util -// Package: JSON -// Module: JSONConfiguration -// -// Copyright (c) 2012, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// SPDX-License-Identifier: BSL-1.0 -// - - - -#include "Poco/Util/JSONConfiguration.h" - - -#ifndef POCO_UTIL_NO_JSONCONFIGURATION - - -#include "Poco/FileStream.h" -#include "Poco/StringTokenizer.h" -#include "Poco/JSON/Parser.h" -#include "Poco/JSON/Query.h" -#include "Poco/RegularExpression.h" -#include "Poco/NumberParser.h" - - -namespace Poco { -namespace Util { - - -JSONConfiguration::JSONConfiguration() : _object(new JSON::Object()) -{ -} - - -JSONConfiguration::JSONConfiguration(const std::string& path) -{ - load(path); -} - - -JSONConfiguration::JSONConfiguration(std::istream& istr) -{ - load(istr); -} - - -JSONConfiguration::JSONConfiguration(const JSON::Object::Ptr& object) : _object(object) -{ -} - - -JSONConfiguration::~JSONConfiguration() -{ -} - - -void JSONConfiguration::load(const std::string& path) -{ - Poco::FileInputStream fis(path); - load(fis); -} - - -void JSONConfiguration::load(std::istream& istr) -{ - JSON::Parser parser; - parser.parse(istr); - DynamicAny result = parser.result(); - if ( result.type() == typeid(JSON::Object::Ptr) ) - { - _object = result.extract<JSON::Object::Ptr>(); - } -} - - -void JSONConfiguration::loadEmpty(const std::string& root) -{ - _object = new JSON::Object(); - JSON::Object::Ptr rootObject = new JSON::Object(); - _object->set(root, rootObject); -} - - -bool JSONConfiguration::getRaw(const std::string & key, std::string & value) const -{ - JSON::Query query(_object); - Poco::DynamicAny result = query.find(key); - if ( ! result.isEmpty() ) - { - value = result.convert<std::string>(); - return true; - } - return false; -} - - -void JSONConfiguration::getIndexes(std::string& name, std::vector<int>& indexes) -{ - indexes.clear(); - - RegularExpression::MatchVec matches; - int firstOffset = -1; - int offset = 0; - RegularExpression regex("\\[([0-9]+)\\]"); - while(regex.match(name, offset, matches) > 0 ) - { - if ( firstOffset == -1 ) - { - firstOffset = static_cast<int>(matches[0].offset); - } - std::string num = name.substr(matches[1].offset, matches[1].length); - indexes.push_back(NumberParser::parse(num)); - offset = static_cast<int>(matches[0].offset + matches[0].length); - } - - if ( firstOffset != -1 ) - { - name = name.substr(0, firstOffset); - } -} - - -JSON::Object::Ptr JSONConfiguration::findStart(const std::string& key, std::string& lastPart) -{ - JSON::Object::Ptr currentObject = _object; - - StringTokenizer tokenizer(key, "."); - lastPart = tokenizer[tokenizer.count() - 1]; - - for(int i = 0; i < tokenizer.count() - 1; ++i) - { - std::vector<int> indexes; - std::string name = tokenizer[i]; - getIndexes(name, indexes); - - DynamicAny result = currentObject->get(name); - - if ( result.isEmpty() ) // Not found - { - if ( indexes.empty() ) // We want an object, create it - { - JSON::Object::Ptr newObject = new JSON::Object(); - currentObject->set(name, newObject); - currentObject = newObject; - } - else // We need an array - { - JSON::Array::Ptr newArray; - JSON::Array::Ptr parentArray; - JSON::Array::Ptr topArray; - for(std::vector<int>::iterator it = indexes.begin(); it != indexes.end(); ++it) - { - newArray = new JSON::Array(); - if ( topArray.isNull() ) - { - topArray = newArray; - } - - if ( ! parentArray.isNull() ) - { - parentArray->add(newArray); - } - - for(int i = 0; i <= *it - 1; ++i) - { - Poco::DynamicAny nullValue; - newArray->add(nullValue); - } - - parentArray = newArray; - } - - currentObject->set(name, topArray); - currentObject = new JSON::Object(); - newArray->add(currentObject); - } - } - else // We have a value - { - if ( indexes.empty() ) // We want an object - { - if ( result.type() == typeid(JSON::Object::Ptr) ) - { - currentObject = result.extract<JSON::Object::Ptr>(); - } - else - { - throw SyntaxException("Expected a JSON object"); - } - } - else - { - if ( result.type() == typeid(JSON::Array::Ptr) ) - { - JSON::Array::Ptr arr = result.extract<JSON::Array::Ptr>(); - - for(std::vector<int>::iterator it = indexes.begin(); it != indexes.end() - 1; ++it) - { - JSON::Array::Ptr currentArray = arr; - arr = arr->getArray(*it); - if ( arr.isNull() ) - { - arr = new JSON::Array(); - currentArray->add(arr); - } - } - - result = arr->get(*indexes.rbegin()); - if ( result.isEmpty() ) // Index doesn't exist - { - JSON::Object::Ptr newObject = new JSON::Object(); - arr->add(newObject); - currentObject = newObject; - } - else // Index is available - { - if ( result.type() == typeid(JSON::Object::Ptr) ) - { - currentObject = result.extract<JSON::Object::Ptr>(); - } - else - { - throw SyntaxException("Expected a JSON object"); - } - } - } - else - { - throw SyntaxException("Expected a JSON array"); - } - } - } - } - return currentObject; -} - - -void JSONConfiguration::setValue(const std::string& key, const Poco::DynamicAny& value) -{ - - std::string sValue; - - value.convert<std::string>(sValue); - KeyValue kv(key, sValue); - - if (eventsEnabled()) - { - propertyChanging(this, kv); - } - - std::string lastPart; - JSON::Object::Ptr parentObject = findStart(key, lastPart); - - std::vector<int> indexes; - getIndexes(lastPart, indexes); - - if ( indexes.empty() ) // No Array - { - parentObject->set(lastPart, value); - } - else - { - DynamicAny result = parentObject->get(lastPart); - if ( result.isEmpty() ) - { - result = JSON::Array::Ptr(new JSON::Array()); - parentObject->set(lastPart, result); - } - else if ( result.type() != typeid(JSON::Array::Ptr) ) - { - throw SyntaxException("Expected a JSON array"); - } - - JSON::Array::Ptr arr = result.extract<JSON::Array::Ptr>(); - for(std::vector<int>::iterator it = indexes.begin(); it != indexes.end() - 1; ++it) - { - JSON::Array::Ptr nextArray = arr->getArray(*it); - if ( nextArray.isNull() ) - { - for(int i = static_cast<int>(arr->size()); i <= *it; ++i) - { - Poco::DynamicAny nullValue; - arr->add(nullValue); - } - nextArray = new JSON::Array(); - arr->add(nextArray); - } - arr = nextArray; - } - arr->set(indexes.back(), value); - } - - if (eventsEnabled()) - { - propertyChanged(this, kv); - } -} - - -void JSONConfiguration::setString(const std::string& key, const std::string& value) -{ - setValue(key, value); -} - - -void JSONConfiguration::setRaw(const std::string& key, const std::string& value) -{ - setValue(key, value); -} - - -void JSONConfiguration::setInt(const std::string& key, int value) -{ - setValue(key, value); -} - - -void JSONConfiguration::setBool(const std::string& key, bool value) -{ - setValue(key, value); -} - - -void JSONConfiguration::setDouble(const std::string& key, double value) -{ - setValue(key, value); -} - - -void JSONConfiguration::enumerate(const std::string& key, Keys& range) const -{ - JSON::Query query(_object); - Poco::DynamicAny result = query.find(key); - if ( result.type() == typeid(JSON::Object::Ptr) ) - { - JSON::Object::Ptr object = result.extract<JSON::Object::Ptr>(); - object->getNames(range); - } -} - - -void JSONConfiguration::save(std::ostream& ostr, unsigned int indent) const -{ - _object->stringify(ostr, indent); -} - - -void JSONConfiguration::removeRaw(const std::string& key) - -{ - - std::string lastPart; - JSON::Object::Ptr parentObject = findStart(key, lastPart); - std::vector<int> indexes; - getIndexes(lastPart, indexes); - - if ( indexes.empty() ) // No Array - { - parentObject->remove(lastPart); - } - else - { - DynamicAny result = parentObject->get(lastPart); - if (!result.isEmpty() && result.type() == typeid(JSON::Array::Ptr)) - { - - JSON::Array::Ptr arr = result.extract<JSON::Array::Ptr>(); - for(std::vector<int>::iterator it = indexes.begin(); it != indexes.end() - 1; ++it) - { - arr = arr->getArray(*it); - } - arr->remove(indexes.back()); - } - } - -} - - -} } // namespace Poco::Util - - -#endif // POCO_UTIL_NO_JSONCONFIGURATION +// +// JSONConfiguration.cpp +// +// Library: Util +// Package: JSON +// Module: JSONConfiguration +// +// Copyright (c) 2012, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + + +#include "Poco/Util/JSONConfiguration.h" + + +#ifndef POCO_UTIL_NO_JSONCONFIGURATION + + +#include "Poco/FileStream.h" +#include "Poco/StringTokenizer.h" +#include "Poco/JSON/Parser.h" +#include "Poco/JSON/Query.h" +#include "Poco/RegularExpression.h" +#include "Poco/NumberParser.h" + + +namespace Poco { +namespace Util { + + +JSONConfiguration::JSONConfiguration() : _object(new JSON::Object()) +{ +} + + +JSONConfiguration::JSONConfiguration(const std::string& path) +{ + load(path); +} + + +JSONConfiguration::JSONConfiguration(std::istream& istr) +{ + load(istr); +} + + +JSONConfiguration::JSONConfiguration(const JSON::Object::Ptr& object) : _object(object) +{ +} + + +JSONConfiguration::~JSONConfiguration() +{ +} + + +void JSONConfiguration::load(const std::string& path) +{ + Poco::FileInputStream fis(path); + load(fis); +} + + +void JSONConfiguration::load(std::istream& istr) +{ + JSON::Parser parser; + parser.parse(istr); + DynamicAny result = parser.result(); + if ( result.type() == typeid(JSON::Object::Ptr) ) + { + _object = result.extract<JSON::Object::Ptr>(); + } +} + + +void JSONConfiguration::loadEmpty(const std::string& root) +{ + _object = new JSON::Object(); + JSON::Object::Ptr rootObject = new JSON::Object(); + _object->set(root, rootObject); +} + + +bool JSONConfiguration::getRaw(const std::string & key, std::string & value) const +{ + JSON::Query query(_object); + Poco::DynamicAny result = query.find(key); + if ( ! result.isEmpty() ) + { + value = result.convert<std::string>(); + return true; + } + return false; +} + + +void JSONConfiguration::getIndexes(std::string& name, std::vector<int>& indexes) +{ + indexes.clear(); + + RegularExpression::MatchVec matches; + int firstOffset = -1; + int offset = 0; + RegularExpression regex("\\[([0-9]+)\\]"); + while(regex.match(name, offset, matches) > 0 ) + { + if ( firstOffset == -1 ) + { + firstOffset = static_cast<int>(matches[0].offset); + } + std::string num = name.substr(matches[1].offset, matches[1].length); + indexes.push_back(NumberParser::parse(num)); + offset = static_cast<int>(matches[0].offset + matches[0].length); + } + + if ( firstOffset != -1 ) + { + name = name.substr(0, firstOffset); + } +} + + +JSON::Object::Ptr JSONConfiguration::findStart(const std::string& key, std::string& lastPart) +{ + JSON::Object::Ptr currentObject = _object; + + StringTokenizer tokenizer(key, "."); + lastPart = tokenizer[tokenizer.count() - 1]; + + for(int i = 0; i < tokenizer.count() - 1; ++i) + { + std::vector<int> indexes; + std::string name = tokenizer[i]; + getIndexes(name, indexes); + + DynamicAny result = currentObject->get(name); + + if ( result.isEmpty() ) // Not found + { + if ( indexes.empty() ) // We want an object, create it + { + JSON::Object::Ptr newObject = new JSON::Object(); + currentObject->set(name, newObject); + currentObject = newObject; + } + else // We need an array + { + JSON::Array::Ptr newArray; + JSON::Array::Ptr parentArray; + JSON::Array::Ptr topArray; + for(std::vector<int>::iterator it = indexes.begin(); it != indexes.end(); ++it) + { + newArray = new JSON::Array(); + if ( topArray.isNull() ) + { + topArray = newArray; + } + + if ( ! parentArray.isNull() ) + { + parentArray->add(newArray); + } + + for(int i = 0; i <= *it - 1; ++i) + { + Poco::DynamicAny nullValue; + newArray->add(nullValue); + } + + parentArray = newArray; + } + + currentObject->set(name, topArray); + currentObject = new JSON::Object(); + newArray->add(currentObject); + } + } + else // We have a value + { + if ( indexes.empty() ) // We want an object + { + if ( result.type() == typeid(JSON::Object::Ptr) ) + { + currentObject = result.extract<JSON::Object::Ptr>(); + } + else + { + throw SyntaxException("Expected a JSON object"); + } + } + else + { + if ( result.type() == typeid(JSON::Array::Ptr) ) + { + JSON::Array::Ptr arr = result.extract<JSON::Array::Ptr>(); + + for(std::vector<int>::iterator it = indexes.begin(); it != indexes.end() - 1; ++it) + { + JSON::Array::Ptr currentArray = arr; + arr = arr->getArray(*it); + if ( arr.isNull() ) + { + arr = new JSON::Array(); + currentArray->add(arr); + } + } + + result = arr->get(*indexes.rbegin()); + if ( result.isEmpty() ) // Index doesn't exist + { + JSON::Object::Ptr newObject = new JSON::Object(); + arr->add(newObject); + currentObject = newObject; + } + else // Index is available + { + if ( result.type() == typeid(JSON::Object::Ptr) ) + { + currentObject = result.extract<JSON::Object::Ptr>(); + } + else + { + throw SyntaxException("Expected a JSON object"); + } + } + } + else + { + throw SyntaxException("Expected a JSON array"); + } + } + } + } + return currentObject; +} + + +void JSONConfiguration::setValue(const std::string& key, const Poco::DynamicAny& value) +{ + + std::string sValue; + + value.convert<std::string>(sValue); + KeyValue kv(key, sValue); + + if (eventsEnabled()) + { + propertyChanging(this, kv); + } + + std::string lastPart; + JSON::Object::Ptr parentObject = findStart(key, lastPart); + + std::vector<int> indexes; + getIndexes(lastPart, indexes); + + if ( indexes.empty() ) // No Array + { + parentObject->set(lastPart, value); + } + else + { + DynamicAny result = parentObject->get(lastPart); + if ( result.isEmpty() ) + { + result = JSON::Array::Ptr(new JSON::Array()); + parentObject->set(lastPart, result); + } + else if ( result.type() != typeid(JSON::Array::Ptr) ) + { + throw SyntaxException("Expected a JSON array"); + } + + JSON::Array::Ptr arr = result.extract<JSON::Array::Ptr>(); + for(std::vector<int>::iterator it = indexes.begin(); it != indexes.end() - 1; ++it) + { + JSON::Array::Ptr nextArray = arr->getArray(*it); + if ( nextArray.isNull() ) + { + for(int i = static_cast<int>(arr->size()); i <= *it; ++i) + { + Poco::DynamicAny nullValue; + arr->add(nullValue); + } + nextArray = new JSON::Array(); + arr->add(nextArray); + } + arr = nextArray; + } + arr->set(indexes.back(), value); + } + + if (eventsEnabled()) + { + propertyChanged(this, kv); + } +} + + +void JSONConfiguration::setString(const std::string& key, const std::string& value) +{ + setValue(key, value); +} + + +void JSONConfiguration::setRaw(const std::string& key, const std::string& value) +{ + setValue(key, value); +} + + +void JSONConfiguration::setInt(const std::string& key, int value) +{ + setValue(key, value); +} + + +void JSONConfiguration::setBool(const std::string& key, bool value) +{ + setValue(key, value); +} + + +void JSONConfiguration::setDouble(const std::string& key, double value) +{ + setValue(key, value); +} + + +void JSONConfiguration::enumerate(const std::string& key, Keys& range) const +{ + JSON::Query query(_object); + Poco::DynamicAny result = query.find(key); + if ( result.type() == typeid(JSON::Object::Ptr) ) + { + JSON::Object::Ptr object = result.extract<JSON::Object::Ptr>(); + object->getNames(range); + } +} + + +void JSONConfiguration::save(std::ostream& ostr, unsigned int indent) const +{ + _object->stringify(ostr, indent); +} + + +void JSONConfiguration::removeRaw(const std::string& key) + +{ + + std::string lastPart; + JSON::Object::Ptr parentObject = findStart(key, lastPart); + std::vector<int> indexes; + getIndexes(lastPart, indexes); + + if ( indexes.empty() ) // No Array + { + parentObject->remove(lastPart); + } + else + { + DynamicAny result = parentObject->get(lastPart); + if (!result.isEmpty() && result.type() == typeid(JSON::Array::Ptr)) + { + + JSON::Array::Ptr arr = result.extract<JSON::Array::Ptr>(); + for(std::vector<int>::iterator it = indexes.begin(); it != indexes.end() - 1; ++it) + { + arr = arr->getArray(*it); + } + arr->remove(indexes.back()); + } + } + +} + + +} } // namespace Poco::Util + + +#endif // POCO_UTIL_NO_JSONCONFIGURATION diff --git a/contrib/libs/poco/Util/src/LayeredConfiguration.cpp b/contrib/libs/poco/Util/src/LayeredConfiguration.cpp index c4cba6322e..1cbd5d7847 100644 --- a/contrib/libs/poco/Util/src/LayeredConfiguration.cpp +++ b/contrib/libs/poco/Util/src/LayeredConfiguration.cpp @@ -1,233 +1,233 @@ -// -// LayeredConfiguration.cpp -// -// Library: Util -// Package: Configuration -// Module: LayeredConfiguration -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// SPDX-License-Identifier: BSL-1.0 -// - - -#include "Poco/Util/LayeredConfiguration.h" -#include "Poco/Exception.h" -#include <set> - - -using Poco::AutoPtr; -using Poco::RuntimeException; - - -namespace Poco { -namespace Util { - - -LayeredConfiguration::LayeredConfiguration() -{ -} - - -LayeredConfiguration::~LayeredConfiguration() -{ -} - - -void LayeredConfiguration::add(AbstractConfiguration* pConfig) -{ - add(pConfig, highest(), false, true); -} - - -void LayeredConfiguration::add(AbstractConfiguration* pConfig, const std::string& label) -{ - add(pConfig, label, highest(), false, true); -} - - -void LayeredConfiguration::add(AbstractConfiguration* pConfig, bool shared) -{ - add(pConfig, highest(), false, shared); -} - - -void LayeredConfiguration::add(AbstractConfiguration* pConfig, const std::string& label, bool shared) -{ - add(pConfig, label, highest(), false, shared); -} - - -void LayeredConfiguration::add(AbstractConfiguration* pConfig, int priority) -{ - add(pConfig, priority, false, true); -} - - -void LayeredConfiguration::add(AbstractConfiguration* pConfig, const std::string& label, int priority) -{ - add(pConfig, label, priority, false, true); -} - - -void LayeredConfiguration::add(AbstractConfiguration* pConfig, int priority, bool shared) -{ - add(pConfig, priority, false, shared); -} - - -void LayeredConfiguration::add(AbstractConfiguration* pConfig, const std::string& label, int priority, bool shared) -{ - add(pConfig, label, priority, false, shared); -} - - -void LayeredConfiguration::addFront(AbstractConfiguration* pConfig) -{ - add(pConfig, lowest(), false, true); -} - - -void LayeredConfiguration::addFront(AbstractConfiguration* pConfig, bool shared) -{ - add(pConfig, lowest(), false, shared); -} - - -void LayeredConfiguration::addWriteable(AbstractConfiguration* pConfig, int priority) -{ - add(pConfig, priority, true, true); -} - - -void LayeredConfiguration::addWriteable(AbstractConfiguration* pConfig, int priority, bool shared) -{ - add(pConfig, priority, true, shared); -} - - -void LayeredConfiguration::add(AbstractConfiguration* pConfig, int priority, bool writeable, bool shared) -{ - add(pConfig, std::string(), priority, writeable, shared); -} - - -void LayeredConfiguration::add(AbstractConfiguration* pConfig, const std::string& label, int priority, bool writeable, bool shared) -{ - ConfigItem item; - item.pConfig = ConfigPtr(pConfig, shared); - item.priority = priority; - item.writeable = writeable; - item.label = label; - - ConfigList::iterator it = _configs.begin(); - while (it != _configs.end() && it->priority < priority) - ++it; - - _configs.insert(it, item); -} - - -void LayeredConfiguration::removeConfiguration(AbstractConfiguration* pConfig) -{ - for (ConfigList::iterator it = _configs.begin(); it != _configs.end(); ++it) - { - if (it->pConfig == pConfig) - { - _configs.erase(it); - break; - } - } -} - - -LayeredConfiguration::ConfigPtr LayeredConfiguration::find(const std::string& label) const -{ - for (ConfigList::const_iterator it = _configs.begin(); it != _configs.end(); ++it) - { - if (it->label == label) - { - return it->pConfig; - } - } - return 0; -} - - -bool LayeredConfiguration::getRaw(const std::string& key, std::string& value) const -{ - for (ConfigList::const_iterator it = _configs.begin(); it != _configs.end(); ++it) - { - if (it->pConfig->getRaw(key, value)) - return true; - } - return false; -} - - -void LayeredConfiguration::setRaw(const std::string& key, const std::string& value) -{ - for (ConfigList::iterator it = _configs.begin(); it != _configs.end(); ++it) - { - if (it->writeable) - { - it->pConfig->setRaw(key, value); - return; - } - } - throw RuntimeException("No writeable configuration object to store the property", key); -} - - -void LayeredConfiguration::enumerate(const std::string& key, Keys& range) const -{ - std::set<std::string> keys; - for (ConfigList::const_iterator itc = _configs.begin(); itc != _configs.end(); ++itc) - { - Keys partRange; - itc->pConfig->enumerate(key, partRange); - for (Keys::const_iterator itr = partRange.begin(); itr != partRange.end(); ++itr) - { - if (keys.find(*itr) == keys.end()) - { - range.push_back(*itr); - keys.insert(*itr); - } - } - } -} - - -void LayeredConfiguration::removeRaw(const std::string& key) -{ - for (ConfigList::iterator it = _configs.begin(); it != _configs.end(); ++it) - { - if (it->writeable) - { - it->pConfig->remove(key); - return; - } - } -} - - -int LayeredConfiguration::lowest() const -{ - if (_configs.empty()) - return 0; - else - return _configs.front().priority - 1; -} - - -int LayeredConfiguration::highest() const -{ - if (_configs.empty()) - return 0; - else - return _configs.back().priority + 1; -} - - -} } // namespace Poco::Util +// +// LayeredConfiguration.cpp +// +// Library: Util +// Package: Configuration +// Module: LayeredConfiguration +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#include "Poco/Util/LayeredConfiguration.h" +#include "Poco/Exception.h" +#include <set> + + +using Poco::AutoPtr; +using Poco::RuntimeException; + + +namespace Poco { +namespace Util { + + +LayeredConfiguration::LayeredConfiguration() +{ +} + + +LayeredConfiguration::~LayeredConfiguration() +{ +} + + +void LayeredConfiguration::add(AbstractConfiguration* pConfig) +{ + add(pConfig, highest(), false, true); +} + + +void LayeredConfiguration::add(AbstractConfiguration* pConfig, const std::string& label) +{ + add(pConfig, label, highest(), false, true); +} + + +void LayeredConfiguration::add(AbstractConfiguration* pConfig, bool shared) +{ + add(pConfig, highest(), false, shared); +} + + +void LayeredConfiguration::add(AbstractConfiguration* pConfig, const std::string& label, bool shared) +{ + add(pConfig, label, highest(), false, shared); +} + + +void LayeredConfiguration::add(AbstractConfiguration* pConfig, int priority) +{ + add(pConfig, priority, false, true); +} + + +void LayeredConfiguration::add(AbstractConfiguration* pConfig, const std::string& label, int priority) +{ + add(pConfig, label, priority, false, true); +} + + +void LayeredConfiguration::add(AbstractConfiguration* pConfig, int priority, bool shared) +{ + add(pConfig, priority, false, shared); +} + + +void LayeredConfiguration::add(AbstractConfiguration* pConfig, const std::string& label, int priority, bool shared) +{ + add(pConfig, label, priority, false, shared); +} + + +void LayeredConfiguration::addFront(AbstractConfiguration* pConfig) +{ + add(pConfig, lowest(), false, true); +} + + +void LayeredConfiguration::addFront(AbstractConfiguration* pConfig, bool shared) +{ + add(pConfig, lowest(), false, shared); +} + + +void LayeredConfiguration::addWriteable(AbstractConfiguration* pConfig, int priority) +{ + add(pConfig, priority, true, true); +} + + +void LayeredConfiguration::addWriteable(AbstractConfiguration* pConfig, int priority, bool shared) +{ + add(pConfig, priority, true, shared); +} + + +void LayeredConfiguration::add(AbstractConfiguration* pConfig, int priority, bool writeable, bool shared) +{ + add(pConfig, std::string(), priority, writeable, shared); +} + + +void LayeredConfiguration::add(AbstractConfiguration* pConfig, const std::string& label, int priority, bool writeable, bool shared) +{ + ConfigItem item; + item.pConfig = ConfigPtr(pConfig, shared); + item.priority = priority; + item.writeable = writeable; + item.label = label; + + ConfigList::iterator it = _configs.begin(); + while (it != _configs.end() && it->priority < priority) + ++it; + + _configs.insert(it, item); +} + + +void LayeredConfiguration::removeConfiguration(AbstractConfiguration* pConfig) +{ + for (ConfigList::iterator it = _configs.begin(); it != _configs.end(); ++it) + { + if (it->pConfig == pConfig) + { + _configs.erase(it); + break; + } + } +} + + +LayeredConfiguration::ConfigPtr LayeredConfiguration::find(const std::string& label) const +{ + for (ConfigList::const_iterator it = _configs.begin(); it != _configs.end(); ++it) + { + if (it->label == label) + { + return it->pConfig; + } + } + return 0; +} + + +bool LayeredConfiguration::getRaw(const std::string& key, std::string& value) const +{ + for (ConfigList::const_iterator it = _configs.begin(); it != _configs.end(); ++it) + { + if (it->pConfig->getRaw(key, value)) + return true; + } + return false; +} + + +void LayeredConfiguration::setRaw(const std::string& key, const std::string& value) +{ + for (ConfigList::iterator it = _configs.begin(); it != _configs.end(); ++it) + { + if (it->writeable) + { + it->pConfig->setRaw(key, value); + return; + } + } + throw RuntimeException("No writeable configuration object to store the property", key); +} + + +void LayeredConfiguration::enumerate(const std::string& key, Keys& range) const +{ + std::set<std::string> keys; + for (ConfigList::const_iterator itc = _configs.begin(); itc != _configs.end(); ++itc) + { + Keys partRange; + itc->pConfig->enumerate(key, partRange); + for (Keys::const_iterator itr = partRange.begin(); itr != partRange.end(); ++itr) + { + if (keys.find(*itr) == keys.end()) + { + range.push_back(*itr); + keys.insert(*itr); + } + } + } +} + + +void LayeredConfiguration::removeRaw(const std::string& key) +{ + for (ConfigList::iterator it = _configs.begin(); it != _configs.end(); ++it) + { + if (it->writeable) + { + it->pConfig->remove(key); + return; + } + } +} + + +int LayeredConfiguration::lowest() const +{ + if (_configs.empty()) + return 0; + else + return _configs.front().priority - 1; +} + + +int LayeredConfiguration::highest() const +{ + if (_configs.empty()) + return 0; + else + return _configs.back().priority + 1; +} + + +} } // namespace Poco::Util diff --git a/contrib/libs/poco/Util/src/LoggingConfigurator.cpp b/contrib/libs/poco/Util/src/LoggingConfigurator.cpp index a7da0f8687..82b9d7d331 100644 --- a/contrib/libs/poco/Util/src/LoggingConfigurator.cpp +++ b/contrib/libs/poco/Util/src/LoggingConfigurator.cpp @@ -1,203 +1,203 @@ -// -// LoggingConfigurator.cpp -// -// Library: Util -// Package: Configuration -// Module: LoggingConfigurator -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// SPDX-License-Identifier: BSL-1.0 -// - - -#include "Poco/Util/LoggingConfigurator.h" -#include "Poco/Util/AbstractConfiguration.h" -#include "Poco/AutoPtr.h" -#include "Poco/Channel.h" -#include "Poco/FormattingChannel.h" -#include "Poco/Formatter.h" -#include "Poco/PatternFormatter.h" -#include "Poco/Logger.h" -#include "Poco/LoggingRegistry.h" -#include "Poco/LoggingFactory.h" -#include <map> - - -using Poco::AutoPtr; -using Poco::Formatter; -using Poco::PatternFormatter; -using Poco::Channel; -using Poco::FormattingChannel; -using Poco::Logger; -using Poco::LoggingRegistry; -using Poco::LoggingFactory; - - -namespace Poco { -namespace Util { - - -LoggingConfigurator::LoggingConfigurator() -{ -} - - -LoggingConfigurator::~LoggingConfigurator() -{ -} - - -void LoggingConfigurator::configure(AbstractConfiguration* pConfig) -{ - poco_check_ptr (pConfig); - - AutoPtr<AbstractConfiguration> pFormattersConfig(pConfig->createView("logging.formatters")); - configureFormatters(pFormattersConfig); - - AutoPtr<AbstractConfiguration> pChannelsConfig(pConfig->createView("logging.channels")); - configureChannels(pChannelsConfig); - - AutoPtr<AbstractConfiguration> pLoggersConfig(pConfig->createView("logging.loggers")); - configureLoggers(pLoggersConfig); -} - - -void LoggingConfigurator::configureFormatters(AbstractConfiguration* pConfig) -{ - AbstractConfiguration::Keys formatters; - pConfig->keys(formatters); - for (AbstractConfiguration::Keys::const_iterator it = formatters.begin(); it != formatters.end(); ++it) - { - AutoPtr<AbstractConfiguration> pFormatterConfig(pConfig->createView(*it)); - AutoPtr<Formatter> pFormatter(createFormatter(pFormatterConfig)); - LoggingRegistry::defaultRegistry().registerFormatter(*it, pFormatter); - } -} - - -void LoggingConfigurator::configureChannels(AbstractConfiguration* pConfig) -{ - AbstractConfiguration::Keys channels; - pConfig->keys(channels); - for (AbstractConfiguration::Keys::const_iterator it = channels.begin(); it != channels.end(); ++it) - { - AutoPtr<AbstractConfiguration> pChannelConfig(pConfig->createView(*it)); - AutoPtr<Channel> pChannel = createChannel(pChannelConfig); - LoggingRegistry::defaultRegistry().registerChannel(*it, pChannel); - } - for (AbstractConfiguration::Keys::const_iterator it = channels.begin(); it != channels.end(); ++it) - { - AutoPtr<AbstractConfiguration> pChannelConfig(pConfig->createView(*it)); - Channel* pChannel = LoggingRegistry::defaultRegistry().channelForName(*it); - configureChannel(pChannel, pChannelConfig); - } -} - - -void LoggingConfigurator::configureLoggers(AbstractConfiguration* pConfig) -{ - typedef std::map<std::string, AutoPtr<AbstractConfiguration> > LoggerMap; - - AbstractConfiguration::Keys loggers; - pConfig->keys(loggers); - // use a map to sort loggers by their name, ensuring initialization in correct order (parents before children) - LoggerMap loggerMap; - for (AbstractConfiguration::Keys::const_iterator it = loggers.begin(); it != loggers.end(); ++it) - { - AutoPtr<AbstractConfiguration> pLoggerConfig(pConfig->createView(*it)); - loggerMap[pLoggerConfig->getString("name", "")] = pLoggerConfig; - } - for (LoggerMap::iterator it = loggerMap.begin(); it != loggerMap.end(); ++it) - { - configureLogger(it->second); - } -} - - -Formatter* LoggingConfigurator::createFormatter(AbstractConfiguration* pConfig) -{ - AutoPtr<Formatter> pFormatter(LoggingFactory::defaultFactory().createFormatter(pConfig->getString("class"))); - AbstractConfiguration::Keys props; - pConfig->keys(props); - for (AbstractConfiguration::Keys::const_iterator it = props.begin(); it != props.end(); ++it) - { - if (*it != "class") - pFormatter->setProperty(*it, pConfig->getString(*it)); - } - return pFormatter.duplicate(); -} - - -Channel* LoggingConfigurator::createChannel(AbstractConfiguration* pConfig) -{ - AutoPtr<Channel> pChannel(LoggingFactory::defaultFactory().createChannel(pConfig->getString("class"))); - AutoPtr<Channel> pWrapper(pChannel); - AbstractConfiguration::Keys props; - pConfig->keys(props); - for (AbstractConfiguration::Keys::const_iterator it = props.begin(); it != props.end(); ++it) - { - if (*it == "pattern") - { - AutoPtr<Formatter> pPatternFormatter(new PatternFormatter(pConfig->getString(*it))); - pWrapper = new FormattingChannel(pPatternFormatter, pChannel); - } - else if (*it == "formatter") - { - AutoPtr<FormattingChannel> pFormattingChannel(new FormattingChannel(0, pChannel)); - if (pConfig->hasProperty("formatter.class")) - { - AutoPtr<AbstractConfiguration> pFormatterConfig(pConfig->createView(*it)); - AutoPtr<Formatter> pFormatter(createFormatter(pFormatterConfig)); - pFormattingChannel->setFormatter(pFormatter); - } - else pFormattingChannel->setProperty(*it, pConfig->getString(*it)); -#if defined(__GNUC__) && __GNUC__ < 3 - pWrapper = pFormattingChannel.duplicate(); -#else - pWrapper = pFormattingChannel; -#endif - } - } - return pWrapper.duplicate(); -} - - -void LoggingConfigurator::configureChannel(Channel* pChannel, AbstractConfiguration* pConfig) -{ - AbstractConfiguration::Keys props; - pConfig->keys(props); - for (AbstractConfiguration::Keys::const_iterator it = props.begin(); it != props.end(); ++it) - { - if (*it != "pattern" && *it != "formatter" && *it != "class") - { - pChannel->setProperty(*it, pConfig->getString(*it)); - } - } -} - - -void LoggingConfigurator::configureLogger(AbstractConfiguration* pConfig) -{ - Logger& logger = Logger::get(pConfig->getString("name", "")); - AbstractConfiguration::Keys props; - pConfig->keys(props); - for (AbstractConfiguration::Keys::const_iterator it = props.begin(); it != props.end(); ++it) - { - if (*it == "channel" && pConfig->hasProperty("channel.class")) - { - AutoPtr<AbstractConfiguration> pChannelConfig(pConfig->createView(*it)); - AutoPtr<Channel> pChannel(createChannel(pChannelConfig)); - configureChannel(pChannel, pChannelConfig); - Logger::setChannel(logger.name(), pChannel); - } - else if (*it != "name") - { - Logger::setProperty(logger.name(), *it, pConfig->getString(*it)); - } - } -} - - -} } // namespace Poco::Util +// +// LoggingConfigurator.cpp +// +// Library: Util +// Package: Configuration +// Module: LoggingConfigurator +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#include "Poco/Util/LoggingConfigurator.h" +#include "Poco/Util/AbstractConfiguration.h" +#include "Poco/AutoPtr.h" +#include "Poco/Channel.h" +#include "Poco/FormattingChannel.h" +#include "Poco/Formatter.h" +#include "Poco/PatternFormatter.h" +#include "Poco/Logger.h" +#include "Poco/LoggingRegistry.h" +#include "Poco/LoggingFactory.h" +#include <map> + + +using Poco::AutoPtr; +using Poco::Formatter; +using Poco::PatternFormatter; +using Poco::Channel; +using Poco::FormattingChannel; +using Poco::Logger; +using Poco::LoggingRegistry; +using Poco::LoggingFactory; + + +namespace Poco { +namespace Util { + + +LoggingConfigurator::LoggingConfigurator() +{ +} + + +LoggingConfigurator::~LoggingConfigurator() +{ +} + + +void LoggingConfigurator::configure(AbstractConfiguration* pConfig) +{ + poco_check_ptr (pConfig); + + AutoPtr<AbstractConfiguration> pFormattersConfig(pConfig->createView("logging.formatters")); + configureFormatters(pFormattersConfig); + + AutoPtr<AbstractConfiguration> pChannelsConfig(pConfig->createView("logging.channels")); + configureChannels(pChannelsConfig); + + AutoPtr<AbstractConfiguration> pLoggersConfig(pConfig->createView("logging.loggers")); + configureLoggers(pLoggersConfig); +} + + +void LoggingConfigurator::configureFormatters(AbstractConfiguration* pConfig) +{ + AbstractConfiguration::Keys formatters; + pConfig->keys(formatters); + for (AbstractConfiguration::Keys::const_iterator it = formatters.begin(); it != formatters.end(); ++it) + { + AutoPtr<AbstractConfiguration> pFormatterConfig(pConfig->createView(*it)); + AutoPtr<Formatter> pFormatter(createFormatter(pFormatterConfig)); + LoggingRegistry::defaultRegistry().registerFormatter(*it, pFormatter); + } +} + + +void LoggingConfigurator::configureChannels(AbstractConfiguration* pConfig) +{ + AbstractConfiguration::Keys channels; + pConfig->keys(channels); + for (AbstractConfiguration::Keys::const_iterator it = channels.begin(); it != channels.end(); ++it) + { + AutoPtr<AbstractConfiguration> pChannelConfig(pConfig->createView(*it)); + AutoPtr<Channel> pChannel = createChannel(pChannelConfig); + LoggingRegistry::defaultRegistry().registerChannel(*it, pChannel); + } + for (AbstractConfiguration::Keys::const_iterator it = channels.begin(); it != channels.end(); ++it) + { + AutoPtr<AbstractConfiguration> pChannelConfig(pConfig->createView(*it)); + Channel* pChannel = LoggingRegistry::defaultRegistry().channelForName(*it); + configureChannel(pChannel, pChannelConfig); + } +} + + +void LoggingConfigurator::configureLoggers(AbstractConfiguration* pConfig) +{ + typedef std::map<std::string, AutoPtr<AbstractConfiguration> > LoggerMap; + + AbstractConfiguration::Keys loggers; + pConfig->keys(loggers); + // use a map to sort loggers by their name, ensuring initialization in correct order (parents before children) + LoggerMap loggerMap; + for (AbstractConfiguration::Keys::const_iterator it = loggers.begin(); it != loggers.end(); ++it) + { + AutoPtr<AbstractConfiguration> pLoggerConfig(pConfig->createView(*it)); + loggerMap[pLoggerConfig->getString("name", "")] = pLoggerConfig; + } + for (LoggerMap::iterator it = loggerMap.begin(); it != loggerMap.end(); ++it) + { + configureLogger(it->second); + } +} + + +Formatter* LoggingConfigurator::createFormatter(AbstractConfiguration* pConfig) +{ + AutoPtr<Formatter> pFormatter(LoggingFactory::defaultFactory().createFormatter(pConfig->getString("class"))); + AbstractConfiguration::Keys props; + pConfig->keys(props); + for (AbstractConfiguration::Keys::const_iterator it = props.begin(); it != props.end(); ++it) + { + if (*it != "class") + pFormatter->setProperty(*it, pConfig->getString(*it)); + } + return pFormatter.duplicate(); +} + + +Channel* LoggingConfigurator::createChannel(AbstractConfiguration* pConfig) +{ + AutoPtr<Channel> pChannel(LoggingFactory::defaultFactory().createChannel(pConfig->getString("class"))); + AutoPtr<Channel> pWrapper(pChannel); + AbstractConfiguration::Keys props; + pConfig->keys(props); + for (AbstractConfiguration::Keys::const_iterator it = props.begin(); it != props.end(); ++it) + { + if (*it == "pattern") + { + AutoPtr<Formatter> pPatternFormatter(new PatternFormatter(pConfig->getString(*it))); + pWrapper = new FormattingChannel(pPatternFormatter, pChannel); + } + else if (*it == "formatter") + { + AutoPtr<FormattingChannel> pFormattingChannel(new FormattingChannel(0, pChannel)); + if (pConfig->hasProperty("formatter.class")) + { + AutoPtr<AbstractConfiguration> pFormatterConfig(pConfig->createView(*it)); + AutoPtr<Formatter> pFormatter(createFormatter(pFormatterConfig)); + pFormattingChannel->setFormatter(pFormatter); + } + else pFormattingChannel->setProperty(*it, pConfig->getString(*it)); +#if defined(__GNUC__) && __GNUC__ < 3 + pWrapper = pFormattingChannel.duplicate(); +#else + pWrapper = pFormattingChannel; +#endif + } + } + return pWrapper.duplicate(); +} + + +void LoggingConfigurator::configureChannel(Channel* pChannel, AbstractConfiguration* pConfig) +{ + AbstractConfiguration::Keys props; + pConfig->keys(props); + for (AbstractConfiguration::Keys::const_iterator it = props.begin(); it != props.end(); ++it) + { + if (*it != "pattern" && *it != "formatter" && *it != "class") + { + pChannel->setProperty(*it, pConfig->getString(*it)); + } + } +} + + +void LoggingConfigurator::configureLogger(AbstractConfiguration* pConfig) +{ + Logger& logger = Logger::get(pConfig->getString("name", "")); + AbstractConfiguration::Keys props; + pConfig->keys(props); + for (AbstractConfiguration::Keys::const_iterator it = props.begin(); it != props.end(); ++it) + { + if (*it == "channel" && pConfig->hasProperty("channel.class")) + { + AutoPtr<AbstractConfiguration> pChannelConfig(pConfig->createView(*it)); + AutoPtr<Channel> pChannel(createChannel(pChannelConfig)); + configureChannel(pChannel, pChannelConfig); + Logger::setChannel(logger.name(), pChannel); + } + else if (*it != "name") + { + Logger::setProperty(logger.name(), *it, pConfig->getString(*it)); + } + } +} + + +} } // namespace Poco::Util diff --git a/contrib/libs/poco/Util/src/LoggingSubsystem.cpp b/contrib/libs/poco/Util/src/LoggingSubsystem.cpp index c03028ad85..08d51a32e1 100644 --- a/contrib/libs/poco/Util/src/LoggingSubsystem.cpp +++ b/contrib/libs/poco/Util/src/LoggingSubsystem.cpp @@ -1,58 +1,58 @@ -// -// LoggingSubsystem.cpp -// -// Library: Util -// Package: Application -// Module: LoggingSubsystem -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// SPDX-License-Identifier: BSL-1.0 -// - - -#include "Poco/Util/LoggingSubsystem.h" -#include "Poco/Util/LoggingConfigurator.h" -#include "Poco/Util/Application.h" -#include "Poco/Logger.h" - - -using Poco::Logger; - - -namespace Poco { -namespace Util { - - -LoggingSubsystem::LoggingSubsystem() -{ -} - - -LoggingSubsystem::~LoggingSubsystem() -{ -} - - -const char* LoggingSubsystem::name() const -{ - return "Logging Subsystem"; -} - - -void LoggingSubsystem::initialize(Application& app) -{ - LoggingConfigurator configurator; - configurator.configure(&app.config()); - std::string logger = app.config().getString("application.logger", "Application"); - app.setLogger(Logger::get(logger)); -} - - -void LoggingSubsystem::uninitialize() -{ -} - - -} } // namespace Poco::Util +// +// LoggingSubsystem.cpp +// +// Library: Util +// Package: Application +// Module: LoggingSubsystem +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#include "Poco/Util/LoggingSubsystem.h" +#include "Poco/Util/LoggingConfigurator.h" +#include "Poco/Util/Application.h" +#include "Poco/Logger.h" + + +using Poco::Logger; + + +namespace Poco { +namespace Util { + + +LoggingSubsystem::LoggingSubsystem() +{ +} + + +LoggingSubsystem::~LoggingSubsystem() +{ +} + + +const char* LoggingSubsystem::name() const +{ + return "Logging Subsystem"; +} + + +void LoggingSubsystem::initialize(Application& app) +{ + LoggingConfigurator configurator; + configurator.configure(&app.config()); + std::string logger = app.config().getString("application.logger", "Application"); + app.setLogger(Logger::get(logger)); +} + + +void LoggingSubsystem::uninitialize() +{ +} + + +} } // namespace Poco::Util diff --git a/contrib/libs/poco/Util/src/MapConfiguration.cpp b/contrib/libs/poco/Util/src/MapConfiguration.cpp index 0eaf9de7b5..480956ba36 100644 --- a/contrib/libs/poco/Util/src/MapConfiguration.cpp +++ b/contrib/libs/poco/Util/src/MapConfiguration.cpp @@ -1,122 +1,122 @@ -// -// MapConfiguration.cpp -// -// Library: Util -// Package: Configuration -// Module: MapConfiguration -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// SPDX-License-Identifier: BSL-1.0 -// - - -#include "Poco/Util/MapConfiguration.h" -#include <set> - - -namespace Poco { -namespace Util { - - -MapConfiguration::MapConfiguration() -{ -} - - -MapConfiguration::~MapConfiguration() -{ -} - - -void MapConfiguration::copyTo(AbstractConfiguration& config) -{ - for (iterator it = _map.begin(); it != _map.end(); ++it) - { - config.setString(it->first, it->second); - } -} - - -void MapConfiguration::clear() -{ - _map.clear(); -} - - -bool MapConfiguration::getRaw(const std::string& key, std::string& value) const -{ - StringMap::const_iterator it = _map.find(key); - if (it != _map.end()) - { - value = it->second; - return true; - } - else return false; -} - - -void MapConfiguration::setRaw(const std::string& key, const std::string& value) -{ - _map[key] = value; -} - - -void MapConfiguration::enumerate(const std::string& key, Keys& range) const -{ - std::set<std::string> keys; - std::string prefix = key; - if (!prefix.empty()) prefix += '.'; - std::string::size_type psize = prefix.size(); - for (StringMap::const_iterator it = _map.begin(); it != _map.end(); ++it) - { - if (it->first.compare(0, psize, prefix) == 0) - { - std::string subKey; - std::string::size_type end = it->first.find('.', psize); - if (end == std::string::npos) - subKey = it->first.substr(psize); - else - subKey = it->first.substr(psize, end - psize); - if (keys.find(subKey) == keys.end()) - { - range.push_back(subKey); - keys.insert(subKey); - } - } - } -} - - -void MapConfiguration::removeRaw(const std::string& key) -{ - std::string prefix = key; - if (!prefix.empty()) prefix += '.'; - std::string::size_type psize = prefix.size(); - StringMap::iterator it = _map.begin(); - StringMap::iterator itCur; - while (it != _map.end()) - { - itCur = it++; - if ((itCur->first == key) || (itCur->first.compare(0, psize, prefix) == 0)) - { - _map.erase(itCur); - } - } -} - - -MapConfiguration::iterator MapConfiguration::begin() const -{ - return _map.begin(); -} - - -MapConfiguration::iterator MapConfiguration::end() const -{ - return _map.end(); -} - - -} } // namespace Poco::Util +// +// MapConfiguration.cpp +// +// Library: Util +// Package: Configuration +// Module: MapConfiguration +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#include "Poco/Util/MapConfiguration.h" +#include <set> + + +namespace Poco { +namespace Util { + + +MapConfiguration::MapConfiguration() +{ +} + + +MapConfiguration::~MapConfiguration() +{ +} + + +void MapConfiguration::copyTo(AbstractConfiguration& config) +{ + for (iterator it = _map.begin(); it != _map.end(); ++it) + { + config.setString(it->first, it->second); + } +} + + +void MapConfiguration::clear() +{ + _map.clear(); +} + + +bool MapConfiguration::getRaw(const std::string& key, std::string& value) const +{ + StringMap::const_iterator it = _map.find(key); + if (it != _map.end()) + { + value = it->second; + return true; + } + else return false; +} + + +void MapConfiguration::setRaw(const std::string& key, const std::string& value) +{ + _map[key] = value; +} + + +void MapConfiguration::enumerate(const std::string& key, Keys& range) const +{ + std::set<std::string> keys; + std::string prefix = key; + if (!prefix.empty()) prefix += '.'; + std::string::size_type psize = prefix.size(); + for (StringMap::const_iterator it = _map.begin(); it != _map.end(); ++it) + { + if (it->first.compare(0, psize, prefix) == 0) + { + std::string subKey; + std::string::size_type end = it->first.find('.', psize); + if (end == std::string::npos) + subKey = it->first.substr(psize); + else + subKey = it->first.substr(psize, end - psize); + if (keys.find(subKey) == keys.end()) + { + range.push_back(subKey); + keys.insert(subKey); + } + } + } +} + + +void MapConfiguration::removeRaw(const std::string& key) +{ + std::string prefix = key; + if (!prefix.empty()) prefix += '.'; + std::string::size_type psize = prefix.size(); + StringMap::iterator it = _map.begin(); + StringMap::iterator itCur; + while (it != _map.end()) + { + itCur = it++; + if ((itCur->first == key) || (itCur->first.compare(0, psize, prefix) == 0)) + { + _map.erase(itCur); + } + } +} + + +MapConfiguration::iterator MapConfiguration::begin() const +{ + return _map.begin(); +} + + +MapConfiguration::iterator MapConfiguration::end() const +{ + return _map.end(); +} + + +} } // namespace Poco::Util diff --git a/contrib/libs/poco/Util/src/Option.cpp b/contrib/libs/poco/Util/src/Option.cpp index 1dd326bc82..cdf33ec067 100644 --- a/contrib/libs/poco/Util/src/Option.cpp +++ b/contrib/libs/poco/Util/src/Option.cpp @@ -1,292 +1,292 @@ -// -// Option.cpp -// -// Library: Util -// Package: Options -// Module: Option -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// SPDX-License-Identifier: BSL-1.0 -// - - -#include "Poco/Util/Option.h" -#include "Poco/Util/OptionException.h" -#include "Poco/Util/Validator.h" -#include "Poco/Util/AbstractConfiguration.h" -#include "Poco/String.h" -#include <algorithm> - - -using Poco::icompare; - - -namespace Poco { -namespace Util { - - -Option::Option(): - _required(false), - _repeatable(false), - _argRequired(false), - _pValidator(0), - _pCallback(0), - _pConfig(0) -{ -} - - -Option::Option(const Option& option): - _shortName(option._shortName), - _fullName(option._fullName), - _description(option._description), - _required(option._required), - _repeatable(option._repeatable), - _argName(option._argName), - _argRequired(option._argRequired), - _group(option._group), - _binding(option._binding), - _pValidator(option._pValidator), - _pCallback(option._pCallback), - _pConfig(option._pConfig) -{ - if (_pValidator) _pValidator->duplicate(); - if (_pCallback) _pCallback = _pCallback->clone(); - if (_pConfig) _pConfig->duplicate(); -} - - -Option::Option(const std::string& fullName, const std::string& shortName): - _shortName(shortName), - _fullName(fullName), +// +// Option.cpp +// +// Library: Util +// Package: Options +// Module: Option +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#include "Poco/Util/Option.h" +#include "Poco/Util/OptionException.h" +#include "Poco/Util/Validator.h" +#include "Poco/Util/AbstractConfiguration.h" +#include "Poco/String.h" +#include <algorithm> + + +using Poco::icompare; + + +namespace Poco { +namespace Util { + + +Option::Option(): _required(false), _repeatable(false), - _argRequired(false), - _pValidator(0), - _pCallback(0), - _pConfig(0) -{ -} - - -Option::Option(const std::string& fullName, const std::string& shortName, const std::string& description, bool required): - _shortName(shortName), - _fullName(fullName), - _description(description), - _required(required), - _repeatable(false), - _argRequired(false), - _pValidator(0), - _pCallback(0), - _pConfig(0) -{ -} - - -Option::Option(const std::string& fullName, const std::string& shortName, const std::string& description, bool required, const std::string& argName, bool argRequired): - _shortName(shortName), - _fullName(fullName), - _description(description), - _required(required), - _repeatable(false), - _argName(argName), - _argRequired(argRequired), - _pValidator(0), - _pCallback(0), - _pConfig(0) -{ -} - - -Option::~Option() -{ - if (_pValidator) _pValidator->release(); - if (_pConfig) _pConfig->release(); - delete _pCallback; -} - - -Option& Option::operator = (const Option& option) -{ - if (&option != this) - { - Option tmp(option); - swap(tmp); - } - return *this; -} - - -void Option::swap(Option& option) -{ - std::swap(_shortName, option._shortName); - std::swap(_fullName, option._fullName); - std::swap(_description, option._description); - std::swap(_required, option._required); - std::swap(_repeatable, option._repeatable); - std::swap(_argName, option._argName); - std::swap(_argRequired, option._argRequired); - std::swap(_group, option._group); - std::swap(_binding, option._binding); - std::swap(_pValidator, option._pValidator); - std::swap(_pCallback, option._pCallback); - std::swap(_pConfig, option._pConfig); -} - - -Option& Option::shortName(const std::string& name) -{ - _shortName = name; - return *this; -} - - -Option& Option::fullName(const std::string& name) -{ - _fullName = name; - return *this; -} - - -Option& Option::description(const std::string& text) -{ - _description = text; - return *this; -} - - -Option& Option::required(bool flag) -{ - _required = flag; - return *this; -} - - -Option& Option::repeatable(bool flag) -{ - _repeatable = flag; - return *this; -} - - -Option& Option::argument(const std::string& name, bool required) -{ - _argName = name; - _argRequired = required; - return *this; -} - - -Option& Option::noArgument() -{ - _argName.clear(); - _argRequired = false; - return *this; -} - - -Option& Option::group(const std::string& group) -{ - _group = group; - return *this; -} - - -Option& Option::binding(const std::string& propertyName) -{ - return binding(propertyName, 0); -} - - -Option& Option::binding(const std::string& propertyName, AbstractConfiguration* pConfig) -{ - _binding = propertyName; - if (_pConfig) _pConfig->release(); - _pConfig = pConfig; - if (_pConfig) _pConfig->duplicate(); - return *this; -} - - -Option& Option::callback(const AbstractOptionCallback& cb) -{ - _pCallback = cb.clone(); - return *this; -} - - -Option& Option::validator(Validator* pValidator) -{ - if (_pValidator) _pValidator->release(); - _pValidator = pValidator; - return *this; -} - - -bool Option::matchesShort(const std::string& option) const -{ - return option.length() > 0 - && !_shortName.empty() && option.compare(0, _shortName.length(), _shortName) == 0; -} - - -bool Option::matchesFull(const std::string& option) const -{ - std::string::size_type pos = option.find_first_of(":="); - std::string::size_type len = pos == std::string::npos ? option.length() : pos; - return len == _fullName.length() - && icompare(option, 0, len, _fullName, 0, len) == 0; -} - - -bool Option::matchesPartial(const std::string& option) const -{ - std::string::size_type pos = option.find_first_of(":="); - std::string::size_type len = pos == std::string::npos ? option.length() : pos; - return option.length() > 0 - && icompare(option, 0, len, _fullName, 0, len) == 0; -} - - -void Option::process(const std::string& option, std::string& arg) const -{ - std::string::size_type pos = option.find_first_of(":="); - std::string::size_type len = pos == std::string::npos ? option.length() : pos; - if (icompare(option, 0, len, _fullName, 0, len) == 0) - { - if (takesArgument()) - { - if (argumentRequired() && pos == std::string::npos) - throw MissingArgumentException(_fullName + " requires " + argumentName()); - if (pos != std::string::npos) - arg.assign(option, pos + 1, option.length() - pos - 1); - else - arg.clear(); - } - else if (pos != std::string::npos) - { - throw UnexpectedArgumentException(option); - } - else arg.clear(); - } - else if (!_shortName.empty() && option.compare(0, _shortName.length(), _shortName) == 0) - { - if (takesArgument()) - { - if (argumentRequired() && option.length() == _shortName.length()) - throw MissingArgumentException(_shortName + " requires " + argumentName()); - arg.assign(option, _shortName.length(), option.length() - _shortName.length()); - } - else if (option.length() != _shortName.length()) - { - throw UnexpectedArgumentException(option); - } - else arg.clear(); - } - else throw UnknownOptionException(option); -} - - -} } // namespace Poco::Util + _argRequired(false), + _pValidator(0), + _pCallback(0), + _pConfig(0) +{ +} + + +Option::Option(const Option& option): + _shortName(option._shortName), + _fullName(option._fullName), + _description(option._description), + _required(option._required), + _repeatable(option._repeatable), + _argName(option._argName), + _argRequired(option._argRequired), + _group(option._group), + _binding(option._binding), + _pValidator(option._pValidator), + _pCallback(option._pCallback), + _pConfig(option._pConfig) +{ + if (_pValidator) _pValidator->duplicate(); + if (_pCallback) _pCallback = _pCallback->clone(); + if (_pConfig) _pConfig->duplicate(); +} + + +Option::Option(const std::string& fullName, const std::string& shortName): + _shortName(shortName), + _fullName(fullName), + _required(false), + _repeatable(false), + _argRequired(false), + _pValidator(0), + _pCallback(0), + _pConfig(0) +{ +} + + +Option::Option(const std::string& fullName, const std::string& shortName, const std::string& description, bool required): + _shortName(shortName), + _fullName(fullName), + _description(description), + _required(required), + _repeatable(false), + _argRequired(false), + _pValidator(0), + _pCallback(0), + _pConfig(0) +{ +} + + +Option::Option(const std::string& fullName, const std::string& shortName, const std::string& description, bool required, const std::string& argName, bool argRequired): + _shortName(shortName), + _fullName(fullName), + _description(description), + _required(required), + _repeatable(false), + _argName(argName), + _argRequired(argRequired), + _pValidator(0), + _pCallback(0), + _pConfig(0) +{ +} + + +Option::~Option() +{ + if (_pValidator) _pValidator->release(); + if (_pConfig) _pConfig->release(); + delete _pCallback; +} + + +Option& Option::operator = (const Option& option) +{ + if (&option != this) + { + Option tmp(option); + swap(tmp); + } + return *this; +} + + +void Option::swap(Option& option) +{ + std::swap(_shortName, option._shortName); + std::swap(_fullName, option._fullName); + std::swap(_description, option._description); + std::swap(_required, option._required); + std::swap(_repeatable, option._repeatable); + std::swap(_argName, option._argName); + std::swap(_argRequired, option._argRequired); + std::swap(_group, option._group); + std::swap(_binding, option._binding); + std::swap(_pValidator, option._pValidator); + std::swap(_pCallback, option._pCallback); + std::swap(_pConfig, option._pConfig); +} + + +Option& Option::shortName(const std::string& name) +{ + _shortName = name; + return *this; +} + + +Option& Option::fullName(const std::string& name) +{ + _fullName = name; + return *this; +} + + +Option& Option::description(const std::string& text) +{ + _description = text; + return *this; +} + + +Option& Option::required(bool flag) +{ + _required = flag; + return *this; +} + + +Option& Option::repeatable(bool flag) +{ + _repeatable = flag; + return *this; +} + + +Option& Option::argument(const std::string& name, bool required) +{ + _argName = name; + _argRequired = required; + return *this; +} + + +Option& Option::noArgument() +{ + _argName.clear(); + _argRequired = false; + return *this; +} + + +Option& Option::group(const std::string& group) +{ + _group = group; + return *this; +} + + +Option& Option::binding(const std::string& propertyName) +{ + return binding(propertyName, 0); +} + + +Option& Option::binding(const std::string& propertyName, AbstractConfiguration* pConfig) +{ + _binding = propertyName; + if (_pConfig) _pConfig->release(); + _pConfig = pConfig; + if (_pConfig) _pConfig->duplicate(); + return *this; +} + + +Option& Option::callback(const AbstractOptionCallback& cb) +{ + _pCallback = cb.clone(); + return *this; +} + + +Option& Option::validator(Validator* pValidator) +{ + if (_pValidator) _pValidator->release(); + _pValidator = pValidator; + return *this; +} + + +bool Option::matchesShort(const std::string& option) const +{ + return option.length() > 0 + && !_shortName.empty() && option.compare(0, _shortName.length(), _shortName) == 0; +} + + +bool Option::matchesFull(const std::string& option) const +{ + std::string::size_type pos = option.find_first_of(":="); + std::string::size_type len = pos == std::string::npos ? option.length() : pos; + return len == _fullName.length() + && icompare(option, 0, len, _fullName, 0, len) == 0; +} + + +bool Option::matchesPartial(const std::string& option) const +{ + std::string::size_type pos = option.find_first_of(":="); + std::string::size_type len = pos == std::string::npos ? option.length() : pos; + return option.length() > 0 + && icompare(option, 0, len, _fullName, 0, len) == 0; +} + + +void Option::process(const std::string& option, std::string& arg) const +{ + std::string::size_type pos = option.find_first_of(":="); + std::string::size_type len = pos == std::string::npos ? option.length() : pos; + if (icompare(option, 0, len, _fullName, 0, len) == 0) + { + if (takesArgument()) + { + if (argumentRequired() && pos == std::string::npos) + throw MissingArgumentException(_fullName + " requires " + argumentName()); + if (pos != std::string::npos) + arg.assign(option, pos + 1, option.length() - pos - 1); + else + arg.clear(); + } + else if (pos != std::string::npos) + { + throw UnexpectedArgumentException(option); + } + else arg.clear(); + } + else if (!_shortName.empty() && option.compare(0, _shortName.length(), _shortName) == 0) + { + if (takesArgument()) + { + if (argumentRequired() && option.length() == _shortName.length()) + throw MissingArgumentException(_shortName + " requires " + argumentName()); + arg.assign(option, _shortName.length(), option.length() - _shortName.length()); + } + else if (option.length() != _shortName.length()) + { + throw UnexpectedArgumentException(option); + } + else arg.clear(); + } + else throw UnknownOptionException(option); +} + + +} } // namespace Poco::Util diff --git a/contrib/libs/poco/Util/src/OptionCallback.cpp b/contrib/libs/poco/Util/src/OptionCallback.cpp index 3123d48577..f9fdfc33d0 100644 --- a/contrib/libs/poco/Util/src/OptionCallback.cpp +++ b/contrib/libs/poco/Util/src/OptionCallback.cpp @@ -1,37 +1,37 @@ -// -// OptionCallback.cpp -// -// Library: Util -// Package: Options -// Module: OptionCallback -// -// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// SPDX-License-Identifier: BSL-1.0 -// - - -#include "Poco/Util/OptionCallback.h" - - -namespace Poco { -namespace Util { - - -AbstractOptionCallback::AbstractOptionCallback() -{ -} - - -AbstractOptionCallback::AbstractOptionCallback(const AbstractOptionCallback&) -{ -} - - -AbstractOptionCallback::~AbstractOptionCallback() -{ -} - - -} } // namespace Poco::Util +// +// OptionCallback.cpp +// +// Library: Util +// Package: Options +// Module: OptionCallback +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#include "Poco/Util/OptionCallback.h" + + +namespace Poco { +namespace Util { + + +AbstractOptionCallback::AbstractOptionCallback() +{ +} + + +AbstractOptionCallback::AbstractOptionCallback(const AbstractOptionCallback&) +{ +} + + +AbstractOptionCallback::~AbstractOptionCallback() +{ +} + + +} } // namespace Poco::Util diff --git a/contrib/libs/poco/Util/src/OptionException.cpp b/contrib/libs/poco/Util/src/OptionException.cpp index 237cf2af93..cda4ed0b2d 100644 --- a/contrib/libs/poco/Util/src/OptionException.cpp +++ b/contrib/libs/poco/Util/src/OptionException.cpp @@ -1,35 +1,35 @@ -// -// OptionException.cpp -// -// Library: Util -// Package: Options -// Module: OptionException -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// SPDX-License-Identifier: BSL-1.0 -// - - -#include "Poco/Util/OptionException.h" -#include <typeinfo> - - -namespace Poco { -namespace Util { - - -POCO_IMPLEMENT_EXCEPTION(OptionException, Poco::DataException, "Option exception") -POCO_IMPLEMENT_EXCEPTION(UnknownOptionException, OptionException, "Unknown option specified") -POCO_IMPLEMENT_EXCEPTION(AmbiguousOptionException, OptionException, "Ambiguous option specified") -POCO_IMPLEMENT_EXCEPTION(MissingOptionException, OptionException, "Required option not specified") -POCO_IMPLEMENT_EXCEPTION(MissingArgumentException, OptionException, "Missing option argument") -POCO_IMPLEMENT_EXCEPTION(InvalidArgumentException, OptionException, "Invalid option argument") -POCO_IMPLEMENT_EXCEPTION(UnexpectedArgumentException, OptionException, "Unexpected option argument") -POCO_IMPLEMENT_EXCEPTION(IncompatibleOptionsException, OptionException, "Incompatible options") -POCO_IMPLEMENT_EXCEPTION(DuplicateOptionException, OptionException, "Option must not be given more than once") -POCO_IMPLEMENT_EXCEPTION(EmptyOptionException, OptionException, "Empty option specified") - - -} } // namespace Poco::Util +// +// OptionException.cpp +// +// Library: Util +// Package: Options +// Module: OptionException +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#include "Poco/Util/OptionException.h" +#include <typeinfo> + + +namespace Poco { +namespace Util { + + +POCO_IMPLEMENT_EXCEPTION(OptionException, Poco::DataException, "Option exception") +POCO_IMPLEMENT_EXCEPTION(UnknownOptionException, OptionException, "Unknown option specified") +POCO_IMPLEMENT_EXCEPTION(AmbiguousOptionException, OptionException, "Ambiguous option specified") +POCO_IMPLEMENT_EXCEPTION(MissingOptionException, OptionException, "Required option not specified") +POCO_IMPLEMENT_EXCEPTION(MissingArgumentException, OptionException, "Missing option argument") +POCO_IMPLEMENT_EXCEPTION(InvalidArgumentException, OptionException, "Invalid option argument") +POCO_IMPLEMENT_EXCEPTION(UnexpectedArgumentException, OptionException, "Unexpected option argument") +POCO_IMPLEMENT_EXCEPTION(IncompatibleOptionsException, OptionException, "Incompatible options") +POCO_IMPLEMENT_EXCEPTION(DuplicateOptionException, OptionException, "Option must not be given more than once") +POCO_IMPLEMENT_EXCEPTION(EmptyOptionException, OptionException, "Empty option specified") + + +} } // namespace Poco::Util diff --git a/contrib/libs/poco/Util/src/OptionProcessor.cpp b/contrib/libs/poco/Util/src/OptionProcessor.cpp index 0f11796932..f9c3dc68da 100644 --- a/contrib/libs/poco/Util/src/OptionProcessor.cpp +++ b/contrib/libs/poco/Util/src/OptionProcessor.cpp @@ -1,159 +1,159 @@ -// -// OptionProcessor.cpp -// -// Library: Util -// Package: Options -// Module: OptionProcessor -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// SPDX-License-Identifier: BSL-1.0 -// - - -#include "Poco/Util/OptionProcessor.h" -#include "Poco/Util/OptionSet.h" -#include "Poco/Util/Option.h" -#include "Poco/Util/OptionException.h" - - -namespace Poco { -namespace Util { - - -OptionProcessor::OptionProcessor(const OptionSet& options): - _options(options), - _unixStyle(true), - _ignore(false) -{ -} - - -OptionProcessor::~OptionProcessor() -{ -} - - -void OptionProcessor::setUnixStyle(bool flag) -{ - _unixStyle = flag; -} - - -bool OptionProcessor::process(const std::string& argument, std::string& optionName, std::string& optionArg) -{ - optionName.clear(); - optionArg.clear(); - if (!_ignore) - { - if (!_deferredOption.empty()) - return processCommon(argument, false, optionName, optionArg); - else if (_unixStyle) - return processUnix(argument, optionName, optionArg); - else - return processDefault(argument, optionName, optionArg); - } - return false; -} - - -void OptionProcessor::checkRequired() const -{ - for (OptionSet::Iterator it = _options.begin(); it != _options.end(); ++it) - { - if (it->required() && _specifiedOptions.find(it->fullName()) == _specifiedOptions.end()) - throw MissingOptionException(it->fullName()); - } - if (!_deferredOption.empty()) - { - std::string optionArg; - const Option& option = _options.getOption(_deferredOption, false); - option.process(_deferredOption, optionArg); // will throw MissingArgumentException - } -} - - -bool OptionProcessor::processUnix(const std::string& argument, std::string& optionName, std::string& optionArg) -{ - std::string::const_iterator it = argument.begin(); - std::string::const_iterator end = argument.end(); - if (it != end) - { - if (*it == '-') - { - ++it; - if (it != end) - { - if (*it == '-') - { - ++it; - if (it == end) - { - _ignore = true; - return true; - } - else return processCommon(std::string(it, end), false, optionName, optionArg); - } - else return processCommon(std::string(it, end), true, optionName, optionArg); - } - } - } - return false; -} - - -bool OptionProcessor::processDefault(const std::string& argument, std::string& optionName, std::string& optionArg) -{ - std::string::const_iterator it = argument.begin(); - std::string::const_iterator end = argument.end(); - if (it != end) - { - if (*it == '/') - { - ++it; - return processCommon(std::string(it, end), false, optionName, optionArg); - } - } - return false; -} - - -bool OptionProcessor::processCommon(const std::string& optionStr, bool isShort, std::string& optionName, std::string& optionArg) -{ - if (!_deferredOption.empty()) - { - const Option& option = _options.getOption(_deferredOption, false); - std::string optionWithArg(_deferredOption); - _deferredOption.clear(); - optionWithArg += '='; - optionWithArg += optionStr; - option.process(optionWithArg, optionArg); - optionName = option.fullName(); - return true; - } - if (optionStr.empty()) throw EmptyOptionException(); - const Option& option = _options.getOption(optionStr, isShort); - const std::string& group = option.group(); - if (!group.empty()) - { - if (_groups.find(group) != _groups.end()) - throw IncompatibleOptionsException(option.fullName()); - else - _groups.insert(group); - } - if (_specifiedOptions.find(option.fullName()) != _specifiedOptions.end() && !option.repeatable()) - throw DuplicateOptionException(option.fullName()); - _specifiedOptions.insert(option.fullName()); - if (option.argumentRequired() && ((!isShort && optionStr.find_first_of(":=") == std::string::npos) || (isShort && optionStr.length() == option.shortName().length()))) - { - _deferredOption = option.fullName(); - return true; - } - option.process(optionStr, optionArg); - optionName = option.fullName(); - return true; -} - - -} } // namespace Poco::Util +// +// OptionProcessor.cpp +// +// Library: Util +// Package: Options +// Module: OptionProcessor +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#include "Poco/Util/OptionProcessor.h" +#include "Poco/Util/OptionSet.h" +#include "Poco/Util/Option.h" +#include "Poco/Util/OptionException.h" + + +namespace Poco { +namespace Util { + + +OptionProcessor::OptionProcessor(const OptionSet& options): + _options(options), + _unixStyle(true), + _ignore(false) +{ +} + + +OptionProcessor::~OptionProcessor() +{ +} + + +void OptionProcessor::setUnixStyle(bool flag) +{ + _unixStyle = flag; +} + + +bool OptionProcessor::process(const std::string& argument, std::string& optionName, std::string& optionArg) +{ + optionName.clear(); + optionArg.clear(); + if (!_ignore) + { + if (!_deferredOption.empty()) + return processCommon(argument, false, optionName, optionArg); + else if (_unixStyle) + return processUnix(argument, optionName, optionArg); + else + return processDefault(argument, optionName, optionArg); + } + return false; +} + + +void OptionProcessor::checkRequired() const +{ + for (OptionSet::Iterator it = _options.begin(); it != _options.end(); ++it) + { + if (it->required() && _specifiedOptions.find(it->fullName()) == _specifiedOptions.end()) + throw MissingOptionException(it->fullName()); + } + if (!_deferredOption.empty()) + { + std::string optionArg; + const Option& option = _options.getOption(_deferredOption, false); + option.process(_deferredOption, optionArg); // will throw MissingArgumentException + } +} + + +bool OptionProcessor::processUnix(const std::string& argument, std::string& optionName, std::string& optionArg) +{ + std::string::const_iterator it = argument.begin(); + std::string::const_iterator end = argument.end(); + if (it != end) + { + if (*it == '-') + { + ++it; + if (it != end) + { + if (*it == '-') + { + ++it; + if (it == end) + { + _ignore = true; + return true; + } + else return processCommon(std::string(it, end), false, optionName, optionArg); + } + else return processCommon(std::string(it, end), true, optionName, optionArg); + } + } + } + return false; +} + + +bool OptionProcessor::processDefault(const std::string& argument, std::string& optionName, std::string& optionArg) +{ + std::string::const_iterator it = argument.begin(); + std::string::const_iterator end = argument.end(); + if (it != end) + { + if (*it == '/') + { + ++it; + return processCommon(std::string(it, end), false, optionName, optionArg); + } + } + return false; +} + + +bool OptionProcessor::processCommon(const std::string& optionStr, bool isShort, std::string& optionName, std::string& optionArg) +{ + if (!_deferredOption.empty()) + { + const Option& option = _options.getOption(_deferredOption, false); + std::string optionWithArg(_deferredOption); + _deferredOption.clear(); + optionWithArg += '='; + optionWithArg += optionStr; + option.process(optionWithArg, optionArg); + optionName = option.fullName(); + return true; + } + if (optionStr.empty()) throw EmptyOptionException(); + const Option& option = _options.getOption(optionStr, isShort); + const std::string& group = option.group(); + if (!group.empty()) + { + if (_groups.find(group) != _groups.end()) + throw IncompatibleOptionsException(option.fullName()); + else + _groups.insert(group); + } + if (_specifiedOptions.find(option.fullName()) != _specifiedOptions.end() && !option.repeatable()) + throw DuplicateOptionException(option.fullName()); + _specifiedOptions.insert(option.fullName()); + if (option.argumentRequired() && ((!isShort && optionStr.find_first_of(":=") == std::string::npos) || (isShort && optionStr.length() == option.shortName().length()))) + { + _deferredOption = option.fullName(); + return true; + } + option.process(optionStr, optionArg); + optionName = option.fullName(); + return true; +} + + +} } // namespace Poco::Util diff --git a/contrib/libs/poco/Util/src/OptionSet.cpp b/contrib/libs/poco/Util/src/OptionSet.cpp index 637c19dd2e..bfda7b7691 100644 --- a/contrib/libs/poco/Util/src/OptionSet.cpp +++ b/contrib/libs/poco/Util/src/OptionSet.cpp @@ -1,122 +1,122 @@ -// -// OptionSet.cpp -// -// Library: Util -// Package: Options -// Module: OptionSet -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// SPDX-License-Identifier: BSL-1.0 -// - - -#include "Poco/Util/OptionSet.h" -#include "Poco/Util/OptionException.h" -#include "Poco/Exception.h" - - -namespace Poco { -namespace Util { - - -OptionSet::OptionSet() -{ -} - - -OptionSet::OptionSet(const OptionSet& options): - _options(options._options) -{ -} - - -OptionSet::~OptionSet() -{ -} - - -OptionSet& OptionSet::operator = (const OptionSet& options) -{ - if (&options != this) - _options = options._options; - return *this; -} - - -void OptionSet::addOption(const Option& option) -{ - poco_assert (!option.fullName().empty()); - OptionVec::const_iterator it = _options.begin(); - OptionVec::const_iterator itEnd = _options.end(); - for (; it != itEnd; ++it) - { - if (it->fullName() == option.fullName()) - { - throw DuplicateOptionException(it->fullName()); - } - } - - _options.push_back(option); -} - - -bool OptionSet::hasOption(const std::string& name, bool matchShort) const -{ - bool found = false; - for (Iterator it = _options.begin(); it != _options.end(); ++it) - { - if ((matchShort && it->matchesShort(name)) || (!matchShort && it->matchesFull(name))) - { - if (!found) - found = true; - else - return false; - } - } - return found; -} - - -const Option& OptionSet::getOption(const std::string& name, bool matchShort) const -{ - const Option* pOption = 0; - for (Iterator it = _options.begin(); it != _options.end(); ++it) - { - if ((matchShort && it->matchesShort(name)) || (!matchShort && it->matchesPartial(name))) - { - if (!pOption) - { - pOption = &*it; - if (!matchShort && it->matchesFull(name)) - break; - } - else if (!matchShort && it->matchesFull(name)) - { - pOption = &*it; - break; - } - else throw AmbiguousOptionException(name); - } - } - if (pOption) - return *pOption; - else - throw UnknownOptionException(name); -} - - -OptionSet::Iterator OptionSet::begin() const -{ - return _options.begin(); -} - - -OptionSet::Iterator OptionSet::end() const -{ - return _options.end(); -} - - -} } // namespace Poco::Util +// +// OptionSet.cpp +// +// Library: Util +// Package: Options +// Module: OptionSet +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#include "Poco/Util/OptionSet.h" +#include "Poco/Util/OptionException.h" +#include "Poco/Exception.h" + + +namespace Poco { +namespace Util { + + +OptionSet::OptionSet() +{ +} + + +OptionSet::OptionSet(const OptionSet& options): + _options(options._options) +{ +} + + +OptionSet::~OptionSet() +{ +} + + +OptionSet& OptionSet::operator = (const OptionSet& options) +{ + if (&options != this) + _options = options._options; + return *this; +} + + +void OptionSet::addOption(const Option& option) +{ + poco_assert (!option.fullName().empty()); + OptionVec::const_iterator it = _options.begin(); + OptionVec::const_iterator itEnd = _options.end(); + for (; it != itEnd; ++it) + { + if (it->fullName() == option.fullName()) + { + throw DuplicateOptionException(it->fullName()); + } + } + + _options.push_back(option); +} + + +bool OptionSet::hasOption(const std::string& name, bool matchShort) const +{ + bool found = false; + for (Iterator it = _options.begin(); it != _options.end(); ++it) + { + if ((matchShort && it->matchesShort(name)) || (!matchShort && it->matchesFull(name))) + { + if (!found) + found = true; + else + return false; + } + } + return found; +} + + +const Option& OptionSet::getOption(const std::string& name, bool matchShort) const +{ + const Option* pOption = 0; + for (Iterator it = _options.begin(); it != _options.end(); ++it) + { + if ((matchShort && it->matchesShort(name)) || (!matchShort && it->matchesPartial(name))) + { + if (!pOption) + { + pOption = &*it; + if (!matchShort && it->matchesFull(name)) + break; + } + else if (!matchShort && it->matchesFull(name)) + { + pOption = &*it; + break; + } + else throw AmbiguousOptionException(name); + } + } + if (pOption) + return *pOption; + else + throw UnknownOptionException(name); +} + + +OptionSet::Iterator OptionSet::begin() const +{ + return _options.begin(); +} + + +OptionSet::Iterator OptionSet::end() const +{ + return _options.end(); +} + + +} } // namespace Poco::Util diff --git a/contrib/libs/poco/Util/src/PropertyFileConfiguration.cpp b/contrib/libs/poco/Util/src/PropertyFileConfiguration.cpp index 253fdbca98..dbdc811403 100644 --- a/contrib/libs/poco/Util/src/PropertyFileConfiguration.cpp +++ b/contrib/libs/poco/Util/src/PropertyFileConfiguration.cpp @@ -1,190 +1,190 @@ -// -// PropertyFileConfiguration.cpp -// -// Library: Util -// Package: Configuration -// Module: PropertyFileConfiguration -// -// Copyright (c) 2004-2009, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// SPDX-License-Identifier: BSL-1.0 -// - - -#include "Poco/Util/PropertyFileConfiguration.h" -#include "Poco/Exception.h" -#include "Poco/String.h" -#include "Poco/Path.h" -#include "Poco/FileStream.h" -#include "Poco/LineEndingConverter.h" -#include "Poco/Ascii.h" - - -using Poco::trim; -using Poco::Path; - - -namespace Poco { -namespace Util { - - -PropertyFileConfiguration::PropertyFileConfiguration() -{ -} - - -PropertyFileConfiguration::PropertyFileConfiguration(std::istream& istr) -{ - load(istr); -} - - -PropertyFileConfiguration::PropertyFileConfiguration(const std::string& path) -{ - load(path); -} - - -PropertyFileConfiguration::~PropertyFileConfiguration() -{ -} - - -void PropertyFileConfiguration::load(std::istream& istr) -{ - clear(); - while (!istr.eof()) - { - parseLine(istr); - } -} - - -void PropertyFileConfiguration::load(const std::string& path) -{ - Poco::FileInputStream istr(path); - if (istr.good()) - load(istr); - else - throw Poco::OpenFileException(path); -} - - -void PropertyFileConfiguration::save(std::ostream& ostr) const -{ - MapConfiguration::iterator it = begin(); - MapConfiguration::iterator ed = end(); - while (it != ed) - { - ostr << it->first << ": "; - for (std::string::const_iterator its = it->second.begin(); its != it->second.end(); ++its) - { - switch (*its) - { - case '\t': - ostr << "\\t"; - break; - case '\r': - ostr << "\\r"; - break; - case '\n': - ostr << "\\n"; - break; - case '\f': - ostr << "\\f"; - break; - case '\\': - ostr << "\\\\"; - break; - default: - ostr << *its; - break; - } - } - ostr << "\n"; - ++it; - } -} - - -void PropertyFileConfiguration::save(const std::string& path) const -{ - Poco::FileOutputStream ostr(path); - if (ostr.good()) - { - Poco::OutputLineEndingConverter lec(ostr); - save(lec); - lec.flush(); - ostr.flush(); - if (!ostr.good()) throw Poco::WriteFileException(path); - } - else throw Poco::CreateFileException(path); -} - - -void PropertyFileConfiguration::parseLine(std::istream& istr) -{ - static const int eof = std::char_traits<char>::eof(); - - int c = istr.get(); - while (c != eof && Poco::Ascii::isSpace(c)) c = istr.get(); - if (c != eof) - { - if (c == '#' || c == '!') - { - while (c != eof && c != '\n' && c != '\r') c = istr.get(); - } - else - { - std::string key; - while (c != eof && c != '=' && c != ':' && c != '\r' && c != '\n') { key += (char) c; c = istr.get(); } - std::string value; - if (c == '=' || c == ':') - { - c = readChar(istr); - while (c != eof && c) { value += (char) c; c = readChar(istr); } - } - setRaw(trim(key), trim(value)); - } - } -} - - -int PropertyFileConfiguration::readChar(std::istream& istr) -{ - for (;;) - { - int c = istr.get(); - if (c == '\\') - { - c = istr.get(); - switch (c) - { - case 't': - return '\t'; - case 'r': - return '\r'; - case 'n': - return '\n'; - case 'f': - return '\f'; - case '\r': - if (istr.peek() == '\n') - istr.get(); - continue; - case '\n': - continue; - default: - return c; - } - } - else if (c == '\n' || c == '\r') - return 0; - else - return c; - } -} - - -} } // namespace Poco::Util +// +// PropertyFileConfiguration.cpp +// +// Library: Util +// Package: Configuration +// Module: PropertyFileConfiguration +// +// Copyright (c) 2004-2009, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#include "Poco/Util/PropertyFileConfiguration.h" +#include "Poco/Exception.h" +#include "Poco/String.h" +#include "Poco/Path.h" +#include "Poco/FileStream.h" +#include "Poco/LineEndingConverter.h" +#include "Poco/Ascii.h" + + +using Poco::trim; +using Poco::Path; + + +namespace Poco { +namespace Util { + + +PropertyFileConfiguration::PropertyFileConfiguration() +{ +} + + +PropertyFileConfiguration::PropertyFileConfiguration(std::istream& istr) +{ + load(istr); +} + + +PropertyFileConfiguration::PropertyFileConfiguration(const std::string& path) +{ + load(path); +} + + +PropertyFileConfiguration::~PropertyFileConfiguration() +{ +} + + +void PropertyFileConfiguration::load(std::istream& istr) +{ + clear(); + while (!istr.eof()) + { + parseLine(istr); + } +} + + +void PropertyFileConfiguration::load(const std::string& path) +{ + Poco::FileInputStream istr(path); + if (istr.good()) + load(istr); + else + throw Poco::OpenFileException(path); +} + + +void PropertyFileConfiguration::save(std::ostream& ostr) const +{ + MapConfiguration::iterator it = begin(); + MapConfiguration::iterator ed = end(); + while (it != ed) + { + ostr << it->first << ": "; + for (std::string::const_iterator its = it->second.begin(); its != it->second.end(); ++its) + { + switch (*its) + { + case '\t': + ostr << "\\t"; + break; + case '\r': + ostr << "\\r"; + break; + case '\n': + ostr << "\\n"; + break; + case '\f': + ostr << "\\f"; + break; + case '\\': + ostr << "\\\\"; + break; + default: + ostr << *its; + break; + } + } + ostr << "\n"; + ++it; + } +} + + +void PropertyFileConfiguration::save(const std::string& path) const +{ + Poco::FileOutputStream ostr(path); + if (ostr.good()) + { + Poco::OutputLineEndingConverter lec(ostr); + save(lec); + lec.flush(); + ostr.flush(); + if (!ostr.good()) throw Poco::WriteFileException(path); + } + else throw Poco::CreateFileException(path); +} + + +void PropertyFileConfiguration::parseLine(std::istream& istr) +{ + static const int eof = std::char_traits<char>::eof(); + + int c = istr.get(); + while (c != eof && Poco::Ascii::isSpace(c)) c = istr.get(); + if (c != eof) + { + if (c == '#' || c == '!') + { + while (c != eof && c != '\n' && c != '\r') c = istr.get(); + } + else + { + std::string key; + while (c != eof && c != '=' && c != ':' && c != '\r' && c != '\n') { key += (char) c; c = istr.get(); } + std::string value; + if (c == '=' || c == ':') + { + c = readChar(istr); + while (c != eof && c) { value += (char) c; c = readChar(istr); } + } + setRaw(trim(key), trim(value)); + } + } +} + + +int PropertyFileConfiguration::readChar(std::istream& istr) +{ + for (;;) + { + int c = istr.get(); + if (c == '\\') + { + c = istr.get(); + switch (c) + { + case 't': + return '\t'; + case 'r': + return '\r'; + case 'n': + return '\n'; + case 'f': + return '\f'; + case '\r': + if (istr.peek() == '\n') + istr.get(); + continue; + case '\n': + continue; + default: + return c; + } + } + else if (c == '\n' || c == '\r') + return 0; + else + return c; + } +} + + +} } // namespace Poco::Util diff --git a/contrib/libs/poco/Util/src/RegExpValidator.cpp b/contrib/libs/poco/Util/src/RegExpValidator.cpp index 0adb588efb..1553340650 100644 --- a/contrib/libs/poco/Util/src/RegExpValidator.cpp +++ b/contrib/libs/poco/Util/src/RegExpValidator.cpp @@ -1,47 +1,47 @@ -// -// RegExpValidator.cpp -// -// Library: Util -// Package: Options -// Module: RegExpValidator -// -// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// SPDX-License-Identifier: BSL-1.0 -// - - -#include "Poco/Util/RegExpValidator.h" -#include "Poco/Util/Option.h" -#include "Poco/Util/OptionException.h" -#include "Poco/RegularExpression.h" -#include "Poco/Format.h" - - -using Poco::format; - - -namespace Poco { -namespace Util { - - -RegExpValidator::RegExpValidator(const std::string& regexp): - _regexp(regexp) -{ -} - - -RegExpValidator::~RegExpValidator() -{ -} - - -void RegExpValidator::validate(const Option& option, const std::string& value) -{ - if (!RegularExpression::match(value, _regexp, RegularExpression::RE_ANCHORED | RegularExpression::RE_UTF8)) - throw InvalidArgumentException(format("argument for %s does not match regular expression %s", option.fullName(), _regexp)); -} - - -} } // namespace Poco::Util +// +// RegExpValidator.cpp +// +// Library: Util +// Package: Options +// Module: RegExpValidator +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#include "Poco/Util/RegExpValidator.h" +#include "Poco/Util/Option.h" +#include "Poco/Util/OptionException.h" +#include "Poco/RegularExpression.h" +#include "Poco/Format.h" + + +using Poco::format; + + +namespace Poco { +namespace Util { + + +RegExpValidator::RegExpValidator(const std::string& regexp): + _regexp(regexp) +{ +} + + +RegExpValidator::~RegExpValidator() +{ +} + + +void RegExpValidator::validate(const Option& option, const std::string& value) +{ + if (!RegularExpression::match(value, _regexp, RegularExpression::RE_ANCHORED | RegularExpression::RE_UTF8)) + throw InvalidArgumentException(format("argument for %s does not match regular expression %s", option.fullName(), _regexp)); +} + + +} } // namespace Poco::Util diff --git a/contrib/libs/poco/Util/src/ServerApplication.cpp b/contrib/libs/poco/Util/src/ServerApplication.cpp index 10e6c35397..e427c0906c 100644 --- a/contrib/libs/poco/Util/src/ServerApplication.cpp +++ b/contrib/libs/poco/Util/src/ServerApplication.cpp @@ -1,749 +1,749 @@ -// -// ServerApplication.cpp -// -// Library: Util -// Package: Application -// Module: ServerApplication -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// SPDX-License-Identifier: BSL-1.0 -// - - -#include "Poco/Util/ServerApplication.h" -#include "Poco/Util/Option.h" -#include "Poco/Util/OptionSet.h" -#include "Poco/Util/OptionException.h" -#include "Poco/FileStream.h" -#include "Poco/Exception.h" -#if !defined(POCO_VXWORKS) -#include "Poco/Process.h" -#include "Poco/NamedEvent.h" -#endif -#include "Poco/NumberFormatter.h" -#include "Poco/Logger.h" -#include "Poco/String.h" -#if defined(POCO_OS_FAMILY_UNIX) && !defined(POCO_VXWORKS) -#include "Poco/TemporaryFile.h" -#include <stdlib.h> -#include <unistd.h> -#include <stdio.h> -#include <signal.h> -#include <sys/stat.h> -#include <fstream> -#elif defined(POCO_OS_FAMILY_WINDOWS) -#if !defined(_WIN32_WCE) -#include "Poco/Util/WinService.h" -#include "Poco/Util/WinRegistryKey.h" -#endif -#include "Poco/UnWindows.h" -#include <cstring> -#endif -#if defined(POCO_WIN32_UTF8) && !defined(POCO_NO_WSTRING) -#include "Poco/UnicodeConverter.h" -#endif - - -using Poco::NumberFormatter; -using Poco::Exception; -using Poco::SystemException; - - -namespace Poco { -namespace Util { - - -#if defined(POCO_OS_FAMILY_WINDOWS) -Poco::NamedEvent ServerApplication::_terminate(Poco::ProcessImpl::terminationEventName(Poco::Process::id())); -#if !defined(_WIN32_WCE) -Poco::Event ServerApplication::_terminated; -SERVICE_STATUS ServerApplication::_serviceStatus; -SERVICE_STATUS_HANDLE ServerApplication::_serviceStatusHandle = 0; -#endif -#endif -#if defined(POCO_VXWORKS) || POCO_OS == POCO_OS_ANDROID -Poco::Event ServerApplication::_terminate; -#endif - - -ServerApplication::ServerApplication() -{ -#if defined(POCO_OS_FAMILY_WINDOWS) -#if !defined(_WIN32_WCE) - _action = SRV_RUN; - std::memset(&_serviceStatus, 0, sizeof(_serviceStatus)); -#endif -#endif -} - - -ServerApplication::~ServerApplication() -{ -} - - -bool ServerApplication::isInteractive() const -{ - bool runsInBackground = config().getBool("application.runAsDaemon", false) || config().getBool("application.runAsService", false); - return !runsInBackground; -} - - -int ServerApplication::run() -{ - return Application::run(); -} - - -void ServerApplication::terminate() -{ -#if defined(POCO_OS_FAMILY_WINDOWS) - _terminate.set(); -#elif defined(POCO_VXWORKS) || POCO_OS == POCO_OS_ANDROID - _terminate.set(); -#else - Poco::Process::requestTermination(Process::id()); -#endif -} - - -#if defined(POCO_OS_FAMILY_WINDOWS) -#if !defined(_WIN32_WCE) - - -// -// Windows specific code -// -BOOL ServerApplication::ConsoleCtrlHandler(DWORD ctrlType) -{ - switch (ctrlType) - { - case CTRL_C_EVENT: - case CTRL_CLOSE_EVENT: - case CTRL_BREAK_EVENT: - terminate(); - return _terminated.tryWait(10000) ? TRUE : FALSE; - default: - return FALSE; - } -} - - -void ServerApplication::ServiceControlHandler(DWORD control) -{ - switch (control) - { - case SERVICE_CONTROL_STOP: - case SERVICE_CONTROL_SHUTDOWN: - terminate(); - _serviceStatus.dwCurrentState = SERVICE_STOP_PENDING; - break; - case SERVICE_CONTROL_INTERROGATE: - break; - } - SetServiceStatus(_serviceStatusHandle, &_serviceStatus); -} - - -#if defined(POCO_WIN32_UTF8) && !defined(POCO_NO_WSTRING) -void ServerApplication::ServiceMain(DWORD argc, LPWSTR* argv) -#else -void ServerApplication::ServiceMain(DWORD argc, LPTSTR* argv) -#endif -{ - ServerApplication& app = static_cast<ServerApplication&>(Application::instance()); - - app.config().setBool("application.runAsService", true); - -#if defined(POCO_WIN32_UTF8) && !defined(POCO_NO_WSTRING) - _serviceStatusHandle = RegisterServiceCtrlHandlerW(L"", ServiceControlHandler); -#else - _serviceStatusHandle = RegisterServiceCtrlHandlerA("", ServiceControlHandler); -#endif - if (!_serviceStatusHandle) - throw SystemException("cannot register service control handler"); - - _serviceStatus.dwServiceType = SERVICE_WIN32; - _serviceStatus.dwCurrentState = SERVICE_START_PENDING; - _serviceStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN; - _serviceStatus.dwWin32ExitCode = 0; - _serviceStatus.dwServiceSpecificExitCode = 0; - _serviceStatus.dwCheckPoint = 0; - _serviceStatus.dwWaitHint = 0; - SetServiceStatus(_serviceStatusHandle, &_serviceStatus); - - try - { -#if defined(POCO_WIN32_UTF8) && !defined(POCO_NO_WSTRING) - std::vector<std::string> args; - for (DWORD i = 0; i < argc; ++i) - { - std::string arg; - Poco::UnicodeConverter::toUTF8(argv[i], arg); - args.push_back(arg); - } - app.init(args); -#else - app.init(argc, argv); -#endif - _serviceStatus.dwCurrentState = SERVICE_RUNNING; - SetServiceStatus(_serviceStatusHandle, &_serviceStatus); - int rc = app.run(); - _serviceStatus.dwWin32ExitCode = rc ? ERROR_SERVICE_SPECIFIC_ERROR : 0; - _serviceStatus.dwServiceSpecificExitCode = rc; - } - catch (Exception& exc) - { - app.logger().log(exc); - _serviceStatus.dwWin32ExitCode = ERROR_SERVICE_SPECIFIC_ERROR; - _serviceStatus.dwServiceSpecificExitCode = EXIT_CONFIG; - } - catch (...) - { - app.logger().error("fatal error - aborting"); - _serviceStatus.dwWin32ExitCode = ERROR_SERVICE_SPECIFIC_ERROR; - _serviceStatus.dwServiceSpecificExitCode = EXIT_SOFTWARE; - } - _serviceStatus.dwCurrentState = SERVICE_STOPPED; - SetServiceStatus(_serviceStatusHandle, &_serviceStatus); -} - - -void ServerApplication::waitForTerminationRequest() -{ - SetConsoleCtrlHandler(ConsoleCtrlHandler, TRUE); - _terminate.wait(); - _terminated.set(); -} - - -int ServerApplication::run(int argc, char** argv) -{ - if (!hasConsole() && isService()) - { - return 0; - } - else - { - int rc = EXIT_OK; - try - { - init(argc, argv); - switch (_action) - { - case SRV_REGISTER: - registerService(); - rc = EXIT_OK; - break; - case SRV_UNREGISTER: - unregisterService(); - rc = EXIT_OK; - break; - default: - rc = run(); - } - } - catch (Exception& exc) - { - logger().log(exc); - rc = EXIT_SOFTWARE; - } - return rc; - } -} - - -int ServerApplication::run(const std::vector<std::string>& args) -{ - if (!hasConsole() && isService()) - { - return 0; - } - else - { - int rc = EXIT_OK; - try - { - init(args); - switch (_action) - { - case SRV_REGISTER: - registerService(); - rc = EXIT_OK; - break; - case SRV_UNREGISTER: - unregisterService(); - rc = EXIT_OK; - break; - default: - rc = run(); - } - } - catch (Exception& exc) - { - logger().log(exc); - rc = EXIT_SOFTWARE; - } - return rc; - } -} - - -#if defined(POCO_WIN32_UTF8) && !defined(POCO_NO_WSTRING) -int ServerApplication::run(int argc, wchar_t** argv) -{ - if (!hasConsole() && isService()) - { - return 0; - } - else - { - int rc = EXIT_OK; - try - { - init(argc, argv); - switch (_action) - { - case SRV_REGISTER: - registerService(); - rc = EXIT_OK; - break; - case SRV_UNREGISTER: - unregisterService(); - rc = EXIT_OK; - break; - default: - rc = run(); - } - } - catch (Exception& exc) - { - logger().log(exc); - rc = EXIT_SOFTWARE; - } - return rc; - } -} -#endif - - -bool ServerApplication::isService() -{ -#if defined(POCO_WIN32_UTF8) && !defined(POCO_NO_WSTRING) - SERVICE_TABLE_ENTRYW svcDispatchTable[2]; - svcDispatchTable[0].lpServiceName = L""; - svcDispatchTable[0].lpServiceProc = ServiceMain; - svcDispatchTable[1].lpServiceName = NULL; - svcDispatchTable[1].lpServiceProc = NULL; - return StartServiceCtrlDispatcherW(svcDispatchTable) != 0; -#else - SERVICE_TABLE_ENTRY svcDispatchTable[2]; - svcDispatchTable[0].lpServiceName = ""; - svcDispatchTable[0].lpServiceProc = ServiceMain; - svcDispatchTable[1].lpServiceName = NULL; - svcDispatchTable[1].lpServiceProc = NULL; - return StartServiceCtrlDispatcherA(svcDispatchTable) != 0; -#endif -} - - -bool ServerApplication::hasConsole() -{ - HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE); - return hStdOut != INVALID_HANDLE_VALUE && hStdOut != NULL; -} - - -void ServerApplication::registerService() -{ - std::string name = config().getString("application.baseName"); - std::string path = config().getString("application.path"); - - WinService service(name); - if (_displayName.empty()) - service.registerService(path); - else - service.registerService(path, _displayName); - if (_startup == "auto") - service.setStartup(WinService::SVC_AUTO_START); - else if (_startup == "manual") - service.setStartup(WinService::SVC_MANUAL_START); - if (!_description.empty()) - service.setDescription(_description); - logger().information("The application has been successfully registered as a service."); -} - - -void ServerApplication::unregisterService() -{ - std::string name = config().getString("application.baseName"); - - WinService service(name); - service.unregisterService(); - logger().information("The service has been successfully unregistered."); -} - - -void ServerApplication::defineOptions(OptionSet& options) -{ - Application::defineOptions(options); - - options.addOption( - Option("registerService", "", "Register the application as a service.") - .required(false) - .repeatable(false) - .callback(OptionCallback<ServerApplication>(this, &ServerApplication::handleRegisterService))); - - options.addOption( - Option("unregisterService", "", "Unregister the application as a service.") - .required(false) - .repeatable(false) - .callback(OptionCallback<ServerApplication>(this, &ServerApplication::handleUnregisterService))); - - options.addOption( - Option("displayName", "", "Specify a display name for the service (only with /registerService).") - .required(false) - .repeatable(false) - .argument("name") - .callback(OptionCallback<ServerApplication>(this, &ServerApplication::handleDisplayName))); - - options.addOption( - Option("description", "", "Specify a description for the service (only with /registerService).") - .required(false) - .repeatable(false) - .argument("text") - .callback(OptionCallback<ServerApplication>(this, &ServerApplication::handleDescription))); - - options.addOption( - Option("startup", "", "Specify the startup mode for the service (only with /registerService).") - .required(false) - .repeatable(false) - .argument("automatic|manual") - .callback(OptionCallback<ServerApplication>(this, &ServerApplication::handleStartup))); -} - - -void ServerApplication::handleRegisterService(const std::string& /*name*/, const std::string& /*value*/) -{ - _action = SRV_REGISTER; -} - - -void ServerApplication::handleUnregisterService(const std::string& /*name*/, const std::string& /*value*/) -{ - _action = SRV_UNREGISTER; -} - - -void ServerApplication::handleDisplayName(const std::string& /*name*/, const std::string& value) -{ - _displayName = value; -} - - -void ServerApplication::handleDescription(const std::string& /*name*/, const std::string& value) -{ - _description = value; -} - - -void ServerApplication::handleStartup(const std::string& /*name*/, const std::string& value) -{ - if (Poco::icompare(value, 4, std::string("auto")) == 0) - _startup = "auto"; - else if (Poco::icompare(value, std::string("manual")) == 0) - _startup = "manual"; - else - throw InvalidArgumentException("argument to startup option must be 'auto[matic]' or 'manual'"); -} - - -#else // _WIN32_WCE -void ServerApplication::waitForTerminationRequest() -{ - _terminate.wait(); -} - - -int ServerApplication::run(int argc, char** argv) -{ - try - { - init(argc, argv); - } - catch (Exception& exc) - { - logger().log(exc); - return EXIT_CONFIG; - } - return run(); -} - - -int ServerApplication::run(const std::vector<std::string>& args) -{ - try - { - init(args); - } - catch (Exception& exc) - { - logger().log(exc); - return EXIT_CONFIG; - } - return run(); -} - - -#if defined(POCO_WIN32_UTF8) && !defined(POCO_NO_WSTRING) -int ServerApplication::run(int argc, wchar_t** argv) -{ - try - { - init(argc, argv); - } - catch (Exception& exc) - { - logger().log(exc); - return EXIT_CONFIG; - } - return run(); -} -#endif - - -#endif // _WIN32_WCE -#elif defined(POCO_VXWORKS) -// -// VxWorks specific code -// -void ServerApplication::waitForTerminationRequest() -{ - _terminate.wait(); -} - - -int ServerApplication::run(int argc, char** argv) -{ - try - { - init(argc, argv); - } - catch (Exception& exc) - { - logger().log(exc); - return EXIT_CONFIG; - } - return run(); -} - - -int ServerApplication::run(const std::vector<std::string>& args) -{ - try - { - init(args); - } - catch (Exception& exc) - { - logger().log(exc); - return EXIT_CONFIG; - } - return run(); -} - - -void ServerApplication::defineOptions(OptionSet& options) -{ - Application::defineOptions(options); -} - - -#elif defined(POCO_OS_FAMILY_UNIX) - - -// -// Unix specific code -// -void ServerApplication::waitForTerminationRequest() -{ -#if POCO_OS != POCO_OS_ANDROID - sigset_t sset; - sigemptyset(&sset); - if (!std::getenv("POCO_ENABLE_DEBUGGER")) - { - sigaddset(&sset, SIGINT); - } - sigaddset(&sset, SIGQUIT); - sigaddset(&sset, SIGTERM); - sigprocmask(SIG_BLOCK, &sset, NULL); - int sig; - sigwait(&sset, &sig); -#else // POCO_OS != POCO_OS_ANDROID - _terminate.wait(); -#endif -} - - -int ServerApplication::run(int argc, char** argv) -{ - bool runAsDaemon = isDaemon(argc, argv); - if (runAsDaemon) - { - beDaemon(); - } - try - { - init(argc, argv); - if (runAsDaemon) - { - int rc = chdir("/"); - if (rc != 0) return EXIT_OSERR; - } - } - catch (Exception& exc) - { - logger().log(exc); - return EXIT_CONFIG; - } - return run(); -} - - -int ServerApplication::run(const std::vector<std::string>& args) -{ - bool runAsDaemon = false; - for (std::vector<std::string>::const_iterator it = args.begin(); it != args.end(); ++it) - { - if (*it == "--daemon") - { - runAsDaemon = true; - break; - } - } - if (runAsDaemon) - { - beDaemon(); - } - try - { - init(args); - if (runAsDaemon) - { - int rc = chdir("/"); - if (rc != 0) return EXIT_OSERR; - } - } - catch (Exception& exc) - { - logger().log(exc); - return EXIT_CONFIG; - } - return run(); -} - - -bool ServerApplication::isDaemon(int argc, char** argv) -{ - std::string option("--daemon"); - for (int i = 1; i < argc; ++i) - { - if (option == argv[i]) - return true; - } - return false; -} - - -void ServerApplication::beDaemon() -{ -#if !defined(POCO_NO_FORK_EXEC) - pid_t pid; - if ((pid = fork()) < 0) - throw SystemException("cannot fork daemon process"); - else if (pid != 0) - exit(0); - - setsid(); - umask(027); - - // attach stdin, stdout, stderr to /dev/null - // instead of just closing them. This avoids - // issues with third party/legacy code writing - // stuff to stdout/stderr. - FILE* fin = freopen("/dev/null", "r+", stdin); - if (!fin) throw Poco::OpenFileException("Cannot attach stdin to /dev/null"); - FILE* fout = freopen("/dev/null", "r+", stdout); - if (!fout) throw Poco::OpenFileException("Cannot attach stdout to /dev/null"); - FILE* ferr = freopen("/dev/null", "r+", stderr); - if (!ferr) throw Poco::OpenFileException("Cannot attach stderr to /dev/null"); -#else - throw Poco::NotImplementedException("platform does not allow fork/exec"); -#endif -} - - -void ServerApplication::defineOptions(OptionSet& options) -{ - Application::defineOptions(options); - - options.addOption( - Option("daemon", "", "Run application as a daemon.") - .required(false) - .repeatable(false) - .callback(OptionCallback<ServerApplication>(this, &ServerApplication::handleDaemon))); - - options.addOption( - Option("umask", "", "Set the daemon's umask (octal, e.g. 027).") - .required(false) - .repeatable(false) - .argument("mask") - .callback(OptionCallback<ServerApplication>(this, &ServerApplication::handleUMask))); - - options.addOption( - Option("pidfile", "", "Write the process ID of the application to given file.") - .required(false) - .repeatable(false) - .argument("path") - .callback(OptionCallback<ServerApplication>(this, &ServerApplication::handlePidFile))); -} - - -void ServerApplication::handleDaemon(const std::string& name, const std::string& value) -{ - config().setBool("application.runAsDaemon", true); -} - - -void ServerApplication::handleUMask(const std::string& name, const std::string& value) -{ - int mask = 0; - for (std::string::const_iterator it = value.begin(); it != value.end(); ++it) - { - mask *= 8; - if (*it >= '0' && *it <= '7') - mask += *it - '0'; - else - throw Poco::InvalidArgumentException("umask contains non-octal characters", value); - } - umask(mask); -} - - -void ServerApplication::handlePidFile(const std::string& name, const std::string& value) -{ - Poco::FileOutputStream ostr(value); - if (ostr.good()) - ostr << Poco::Process::id() << std::endl; - else - throw Poco::CreateFileException("Cannot write PID to file", value); - Poco::TemporaryFile::registerForDeletion(value); -} - - -#endif - - -} } // namespace Poco::Util +// +// ServerApplication.cpp +// +// Library: Util +// Package: Application +// Module: ServerApplication +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#include "Poco/Util/ServerApplication.h" +#include "Poco/Util/Option.h" +#include "Poco/Util/OptionSet.h" +#include "Poco/Util/OptionException.h" +#include "Poco/FileStream.h" +#include "Poco/Exception.h" +#if !defined(POCO_VXWORKS) +#include "Poco/Process.h" +#include "Poco/NamedEvent.h" +#endif +#include "Poco/NumberFormatter.h" +#include "Poco/Logger.h" +#include "Poco/String.h" +#if defined(POCO_OS_FAMILY_UNIX) && !defined(POCO_VXWORKS) +#include "Poco/TemporaryFile.h" +#include <stdlib.h> +#include <unistd.h> +#include <stdio.h> +#include <signal.h> +#include <sys/stat.h> +#include <fstream> +#elif defined(POCO_OS_FAMILY_WINDOWS) +#if !defined(_WIN32_WCE) +#include "Poco/Util/WinService.h" +#include "Poco/Util/WinRegistryKey.h" +#endif +#include "Poco/UnWindows.h" +#include <cstring> +#endif +#if defined(POCO_WIN32_UTF8) && !defined(POCO_NO_WSTRING) +#include "Poco/UnicodeConverter.h" +#endif + + +using Poco::NumberFormatter; +using Poco::Exception; +using Poco::SystemException; + + +namespace Poco { +namespace Util { + + +#if defined(POCO_OS_FAMILY_WINDOWS) +Poco::NamedEvent ServerApplication::_terminate(Poco::ProcessImpl::terminationEventName(Poco::Process::id())); +#if !defined(_WIN32_WCE) +Poco::Event ServerApplication::_terminated; +SERVICE_STATUS ServerApplication::_serviceStatus; +SERVICE_STATUS_HANDLE ServerApplication::_serviceStatusHandle = 0; +#endif +#endif +#if defined(POCO_VXWORKS) || POCO_OS == POCO_OS_ANDROID +Poco::Event ServerApplication::_terminate; +#endif + + +ServerApplication::ServerApplication() +{ +#if defined(POCO_OS_FAMILY_WINDOWS) +#if !defined(_WIN32_WCE) + _action = SRV_RUN; + std::memset(&_serviceStatus, 0, sizeof(_serviceStatus)); +#endif +#endif +} + + +ServerApplication::~ServerApplication() +{ +} + + +bool ServerApplication::isInteractive() const +{ + bool runsInBackground = config().getBool("application.runAsDaemon", false) || config().getBool("application.runAsService", false); + return !runsInBackground; +} + + +int ServerApplication::run() +{ + return Application::run(); +} + + +void ServerApplication::terminate() +{ +#if defined(POCO_OS_FAMILY_WINDOWS) + _terminate.set(); +#elif defined(POCO_VXWORKS) || POCO_OS == POCO_OS_ANDROID + _terminate.set(); +#else + Poco::Process::requestTermination(Process::id()); +#endif +} + + +#if defined(POCO_OS_FAMILY_WINDOWS) +#if !defined(_WIN32_WCE) + + +// +// Windows specific code +// +BOOL ServerApplication::ConsoleCtrlHandler(DWORD ctrlType) +{ + switch (ctrlType) + { + case CTRL_C_EVENT: + case CTRL_CLOSE_EVENT: + case CTRL_BREAK_EVENT: + terminate(); + return _terminated.tryWait(10000) ? TRUE : FALSE; + default: + return FALSE; + } +} + + +void ServerApplication::ServiceControlHandler(DWORD control) +{ + switch (control) + { + case SERVICE_CONTROL_STOP: + case SERVICE_CONTROL_SHUTDOWN: + terminate(); + _serviceStatus.dwCurrentState = SERVICE_STOP_PENDING; + break; + case SERVICE_CONTROL_INTERROGATE: + break; + } + SetServiceStatus(_serviceStatusHandle, &_serviceStatus); +} + + +#if defined(POCO_WIN32_UTF8) && !defined(POCO_NO_WSTRING) +void ServerApplication::ServiceMain(DWORD argc, LPWSTR* argv) +#else +void ServerApplication::ServiceMain(DWORD argc, LPTSTR* argv) +#endif +{ + ServerApplication& app = static_cast<ServerApplication&>(Application::instance()); + + app.config().setBool("application.runAsService", true); + +#if defined(POCO_WIN32_UTF8) && !defined(POCO_NO_WSTRING) + _serviceStatusHandle = RegisterServiceCtrlHandlerW(L"", ServiceControlHandler); +#else + _serviceStatusHandle = RegisterServiceCtrlHandlerA("", ServiceControlHandler); +#endif + if (!_serviceStatusHandle) + throw SystemException("cannot register service control handler"); + + _serviceStatus.dwServiceType = SERVICE_WIN32; + _serviceStatus.dwCurrentState = SERVICE_START_PENDING; + _serviceStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN; + _serviceStatus.dwWin32ExitCode = 0; + _serviceStatus.dwServiceSpecificExitCode = 0; + _serviceStatus.dwCheckPoint = 0; + _serviceStatus.dwWaitHint = 0; + SetServiceStatus(_serviceStatusHandle, &_serviceStatus); + + try + { +#if defined(POCO_WIN32_UTF8) && !defined(POCO_NO_WSTRING) + std::vector<std::string> args; + for (DWORD i = 0; i < argc; ++i) + { + std::string arg; + Poco::UnicodeConverter::toUTF8(argv[i], arg); + args.push_back(arg); + } + app.init(args); +#else + app.init(argc, argv); +#endif + _serviceStatus.dwCurrentState = SERVICE_RUNNING; + SetServiceStatus(_serviceStatusHandle, &_serviceStatus); + int rc = app.run(); + _serviceStatus.dwWin32ExitCode = rc ? ERROR_SERVICE_SPECIFIC_ERROR : 0; + _serviceStatus.dwServiceSpecificExitCode = rc; + } + catch (Exception& exc) + { + app.logger().log(exc); + _serviceStatus.dwWin32ExitCode = ERROR_SERVICE_SPECIFIC_ERROR; + _serviceStatus.dwServiceSpecificExitCode = EXIT_CONFIG; + } + catch (...) + { + app.logger().error("fatal error - aborting"); + _serviceStatus.dwWin32ExitCode = ERROR_SERVICE_SPECIFIC_ERROR; + _serviceStatus.dwServiceSpecificExitCode = EXIT_SOFTWARE; + } + _serviceStatus.dwCurrentState = SERVICE_STOPPED; + SetServiceStatus(_serviceStatusHandle, &_serviceStatus); +} + + +void ServerApplication::waitForTerminationRequest() +{ + SetConsoleCtrlHandler(ConsoleCtrlHandler, TRUE); + _terminate.wait(); + _terminated.set(); +} + + +int ServerApplication::run(int argc, char** argv) +{ + if (!hasConsole() && isService()) + { + return 0; + } + else + { + int rc = EXIT_OK; + try + { + init(argc, argv); + switch (_action) + { + case SRV_REGISTER: + registerService(); + rc = EXIT_OK; + break; + case SRV_UNREGISTER: + unregisterService(); + rc = EXIT_OK; + break; + default: + rc = run(); + } + } + catch (Exception& exc) + { + logger().log(exc); + rc = EXIT_SOFTWARE; + } + return rc; + } +} + + +int ServerApplication::run(const std::vector<std::string>& args) +{ + if (!hasConsole() && isService()) + { + return 0; + } + else + { + int rc = EXIT_OK; + try + { + init(args); + switch (_action) + { + case SRV_REGISTER: + registerService(); + rc = EXIT_OK; + break; + case SRV_UNREGISTER: + unregisterService(); + rc = EXIT_OK; + break; + default: + rc = run(); + } + } + catch (Exception& exc) + { + logger().log(exc); + rc = EXIT_SOFTWARE; + } + return rc; + } +} + + +#if defined(POCO_WIN32_UTF8) && !defined(POCO_NO_WSTRING) +int ServerApplication::run(int argc, wchar_t** argv) +{ + if (!hasConsole() && isService()) + { + return 0; + } + else + { + int rc = EXIT_OK; + try + { + init(argc, argv); + switch (_action) + { + case SRV_REGISTER: + registerService(); + rc = EXIT_OK; + break; + case SRV_UNREGISTER: + unregisterService(); + rc = EXIT_OK; + break; + default: + rc = run(); + } + } + catch (Exception& exc) + { + logger().log(exc); + rc = EXIT_SOFTWARE; + } + return rc; + } +} +#endif + + +bool ServerApplication::isService() +{ +#if defined(POCO_WIN32_UTF8) && !defined(POCO_NO_WSTRING) + SERVICE_TABLE_ENTRYW svcDispatchTable[2]; + svcDispatchTable[0].lpServiceName = L""; + svcDispatchTable[0].lpServiceProc = ServiceMain; + svcDispatchTable[1].lpServiceName = NULL; + svcDispatchTable[1].lpServiceProc = NULL; + return StartServiceCtrlDispatcherW(svcDispatchTable) != 0; +#else + SERVICE_TABLE_ENTRY svcDispatchTable[2]; + svcDispatchTable[0].lpServiceName = ""; + svcDispatchTable[0].lpServiceProc = ServiceMain; + svcDispatchTable[1].lpServiceName = NULL; + svcDispatchTable[1].lpServiceProc = NULL; + return StartServiceCtrlDispatcherA(svcDispatchTable) != 0; +#endif +} + + +bool ServerApplication::hasConsole() +{ + HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE); + return hStdOut != INVALID_HANDLE_VALUE && hStdOut != NULL; +} + + +void ServerApplication::registerService() +{ + std::string name = config().getString("application.baseName"); + std::string path = config().getString("application.path"); + + WinService service(name); + if (_displayName.empty()) + service.registerService(path); + else + service.registerService(path, _displayName); + if (_startup == "auto") + service.setStartup(WinService::SVC_AUTO_START); + else if (_startup == "manual") + service.setStartup(WinService::SVC_MANUAL_START); + if (!_description.empty()) + service.setDescription(_description); + logger().information("The application has been successfully registered as a service."); +} + + +void ServerApplication::unregisterService() +{ + std::string name = config().getString("application.baseName"); + + WinService service(name); + service.unregisterService(); + logger().information("The service has been successfully unregistered."); +} + + +void ServerApplication::defineOptions(OptionSet& options) +{ + Application::defineOptions(options); + + options.addOption( + Option("registerService", "", "Register the application as a service.") + .required(false) + .repeatable(false) + .callback(OptionCallback<ServerApplication>(this, &ServerApplication::handleRegisterService))); + + options.addOption( + Option("unregisterService", "", "Unregister the application as a service.") + .required(false) + .repeatable(false) + .callback(OptionCallback<ServerApplication>(this, &ServerApplication::handleUnregisterService))); + + options.addOption( + Option("displayName", "", "Specify a display name for the service (only with /registerService).") + .required(false) + .repeatable(false) + .argument("name") + .callback(OptionCallback<ServerApplication>(this, &ServerApplication::handleDisplayName))); + + options.addOption( + Option("description", "", "Specify a description for the service (only with /registerService).") + .required(false) + .repeatable(false) + .argument("text") + .callback(OptionCallback<ServerApplication>(this, &ServerApplication::handleDescription))); + + options.addOption( + Option("startup", "", "Specify the startup mode for the service (only with /registerService).") + .required(false) + .repeatable(false) + .argument("automatic|manual") + .callback(OptionCallback<ServerApplication>(this, &ServerApplication::handleStartup))); +} + + +void ServerApplication::handleRegisterService(const std::string& /*name*/, const std::string& /*value*/) +{ + _action = SRV_REGISTER; +} + + +void ServerApplication::handleUnregisterService(const std::string& /*name*/, const std::string& /*value*/) +{ + _action = SRV_UNREGISTER; +} + + +void ServerApplication::handleDisplayName(const std::string& /*name*/, const std::string& value) +{ + _displayName = value; +} + + +void ServerApplication::handleDescription(const std::string& /*name*/, const std::string& value) +{ + _description = value; +} + + +void ServerApplication::handleStartup(const std::string& /*name*/, const std::string& value) +{ + if (Poco::icompare(value, 4, std::string("auto")) == 0) + _startup = "auto"; + else if (Poco::icompare(value, std::string("manual")) == 0) + _startup = "manual"; + else + throw InvalidArgumentException("argument to startup option must be 'auto[matic]' or 'manual'"); +} + + +#else // _WIN32_WCE +void ServerApplication::waitForTerminationRequest() +{ + _terminate.wait(); +} + + +int ServerApplication::run(int argc, char** argv) +{ + try + { + init(argc, argv); + } + catch (Exception& exc) + { + logger().log(exc); + return EXIT_CONFIG; + } + return run(); +} + + +int ServerApplication::run(const std::vector<std::string>& args) +{ + try + { + init(args); + } + catch (Exception& exc) + { + logger().log(exc); + return EXIT_CONFIG; + } + return run(); +} + + +#if defined(POCO_WIN32_UTF8) && !defined(POCO_NO_WSTRING) +int ServerApplication::run(int argc, wchar_t** argv) +{ + try + { + init(argc, argv); + } + catch (Exception& exc) + { + logger().log(exc); + return EXIT_CONFIG; + } + return run(); +} +#endif + + +#endif // _WIN32_WCE +#elif defined(POCO_VXWORKS) +// +// VxWorks specific code +// +void ServerApplication::waitForTerminationRequest() +{ + _terminate.wait(); +} + + +int ServerApplication::run(int argc, char** argv) +{ + try + { + init(argc, argv); + } + catch (Exception& exc) + { + logger().log(exc); + return EXIT_CONFIG; + } + return run(); +} + + +int ServerApplication::run(const std::vector<std::string>& args) +{ + try + { + init(args); + } + catch (Exception& exc) + { + logger().log(exc); + return EXIT_CONFIG; + } + return run(); +} + + +void ServerApplication::defineOptions(OptionSet& options) +{ + Application::defineOptions(options); +} + + +#elif defined(POCO_OS_FAMILY_UNIX) + + +// +// Unix specific code +// +void ServerApplication::waitForTerminationRequest() +{ +#if POCO_OS != POCO_OS_ANDROID + sigset_t sset; + sigemptyset(&sset); + if (!std::getenv("POCO_ENABLE_DEBUGGER")) + { + sigaddset(&sset, SIGINT); + } + sigaddset(&sset, SIGQUIT); + sigaddset(&sset, SIGTERM); + sigprocmask(SIG_BLOCK, &sset, NULL); + int sig; + sigwait(&sset, &sig); +#else // POCO_OS != POCO_OS_ANDROID + _terminate.wait(); +#endif +} + + +int ServerApplication::run(int argc, char** argv) +{ + bool runAsDaemon = isDaemon(argc, argv); + if (runAsDaemon) + { + beDaemon(); + } + try + { + init(argc, argv); + if (runAsDaemon) + { + int rc = chdir("/"); + if (rc != 0) return EXIT_OSERR; + } + } + catch (Exception& exc) + { + logger().log(exc); + return EXIT_CONFIG; + } + return run(); +} + + +int ServerApplication::run(const std::vector<std::string>& args) +{ + bool runAsDaemon = false; + for (std::vector<std::string>::const_iterator it = args.begin(); it != args.end(); ++it) + { + if (*it == "--daemon") + { + runAsDaemon = true; + break; + } + } + if (runAsDaemon) + { + beDaemon(); + } + try + { + init(args); + if (runAsDaemon) + { + int rc = chdir("/"); + if (rc != 0) return EXIT_OSERR; + } + } + catch (Exception& exc) + { + logger().log(exc); + return EXIT_CONFIG; + } + return run(); +} + + +bool ServerApplication::isDaemon(int argc, char** argv) +{ + std::string option("--daemon"); + for (int i = 1; i < argc; ++i) + { + if (option == argv[i]) + return true; + } + return false; +} + + +void ServerApplication::beDaemon() +{ +#if !defined(POCO_NO_FORK_EXEC) + pid_t pid; + if ((pid = fork()) < 0) + throw SystemException("cannot fork daemon process"); + else if (pid != 0) + exit(0); + + setsid(); + umask(027); + + // attach stdin, stdout, stderr to /dev/null + // instead of just closing them. This avoids + // issues with third party/legacy code writing + // stuff to stdout/stderr. + FILE* fin = freopen("/dev/null", "r+", stdin); + if (!fin) throw Poco::OpenFileException("Cannot attach stdin to /dev/null"); + FILE* fout = freopen("/dev/null", "r+", stdout); + if (!fout) throw Poco::OpenFileException("Cannot attach stdout to /dev/null"); + FILE* ferr = freopen("/dev/null", "r+", stderr); + if (!ferr) throw Poco::OpenFileException("Cannot attach stderr to /dev/null"); +#else + throw Poco::NotImplementedException("platform does not allow fork/exec"); +#endif +} + + +void ServerApplication::defineOptions(OptionSet& options) +{ + Application::defineOptions(options); + + options.addOption( + Option("daemon", "", "Run application as a daemon.") + .required(false) + .repeatable(false) + .callback(OptionCallback<ServerApplication>(this, &ServerApplication::handleDaemon))); + + options.addOption( + Option("umask", "", "Set the daemon's umask (octal, e.g. 027).") + .required(false) + .repeatable(false) + .argument("mask") + .callback(OptionCallback<ServerApplication>(this, &ServerApplication::handleUMask))); + + options.addOption( + Option("pidfile", "", "Write the process ID of the application to given file.") + .required(false) + .repeatable(false) + .argument("path") + .callback(OptionCallback<ServerApplication>(this, &ServerApplication::handlePidFile))); +} + + +void ServerApplication::handleDaemon(const std::string& name, const std::string& value) +{ + config().setBool("application.runAsDaemon", true); +} + + +void ServerApplication::handleUMask(const std::string& name, const std::string& value) +{ + int mask = 0; + for (std::string::const_iterator it = value.begin(); it != value.end(); ++it) + { + mask *= 8; + if (*it >= '0' && *it <= '7') + mask += *it - '0'; + else + throw Poco::InvalidArgumentException("umask contains non-octal characters", value); + } + umask(mask); +} + + +void ServerApplication::handlePidFile(const std::string& name, const std::string& value) +{ + Poco::FileOutputStream ostr(value); + if (ostr.good()) + ostr << Poco::Process::id() << std::endl; + else + throw Poco::CreateFileException("Cannot write PID to file", value); + Poco::TemporaryFile::registerForDeletion(value); +} + + +#endif + + +} } // namespace Poco::Util diff --git a/contrib/libs/poco/Util/src/Subsystem.cpp b/contrib/libs/poco/Util/src/Subsystem.cpp index bb11856f5e..5e6ed6c732 100644 --- a/contrib/libs/poco/Util/src/Subsystem.cpp +++ b/contrib/libs/poco/Util/src/Subsystem.cpp @@ -1,44 +1,44 @@ -// -// Subsystem.cpp -// -// Library: Util -// Package: Application -// Module: Subsystem -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// SPDX-License-Identifier: BSL-1.0 -// - - -#include "Poco/Util/Subsystem.h" - - -namespace Poco { -namespace Util { - - -Subsystem::Subsystem() -{ -} - - -Subsystem::~Subsystem() -{ -} - - -void Subsystem::reinitialize(Application& app) -{ - uninitialize(); - initialize(app); -} - - -void Subsystem::defineOptions(OptionSet& /*options*/) -{ -} - - -} } // namespace Poco::Util +// +// Subsystem.cpp +// +// Library: Util +// Package: Application +// Module: Subsystem +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#include "Poco/Util/Subsystem.h" + + +namespace Poco { +namespace Util { + + +Subsystem::Subsystem() +{ +} + + +Subsystem::~Subsystem() +{ +} + + +void Subsystem::reinitialize(Application& app) +{ + uninitialize(); + initialize(app); +} + + +void Subsystem::defineOptions(OptionSet& /*options*/) +{ +} + + +} } // namespace Poco::Util diff --git a/contrib/libs/poco/Util/src/SystemConfiguration.cpp b/contrib/libs/poco/Util/src/SystemConfiguration.cpp index ed0b54150a..f0a4156472 100644 --- a/contrib/libs/poco/Util/src/SystemConfiguration.cpp +++ b/contrib/libs/poco/Util/src/SystemConfiguration.cpp @@ -1,212 +1,212 @@ -// -// SystemConfiguration.cpp -// -// Library: Util -// Package: Configuration -// Module: SystemConfiguration -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// SPDX-License-Identifier: BSL-1.0 -// - - -#include "Poco/Util/SystemConfiguration.h" -#include "Poco/Environment.h" -#include "Poco/Path.h" -#include "Poco/DateTime.h" -#include "Poco/DateTimeFormatter.h" -#include "Poco/DateTimeFormat.h" -#include "Poco/NumberFormatter.h" -#if !defined(POCO_VXWORKS) -#include "Poco/Process.h" -#endif -#include "Poco/Exception.h" -#include <cstdio> - - -using Poco::Environment; -using Poco::Path; - - -namespace Poco { -namespace Util { - - -const std::string SystemConfiguration::OSNAME = "system.osName"; -const std::string SystemConfiguration::OSVERSION = "system.osVersion"; -const std::string SystemConfiguration::OSARCHITECTURE = "system.osArchitecture"; -const std::string SystemConfiguration::NODENAME = "system.nodeName"; -const std::string SystemConfiguration::NODEID = "system.nodeId"; -const std::string SystemConfiguration::CURRENTDIR = "system.currentDir"; -const std::string SystemConfiguration::HOMEDIR = "system.homeDir"; -const std::string SystemConfiguration::CONFIGHOMEDIR = "system.configHomeDir"; -const std::string SystemConfiguration::CACHEHOMEDIR = "system.cacheHomeDir"; -const std::string SystemConfiguration::DATAHOMEDIR = "system.dataHomeDir"; -const std::string SystemConfiguration::TEMPHOMEDIR = "system.tempHomeDir"; -const std::string SystemConfiguration::TEMPDIR = "system.tempDir"; -const std::string SystemConfiguration::CONFIGDIR = "system.configDir"; -const std::string SystemConfiguration::DATETIME = "system.dateTime"; -#if !defined(POCO_VXWORKS) -const std::string SystemConfiguration::PID = "system.pid"; -#endif -const std::string SystemConfiguration::ENV = "system.env."; - - -SystemConfiguration::SystemConfiguration() -{ -} - - -SystemConfiguration::~SystemConfiguration() -{ -} - - -bool SystemConfiguration::getRaw(const std::string& key, std::string& value) const -{ - if (key == OSNAME) - { - value = Environment::osName(); - } - else if (key == OSVERSION) - { - value = Environment::osVersion(); - } - else if (key == OSARCHITECTURE) - { - value = Environment::osArchitecture(); - } - else if (key == NODENAME) - { - value = Environment::nodeName(); - } - else if (key == NODEID) - { - try - { - Poco::Environment::NodeId id; - Poco::Environment::nodeId(id); - char result[13]; - std::sprintf(result, "%02x%02x%02x%02x%02x%02x", - id[0], - id[1], - id[2], - id[3], - id[4], - id[5]); - value = result; - } - catch (...) - { - value = "000000000000"; - } - } - else if (key == CURRENTDIR) - { - value = Path::current(); - } - else if (key == HOMEDIR) - { - value = Path::home(); - } - else if (key == CONFIGHOMEDIR) - { - value = Path::configHome(); - } - else if (key == CACHEHOMEDIR) - { - value = Path::cacheHome(); - } - else if (key == DATAHOMEDIR) - { - value = Path::dataHome(); - } - - else if (key == TEMPHOMEDIR) - { - value = Path::tempHome(); - } - else if (key == TEMPDIR) - { - value = Path::temp(); - } - else if (key == CONFIGDIR) - { - value = Path::config(); - } - else if (key == DATETIME) - { - value = Poco::DateTimeFormatter::format(Poco::DateTime(), Poco::DateTimeFormat::ISO8601_FORMAT); - } -#if !defined(POCO_VXWORKS) - else if (key == PID) - { - value = "0"; - value = Poco::NumberFormatter::format(Poco::Process::id()); - } -#endif - else if (key.compare(0, ENV.size(), ENV) == 0) - { - return getEnv(key.substr(ENV.size()), value); - } - else return false; - return true; -} - - -void SystemConfiguration::setRaw(const std::string& key, const std::string& /*value*/) -{ - throw Poco::InvalidAccessException("Attempt to modify a system property", key); -} - - -void SystemConfiguration::enumerate(const std::string& key, Keys& range) const -{ - if (key.empty()) - { - range.push_back("system"); - } - else if (key == "system") - { - range.push_back("osName"); - range.push_back("osVersion"); - range.push_back("osArchitecture"); - range.push_back("nodeName"); - range.push_back("nodeId"); - range.push_back("currentDir"); - range.push_back("homeDir"); - range.push_back("configHomeDir"); - range.push_back("cacheHomeDir"); - range.push_back("dataHomeDir"); - range.push_back("tempHomeDir"); - range.push_back("tempDir"); - range.push_back("configDir"); - range.push_back("dateTime"); -#if !defined(POCO_VXWORKS) - range.push_back("pid"); -#endif - range.push_back("env"); - } -} - - -void SystemConfiguration::removeRaw(const std::string& /*key*/) -{ - throw Poco::NotImplementedException("Removing a key in a SystemConfiguration"); -} - - -bool SystemConfiguration::getEnv(const std::string& name, std::string& value) -{ - if (Environment::has(name)) - { - value = Environment::get(name); - return true; - } - return false; -} - - -} } // namespace Poco::Util +// +// SystemConfiguration.cpp +// +// Library: Util +// Package: Configuration +// Module: SystemConfiguration +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#include "Poco/Util/SystemConfiguration.h" +#include "Poco/Environment.h" +#include "Poco/Path.h" +#include "Poco/DateTime.h" +#include "Poco/DateTimeFormatter.h" +#include "Poco/DateTimeFormat.h" +#include "Poco/NumberFormatter.h" +#if !defined(POCO_VXWORKS) +#include "Poco/Process.h" +#endif +#include "Poco/Exception.h" +#include <cstdio> + + +using Poco::Environment; +using Poco::Path; + + +namespace Poco { +namespace Util { + + +const std::string SystemConfiguration::OSNAME = "system.osName"; +const std::string SystemConfiguration::OSVERSION = "system.osVersion"; +const std::string SystemConfiguration::OSARCHITECTURE = "system.osArchitecture"; +const std::string SystemConfiguration::NODENAME = "system.nodeName"; +const std::string SystemConfiguration::NODEID = "system.nodeId"; +const std::string SystemConfiguration::CURRENTDIR = "system.currentDir"; +const std::string SystemConfiguration::HOMEDIR = "system.homeDir"; +const std::string SystemConfiguration::CONFIGHOMEDIR = "system.configHomeDir"; +const std::string SystemConfiguration::CACHEHOMEDIR = "system.cacheHomeDir"; +const std::string SystemConfiguration::DATAHOMEDIR = "system.dataHomeDir"; +const std::string SystemConfiguration::TEMPHOMEDIR = "system.tempHomeDir"; +const std::string SystemConfiguration::TEMPDIR = "system.tempDir"; +const std::string SystemConfiguration::CONFIGDIR = "system.configDir"; +const std::string SystemConfiguration::DATETIME = "system.dateTime"; +#if !defined(POCO_VXWORKS) +const std::string SystemConfiguration::PID = "system.pid"; +#endif +const std::string SystemConfiguration::ENV = "system.env."; + + +SystemConfiguration::SystemConfiguration() +{ +} + + +SystemConfiguration::~SystemConfiguration() +{ +} + + +bool SystemConfiguration::getRaw(const std::string& key, std::string& value) const +{ + if (key == OSNAME) + { + value = Environment::osName(); + } + else if (key == OSVERSION) + { + value = Environment::osVersion(); + } + else if (key == OSARCHITECTURE) + { + value = Environment::osArchitecture(); + } + else if (key == NODENAME) + { + value = Environment::nodeName(); + } + else if (key == NODEID) + { + try + { + Poco::Environment::NodeId id; + Poco::Environment::nodeId(id); + char result[13]; + std::sprintf(result, "%02x%02x%02x%02x%02x%02x", + id[0], + id[1], + id[2], + id[3], + id[4], + id[5]); + value = result; + } + catch (...) + { + value = "000000000000"; + } + } + else if (key == CURRENTDIR) + { + value = Path::current(); + } + else if (key == HOMEDIR) + { + value = Path::home(); + } + else if (key == CONFIGHOMEDIR) + { + value = Path::configHome(); + } + else if (key == CACHEHOMEDIR) + { + value = Path::cacheHome(); + } + else if (key == DATAHOMEDIR) + { + value = Path::dataHome(); + } + + else if (key == TEMPHOMEDIR) + { + value = Path::tempHome(); + } + else if (key == TEMPDIR) + { + value = Path::temp(); + } + else if (key == CONFIGDIR) + { + value = Path::config(); + } + else if (key == DATETIME) + { + value = Poco::DateTimeFormatter::format(Poco::DateTime(), Poco::DateTimeFormat::ISO8601_FORMAT); + } +#if !defined(POCO_VXWORKS) + else if (key == PID) + { + value = "0"; + value = Poco::NumberFormatter::format(Poco::Process::id()); + } +#endif + else if (key.compare(0, ENV.size(), ENV) == 0) + { + return getEnv(key.substr(ENV.size()), value); + } + else return false; + return true; +} + + +void SystemConfiguration::setRaw(const std::string& key, const std::string& /*value*/) +{ + throw Poco::InvalidAccessException("Attempt to modify a system property", key); +} + + +void SystemConfiguration::enumerate(const std::string& key, Keys& range) const +{ + if (key.empty()) + { + range.push_back("system"); + } + else if (key == "system") + { + range.push_back("osName"); + range.push_back("osVersion"); + range.push_back("osArchitecture"); + range.push_back("nodeName"); + range.push_back("nodeId"); + range.push_back("currentDir"); + range.push_back("homeDir"); + range.push_back("configHomeDir"); + range.push_back("cacheHomeDir"); + range.push_back("dataHomeDir"); + range.push_back("tempHomeDir"); + range.push_back("tempDir"); + range.push_back("configDir"); + range.push_back("dateTime"); +#if !defined(POCO_VXWORKS) + range.push_back("pid"); +#endif + range.push_back("env"); + } +} + + +void SystemConfiguration::removeRaw(const std::string& /*key*/) +{ + throw Poco::NotImplementedException("Removing a key in a SystemConfiguration"); +} + + +bool SystemConfiguration::getEnv(const std::string& name, std::string& value) +{ + if (Environment::has(name)) + { + value = Environment::get(name); + return true; + } + return false; +} + + +} } // namespace Poco::Util diff --git a/contrib/libs/poco/Util/src/Timer.cpp b/contrib/libs/poco/Util/src/Timer.cpp index 8d4a95abff..3de4821c16 100644 --- a/contrib/libs/poco/Util/src/Timer.cpp +++ b/contrib/libs/poco/Util/src/Timer.cpp @@ -1,351 +1,351 @@ -// -// Timer.cpp -// -// Library: Util -// Package: Timer -// Module: Timer -// -// Copyright (c) 2009, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// SPDX-License-Identifier: BSL-1.0 -// - - -#include "Poco/Util/Timer.h" -#include "Poco/Notification.h" -#include "Poco/ErrorHandler.h" -#include "Poco/Event.h" - - -using Poco::ErrorHandler; - - -namespace Poco { -namespace Util { - - -class TimerNotification: public Poco::Notification -{ -public: - TimerNotification(Poco::TimedNotificationQueue& queue): - _queue(queue) - { - } - - ~TimerNotification() - { - } - - virtual bool execute() = 0; - - Poco::TimedNotificationQueue& queue() - { - return _queue; - } - -private: - Poco::TimedNotificationQueue& _queue; -}; - - -class StopNotification: public TimerNotification -{ -public: - StopNotification(Poco::TimedNotificationQueue& queue): - TimerNotification(queue) - { - } - - ~StopNotification() - { - } - - bool execute() - { - queue().clear(); - return false; - } -}; - - -class CancelNotification: public TimerNotification -{ -public: - CancelNotification(Poco::TimedNotificationQueue& queue): - TimerNotification(queue) - { - } - - ~CancelNotification() - { - } - - bool execute() - { - // Check if there's a StopNotification pending. - Poco::AutoPtr<TimerNotification> pNf = static_cast<TimerNotification*>(queue().dequeueNotification()); - while (pNf) - { - if (pNf.cast<StopNotification>()) - { - queue().clear(); - _finished.set(); - return false; - } - pNf = static_cast<TimerNotification*>(queue().dequeueNotification()); - } - - queue().clear(); - _finished.set(); - return true; - } - - void wait() - { - _finished.wait(); - } - -private: - Poco::Event _finished; -}; - - -class TaskNotification: public TimerNotification -{ -public: - TaskNotification(Poco::TimedNotificationQueue& queue, TimerTask::Ptr pTask): - TimerNotification(queue), - _pTask(pTask) - { - } - - ~TaskNotification() - { - } - - TimerTask::Ptr task() - { - return _pTask; - } - - bool execute() - { - if (!_pTask->isCancelled()) - { - try - { - _pTask->_lastExecution.update(); - _pTask->run(); - } - catch (Exception& exc) - { - ErrorHandler::handle(exc); - } - catch (std::exception& exc) - { - ErrorHandler::handle(exc); - } - catch (...) - { - ErrorHandler::handle(); - } - } - return true; - } - -private: - TimerTask::Ptr _pTask; -}; - - -class PeriodicTaskNotification: public TaskNotification -{ -public: - PeriodicTaskNotification(Poco::TimedNotificationQueue& queue, TimerTask::Ptr pTask, long interval): - TaskNotification(queue, pTask), - _interval(interval) - { - } - - ~PeriodicTaskNotification() - { - } - - bool execute() - { - TaskNotification::execute(); - - if (!task()->isCancelled()) - { - Poco::Clock now; - Poco::Clock nextExecution; - nextExecution += static_cast<Poco::Clock::ClockDiff>(_interval)*1000; - if (nextExecution < now) nextExecution = now; - queue().enqueueNotification(this, nextExecution); - duplicate(); - } - return true; - } - -private: - long _interval; -}; - - -class FixedRateTaskNotification: public TaskNotification -{ -public: - FixedRateTaskNotification(Poco::TimedNotificationQueue& queue, TimerTask::Ptr pTask, long interval, Poco::Clock clock): - TaskNotification(queue, pTask), - _interval(interval), - _nextExecution(clock) - { - } - - ~FixedRateTaskNotification() - { - } - - bool execute() - { - TaskNotification::execute(); - - if (!task()->isCancelled()) - { - Poco::Clock now; - _nextExecution += static_cast<Poco::Clock::ClockDiff>(_interval)*1000; - if (_nextExecution < now) _nextExecution = now; - queue().enqueueNotification(this, _nextExecution); - duplicate(); - } - return true; - } - -private: - long _interval; - Poco::Clock _nextExecution; -}; - - -Timer::Timer() -{ - _thread.start(*this); -} - - -Timer::Timer(Poco::Thread::Priority priority) -{ - _thread.setPriority(priority); - _thread.start(*this); -} - - -Timer::~Timer() -{ - try - { - _queue.enqueueNotification(new StopNotification(_queue), Poco::Clock(0)); - _thread.join(); - } - catch (...) - { - poco_unexpected(); - } -} - - -void Timer::cancel(bool wait) -{ - Poco::AutoPtr<CancelNotification> pNf = new CancelNotification(_queue); - _queue.enqueueNotification(pNf, Poco::Clock(0)); - if (wait) - { - pNf->wait(); - } -} - - -void Timer::schedule(TimerTask::Ptr pTask, Poco::Timestamp time) -{ - validateTask(pTask); - _queue.enqueueNotification(new TaskNotification(_queue, pTask), time); -} - - -void Timer::schedule(TimerTask::Ptr pTask, Poco::Clock clock) -{ - validateTask(pTask); - _queue.enqueueNotification(new TaskNotification(_queue, pTask), clock); -} - - -void Timer::schedule(TimerTask::Ptr pTask, long delay, long interval) -{ - Poco::Clock clock; - clock += static_cast<Poco::Clock::ClockDiff>(delay)*1000; - schedule(pTask, clock, interval); -} - - -void Timer::schedule(TimerTask::Ptr pTask, Poco::Timestamp time, long interval) -{ - validateTask(pTask); - _queue.enqueueNotification(new PeriodicTaskNotification(_queue, pTask, interval), time); -} - - -void Timer::schedule(TimerTask::Ptr pTask, Poco::Clock clock, long interval) -{ - validateTask(pTask); - _queue.enqueueNotification(new PeriodicTaskNotification(_queue, pTask, interval), clock); -} - - -void Timer::scheduleAtFixedRate(TimerTask::Ptr pTask, long delay, long interval) -{ - Poco::Clock clock; - clock += static_cast<Poco::Clock::ClockDiff>(delay)*1000; - scheduleAtFixedRate(pTask, clock, interval); -} - - -void Timer::scheduleAtFixedRate(TimerTask::Ptr pTask, Poco::Timestamp time, long interval) -{ - validateTask(pTask); - Poco::Timestamp tsNow; - Poco::Clock clock; - Poco::Timestamp::TimeDiff diff = time - tsNow; - clock += diff; - _queue.enqueueNotification(new FixedRateTaskNotification(_queue, pTask, interval, clock), clock); -} - - -void Timer::scheduleAtFixedRate(TimerTask::Ptr pTask, Poco::Clock clock, long interval) -{ - validateTask(pTask); - _queue.enqueueNotification(new FixedRateTaskNotification(_queue, pTask, interval, clock), clock); -} - - -void Timer::run() -{ - bool cont = true; - while (cont) - { - Poco::AutoPtr<TimerNotification> pNf = static_cast<TimerNotification*>(_queue.waitDequeueNotification()); - cont = pNf->execute(); - } -} - - -void Timer::validateTask(const TimerTask::Ptr& pTask) -{ - if (pTask->isCancelled()) - { - throw Poco::IllegalStateException("A cancelled task must not be rescheduled"); - } -} - - -} } // namespace Poco::Util +// +// Timer.cpp +// +// Library: Util +// Package: Timer +// Module: Timer +// +// Copyright (c) 2009, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#include "Poco/Util/Timer.h" +#include "Poco/Notification.h" +#include "Poco/ErrorHandler.h" +#include "Poco/Event.h" + + +using Poco::ErrorHandler; + + +namespace Poco { +namespace Util { + + +class TimerNotification: public Poco::Notification +{ +public: + TimerNotification(Poco::TimedNotificationQueue& queue): + _queue(queue) + { + } + + ~TimerNotification() + { + } + + virtual bool execute() = 0; + + Poco::TimedNotificationQueue& queue() + { + return _queue; + } + +private: + Poco::TimedNotificationQueue& _queue; +}; + + +class StopNotification: public TimerNotification +{ +public: + StopNotification(Poco::TimedNotificationQueue& queue): + TimerNotification(queue) + { + } + + ~StopNotification() + { + } + + bool execute() + { + queue().clear(); + return false; + } +}; + + +class CancelNotification: public TimerNotification +{ +public: + CancelNotification(Poco::TimedNotificationQueue& queue): + TimerNotification(queue) + { + } + + ~CancelNotification() + { + } + + bool execute() + { + // Check if there's a StopNotification pending. + Poco::AutoPtr<TimerNotification> pNf = static_cast<TimerNotification*>(queue().dequeueNotification()); + while (pNf) + { + if (pNf.cast<StopNotification>()) + { + queue().clear(); + _finished.set(); + return false; + } + pNf = static_cast<TimerNotification*>(queue().dequeueNotification()); + } + + queue().clear(); + _finished.set(); + return true; + } + + void wait() + { + _finished.wait(); + } + +private: + Poco::Event _finished; +}; + + +class TaskNotification: public TimerNotification +{ +public: + TaskNotification(Poco::TimedNotificationQueue& queue, TimerTask::Ptr pTask): + TimerNotification(queue), + _pTask(pTask) + { + } + + ~TaskNotification() + { + } + + TimerTask::Ptr task() + { + return _pTask; + } + + bool execute() + { + if (!_pTask->isCancelled()) + { + try + { + _pTask->_lastExecution.update(); + _pTask->run(); + } + catch (Exception& exc) + { + ErrorHandler::handle(exc); + } + catch (std::exception& exc) + { + ErrorHandler::handle(exc); + } + catch (...) + { + ErrorHandler::handle(); + } + } + return true; + } + +private: + TimerTask::Ptr _pTask; +}; + + +class PeriodicTaskNotification: public TaskNotification +{ +public: + PeriodicTaskNotification(Poco::TimedNotificationQueue& queue, TimerTask::Ptr pTask, long interval): + TaskNotification(queue, pTask), + _interval(interval) + { + } + + ~PeriodicTaskNotification() + { + } + + bool execute() + { + TaskNotification::execute(); + + if (!task()->isCancelled()) + { + Poco::Clock now; + Poco::Clock nextExecution; + nextExecution += static_cast<Poco::Clock::ClockDiff>(_interval)*1000; + if (nextExecution < now) nextExecution = now; + queue().enqueueNotification(this, nextExecution); + duplicate(); + } + return true; + } + +private: + long _interval; +}; + + +class FixedRateTaskNotification: public TaskNotification +{ +public: + FixedRateTaskNotification(Poco::TimedNotificationQueue& queue, TimerTask::Ptr pTask, long interval, Poco::Clock clock): + TaskNotification(queue, pTask), + _interval(interval), + _nextExecution(clock) + { + } + + ~FixedRateTaskNotification() + { + } + + bool execute() + { + TaskNotification::execute(); + + if (!task()->isCancelled()) + { + Poco::Clock now; + _nextExecution += static_cast<Poco::Clock::ClockDiff>(_interval)*1000; + if (_nextExecution < now) _nextExecution = now; + queue().enqueueNotification(this, _nextExecution); + duplicate(); + } + return true; + } + +private: + long _interval; + Poco::Clock _nextExecution; +}; + + +Timer::Timer() +{ + _thread.start(*this); +} + + +Timer::Timer(Poco::Thread::Priority priority) +{ + _thread.setPriority(priority); + _thread.start(*this); +} + + +Timer::~Timer() +{ + try + { + _queue.enqueueNotification(new StopNotification(_queue), Poco::Clock(0)); + _thread.join(); + } + catch (...) + { + poco_unexpected(); + } +} + + +void Timer::cancel(bool wait) +{ + Poco::AutoPtr<CancelNotification> pNf = new CancelNotification(_queue); + _queue.enqueueNotification(pNf, Poco::Clock(0)); + if (wait) + { + pNf->wait(); + } +} + + +void Timer::schedule(TimerTask::Ptr pTask, Poco::Timestamp time) +{ + validateTask(pTask); + _queue.enqueueNotification(new TaskNotification(_queue, pTask), time); +} + + +void Timer::schedule(TimerTask::Ptr pTask, Poco::Clock clock) +{ + validateTask(pTask); + _queue.enqueueNotification(new TaskNotification(_queue, pTask), clock); +} + + +void Timer::schedule(TimerTask::Ptr pTask, long delay, long interval) +{ + Poco::Clock clock; + clock += static_cast<Poco::Clock::ClockDiff>(delay)*1000; + schedule(pTask, clock, interval); +} + + +void Timer::schedule(TimerTask::Ptr pTask, Poco::Timestamp time, long interval) +{ + validateTask(pTask); + _queue.enqueueNotification(new PeriodicTaskNotification(_queue, pTask, interval), time); +} + + +void Timer::schedule(TimerTask::Ptr pTask, Poco::Clock clock, long interval) +{ + validateTask(pTask); + _queue.enqueueNotification(new PeriodicTaskNotification(_queue, pTask, interval), clock); +} + + +void Timer::scheduleAtFixedRate(TimerTask::Ptr pTask, long delay, long interval) +{ + Poco::Clock clock; + clock += static_cast<Poco::Clock::ClockDiff>(delay)*1000; + scheduleAtFixedRate(pTask, clock, interval); +} + + +void Timer::scheduleAtFixedRate(TimerTask::Ptr pTask, Poco::Timestamp time, long interval) +{ + validateTask(pTask); + Poco::Timestamp tsNow; + Poco::Clock clock; + Poco::Timestamp::TimeDiff diff = time - tsNow; + clock += diff; + _queue.enqueueNotification(new FixedRateTaskNotification(_queue, pTask, interval, clock), clock); +} + + +void Timer::scheduleAtFixedRate(TimerTask::Ptr pTask, Poco::Clock clock, long interval) +{ + validateTask(pTask); + _queue.enqueueNotification(new FixedRateTaskNotification(_queue, pTask, interval, clock), clock); +} + + +void Timer::run() +{ + bool cont = true; + while (cont) + { + Poco::AutoPtr<TimerNotification> pNf = static_cast<TimerNotification*>(_queue.waitDequeueNotification()); + cont = pNf->execute(); + } +} + + +void Timer::validateTask(const TimerTask::Ptr& pTask) +{ + if (pTask->isCancelled()) + { + throw Poco::IllegalStateException("A cancelled task must not be rescheduled"); + } +} + + +} } // namespace Poco::Util diff --git a/contrib/libs/poco/Util/src/TimerTask.cpp b/contrib/libs/poco/Util/src/TimerTask.cpp index d2d107cf3c..dac3794d1c 100644 --- a/contrib/libs/poco/Util/src/TimerTask.cpp +++ b/contrib/libs/poco/Util/src/TimerTask.cpp @@ -1,40 +1,40 @@ -// -// TimerTask.cpp -// -// Library: Util -// Package: Timer -// Module: TimerTask -// -// Copyright (c) 2009, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// SPDX-License-Identifier: BSL-1.0 -// - - -#include "Poco/Util/TimerTask.h" - - -namespace Poco { -namespace Util { - - -TimerTask::TimerTask(): - _lastExecution(0), - _isCancelled(false) -{ -} - - -TimerTask::~TimerTask() -{ -} - - -void TimerTask::cancel() -{ - _isCancelled = true; -} - - -} } // namespace Poco::Util +// +// TimerTask.cpp +// +// Library: Util +// Package: Timer +// Module: TimerTask +// +// Copyright (c) 2009, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#include "Poco/Util/TimerTask.h" + + +namespace Poco { +namespace Util { + + +TimerTask::TimerTask(): + _lastExecution(0), + _isCancelled(false) +{ +} + + +TimerTask::~TimerTask() +{ +} + + +void TimerTask::cancel() +{ + _isCancelled = true; +} + + +} } // namespace Poco::Util diff --git a/contrib/libs/poco/Util/src/Validator.cpp b/contrib/libs/poco/Util/src/Validator.cpp index 79747df235..bc596db289 100644 --- a/contrib/libs/poco/Util/src/Validator.cpp +++ b/contrib/libs/poco/Util/src/Validator.cpp @@ -1,32 +1,32 @@ -// -// Validator.cpp -// -// Library: Util -// Package: Options -// Module: Validator -// -// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// SPDX-License-Identifier: BSL-1.0 -// - - -#include "Poco/Util/Validator.h" - - -namespace Poco { -namespace Util { - - -Validator::Validator() -{ -} - - -Validator::~Validator() -{ -} - - -} } // namespace Poco::Util +// +// Validator.cpp +// +// Library: Util +// Package: Options +// Module: Validator +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#include "Poco/Util/Validator.h" + + +namespace Poco { +namespace Util { + + +Validator::Validator() +{ +} + + +Validator::~Validator() +{ +} + + +} } // namespace Poco::Util diff --git a/contrib/libs/poco/Util/src/XMLConfiguration.cpp b/contrib/libs/poco/Util/src/XMLConfiguration.cpp index 20b502e153..a4b655b9d9 100644 --- a/contrib/libs/poco/Util/src/XMLConfiguration.cpp +++ b/contrib/libs/poco/Util/src/XMLConfiguration.cpp @@ -1,479 +1,479 @@ -// -// XMLConfiguration.cpp -// -// Library: Util -// Package: Configuration -// Module: XMLConfiguration -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// SPDX-License-Identifier: BSL-1.0 -// - - -#include "Poco/Util/XMLConfiguration.h" - - -#ifndef POCO_UTIL_NO_XMLCONFIGURATION - - -#include "Poco/SAX/InputSource.h" -#include "Poco/DOM/DOMParser.h" -#include "Poco/DOM/Element.h" -#include "Poco/DOM/Attr.h" -#include "Poco/DOM/Text.h" -#include "Poco/XML/XMLWriter.h" -#include "Poco/Exception.h" -#include "Poco/NumberParser.h" -#include "Poco/NumberFormatter.h" -#include <set> - - -namespace Poco { -namespace Util { - - -XMLConfiguration::XMLConfiguration(): - _delim('.') -{ - loadEmpty("config"); -} - - -XMLConfiguration::XMLConfiguration(char delim): - _delim(delim) -{ - loadEmpty("config"); -} - - -XMLConfiguration::XMLConfiguration(Poco::XML::InputSource* pInputSource): - _delim('.') -{ - load(pInputSource); -} - - -XMLConfiguration::XMLConfiguration(Poco::XML::InputSource* pInputSource, char delim): - _delim(delim) -{ - load(pInputSource); -} - - -XMLConfiguration::XMLConfiguration(std::istream& istr): - _delim('.') -{ - load(istr); -} - - -XMLConfiguration::XMLConfiguration(std::istream& istr, char delim): - _delim(delim) -{ - load(istr); -} - - -XMLConfiguration::XMLConfiguration(const std::string& path): - _delim('.') -{ - load(path); -} - - -XMLConfiguration::XMLConfiguration(const std::string& path, char delim): - _delim(delim) -{ - load(path); -} - - -XMLConfiguration::XMLConfiguration(const Poco::XML::Document* pDocument): - _delim('.') -{ - load(pDocument); -} - - -XMLConfiguration::XMLConfiguration(const Poco::XML::Document* pDocument, char delim): - _delim(delim) -{ - load(pDocument); -} - - -XMLConfiguration::XMLConfiguration(const Poco::XML::Node* pNode): - _delim('.') -{ - load(pNode); -} - - -XMLConfiguration::XMLConfiguration(const Poco::XML::Node* pNode, char delim): - _delim(delim) -{ - load(pNode); -} - - -XMLConfiguration::~XMLConfiguration() -{ -} - - -void XMLConfiguration::load(Poco::XML::InputSource* pInputSource, unsigned long namePoolSize) -{ - poco_check_ptr (pInputSource); - - Poco::XML::DOMParser parser(namePoolSize); - parser.setFeature(Poco::XML::XMLReader::FEATURE_NAMESPACES, false); - parser.setFeature(Poco::XML::DOMParser::FEATURE_FILTER_WHITESPACE, true); - Poco::XML::AutoPtr<Poco::XML::Document> pDoc = parser.parse(pInputSource); - load(pDoc); -} - - -void XMLConfiguration::load(Poco::XML::InputSource* pInputSource) -{ - load(pInputSource, POCO_XML_NAMEPOOL_DEFAULT_SIZE); -} - - -void XMLConfiguration::load(std::istream& istr) -{ - Poco::XML::InputSource src(istr); - load(&src); -} - - -void XMLConfiguration::load(const std::string& path) -{ - Poco::XML::InputSource src(path); - load(&src); -} - - -void XMLConfiguration::load(const Poco::XML::Document* pDocument) -{ - poco_check_ptr (pDocument); - - _pDocument = Poco::XML::AutoPtr<Poco::XML::Document>(const_cast<Poco::XML::Document*>(pDocument), true); - _pRoot = Poco::XML::AutoPtr<Poco::XML::Node>(pDocument->documentElement(), true); -} - - -void XMLConfiguration::load(const Poco::XML::Node* pNode) -{ - poco_check_ptr (pNode); - - if (pNode->nodeType() == Poco::XML::Node::DOCUMENT_NODE) - { - load(static_cast<const Poco::XML::Document*>(pNode)); - } - else - { - _pDocument = Poco::XML::AutoPtr<Poco::XML::Document>(pNode->ownerDocument(), true); - _pRoot = Poco::XML::AutoPtr<Poco::XML::Node>(const_cast<Poco::XML::Node*>(pNode), true); - } -} - - -void XMLConfiguration::loadEmpty(const std::string& rootElementName) -{ - _pDocument = new Poco::XML::Document; - _pRoot = _pDocument->createElement(rootElementName); - _pDocument->appendChild(_pRoot); -} - - -void XMLConfiguration::save(const std::string& path) const -{ - Poco::XML::DOMWriter writer; - writer.setNewLine("\n"); - writer.setOptions(Poco::XML::XMLWriter::PRETTY_PRINT); - writer.writeNode(path, _pDocument); -} - - -void XMLConfiguration::save(std::ostream& ostr) const -{ - Poco::XML::DOMWriter writer; - writer.setNewLine("\n"); - writer.setOptions(Poco::XML::XMLWriter::PRETTY_PRINT); - writer.writeNode(ostr, _pDocument); -} - - -void XMLConfiguration::save(Poco::XML::DOMWriter& writer, const std::string& path) const -{ - writer.writeNode(path, _pDocument); -} - - -void XMLConfiguration::save(Poco::XML::DOMWriter& writer, std::ostream& ostr) const -{ - writer.writeNode(ostr, _pDocument); -} - - -bool XMLConfiguration::getRaw(const std::string& key, std::string& value) const -{ - const Poco::XML::Node* pNode = findNode(key); - if (pNode) - { - value = pNode->innerText(); - return true; - } - else return false; -} - - -void XMLConfiguration::setRaw(const std::string& key, const std::string& value) -{ - std::string::const_iterator it = key.begin(); - Poco::XML::Node* pNode = findNode(it, key.end(), _pRoot, true); - if (pNode) - { - unsigned short nodeType = pNode->nodeType(); - if (Poco::XML::Node::ATTRIBUTE_NODE == nodeType) - { - pNode->setNodeValue(value); - } - else if (Poco::XML::Node::ELEMENT_NODE == nodeType) - { - Poco::XML::Node* pChildNode = pNode->firstChild(); - if (pChildNode) - { - if (Poco::XML::Node::TEXT_NODE == pChildNode->nodeType()) - { - pChildNode->setNodeValue(value); - } - } - else - { - Poco::AutoPtr<Poco::XML::Node> pText = _pDocument->createTextNode(value); - pNode->appendChild(pText); - } - } - } - else throw NotFoundException("Node not found in XMLConfiguration", key); -} - - -void XMLConfiguration::enumerate(const std::string& key, Keys& range) const -{ - using Poco::NumberFormatter; - - std::multiset<std::string> keys; - const Poco::XML::Node* pNode = findNode(key); - if (pNode) - { - const Poco::XML::Node* pChild = pNode->firstChild(); - while (pChild) - { - if (pChild->nodeType() == Poco::XML::Node::ELEMENT_NODE) - { - const std::string& nodeName = pChild->nodeName(); - int n = (int) keys.count(nodeName); - if (n) - range.push_back(nodeName + "[" + NumberFormatter::format(n) + "]"); - else - range.push_back(nodeName); - keys.insert(nodeName); - } - pChild = pChild->nextSibling(); - } - } -} - - -void XMLConfiguration::removeRaw(const std::string& key) -{ - Poco::XML::Node* pNode = findNode(key); - - if (pNode) - { - if (pNode->nodeType() == Poco::XML::Node::ELEMENT_NODE) - { - Poco::XML::Node* pParent = pNode->parentNode(); - if (pParent) - { - pParent->removeChild(pNode); - } - } - else if (pNode->nodeType() == Poco::XML::Node::ATTRIBUTE_NODE) - { - Poco::XML::Attr* pAttr = dynamic_cast<Poco::XML::Attr*>(pNode); - Poco::XML::Element* pOwner = pAttr->ownerElement(); - if (pOwner) - { - pOwner->removeAttributeNode(pAttr); - } - } - } -} - - -const Poco::XML::Node* XMLConfiguration::findNode(const std::string& key) const -{ - std::string::const_iterator it = key.begin(); - Poco::XML::Node* pRoot = const_cast<Poco::XML::Node*>(_pRoot.get()); - return findNode(it, key.end(), pRoot); -} - - -Poco::XML::Node* XMLConfiguration::findNode(const std::string& key) -{ - std::string::const_iterator it = key.begin(); - Poco::XML::Node* pRoot = const_cast<Poco::XML::Node*>(_pRoot.get()); - return findNode(it, key.end(), pRoot); -} - - -Poco::XML::Node* XMLConfiguration::findNode(std::string::const_iterator& it, const std::string::const_iterator& end, Poco::XML::Node* pNode, bool create) const -{ - if (pNode && it != end) - { - if (*it == '[') - { - ++it; - if (it != end && *it == '@') - { - ++it; - std::string attr; - while (it != end && *it != ']' && *it != '=') attr += *it++; - if (it != end && *it == '=') - { - ++it; - std::string value; - if (it != end && *it == '\'') - { - ++it; - while (it != end && *it != '\'') value += *it++; - if (it != end) ++it; - } - else - { - while (it != end && *it != ']') value += *it++; - } - if (it != end) ++it; - return findNode(it, end, findElement(attr, value, pNode), create); - } - else - { - if (it != end) ++it; - return findAttribute(attr, pNode, create); - } - } - else - { - std::string index; - while (it != end && *it != ']') index += *it++; - if (it != end) ++it; - return findNode(it, end, findElement(Poco::NumberParser::parse(index), pNode, create), create); - } - } - else - { - while (it != end && *it == _delim) ++it; - std::string key; - while (it != end && *it != _delim && *it != '[') key += *it++; - return findNode(it, end, findElement(key, pNode, create), create); - } - } - else return pNode; -} - - -Poco::XML::Node* XMLConfiguration::findElement(const std::string& name, Poco::XML::Node* pNode, bool create) -{ - Poco::XML::Node* pChild = pNode->firstChild(); - while (pChild) - { - if (pChild->nodeType() == Poco::XML::Node::ELEMENT_NODE && pChild->nodeName() == name) - return pChild; - pChild = pChild->nextSibling(); - } - if (create) - { - Poco::AutoPtr<Poco::XML::Element> pElem = pNode->ownerDocument()->createElement(name); - pNode->appendChild(pElem); - return pElem; - } - else return 0; -} - - -Poco::XML::Node* XMLConfiguration::findElement(int index, Poco::XML::Node* pNode, bool create) -{ - Poco::XML::Node* pRefNode = pNode; - if (index > 0) - { - pNode = pNode->nextSibling(); - while (pNode) - { - if (pNode->nodeName() == pRefNode->nodeName()) - { - if (--index == 0) break; - } - pNode = pNode->nextSibling(); - } - } - if (!pNode && create) - { - if (index == 1) - { - Poco::AutoPtr<Poco::XML::Element> pElem = pRefNode->ownerDocument()->createElement(pRefNode->nodeName()); - pRefNode->parentNode()->appendChild(pElem); - return pElem; - } - else throw Poco::InvalidArgumentException("Element index out of range."); - } - return pNode; -} - - -Poco::XML::Node* XMLConfiguration::findElement(const std::string& attr, const std::string& value, Poco::XML::Node* pNode) -{ - Poco::XML::Node* pRefNode = pNode; - Poco::XML::Element* pElem = dynamic_cast<Poco::XML::Element*>(pNode); - if (!(pElem && pElem->getAttribute(attr) == value)) - { - pNode = pNode->nextSibling(); - while (pNode) - { - if (pNode->nodeName() == pRefNode->nodeName()) - { - pElem = dynamic_cast<Poco::XML::Element*>(pNode); - if (pElem && pElem->getAttribute(attr) == value) break; - } - pNode = pNode->nextSibling(); - } - } - return pNode; -} - - -Poco::XML::Node* XMLConfiguration::findAttribute(const std::string& name, Poco::XML::Node* pNode, bool create) -{ - Poco::XML::Node* pResult(0); - Poco::XML::Element* pElem = dynamic_cast<Poco::XML::Element*>(pNode); - if (pElem) - { - pResult = pElem->getAttributeNode(name); - if (!pResult && create) - { - Poco::AutoPtr<Poco::XML::Attr> pAttr = pNode->ownerDocument()->createAttribute(name); - pElem->setAttributeNode(pAttr); - return pAttr; - } - } - return pResult; -} - - -} } // namespace Poco::Util - -#endif // POCO_UTIL_NO_XMLCONFIGURATION +// +// XMLConfiguration.cpp +// +// Library: Util +// Package: Configuration +// Module: XMLConfiguration +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#include "Poco/Util/XMLConfiguration.h" + + +#ifndef POCO_UTIL_NO_XMLCONFIGURATION + + +#include "Poco/SAX/InputSource.h" +#include "Poco/DOM/DOMParser.h" +#include "Poco/DOM/Element.h" +#include "Poco/DOM/Attr.h" +#include "Poco/DOM/Text.h" +#include "Poco/XML/XMLWriter.h" +#include "Poco/Exception.h" +#include "Poco/NumberParser.h" +#include "Poco/NumberFormatter.h" +#include <set> + + +namespace Poco { +namespace Util { + + +XMLConfiguration::XMLConfiguration(): + _delim('.') +{ + loadEmpty("config"); +} + + +XMLConfiguration::XMLConfiguration(char delim): + _delim(delim) +{ + loadEmpty("config"); +} + + +XMLConfiguration::XMLConfiguration(Poco::XML::InputSource* pInputSource): + _delim('.') +{ + load(pInputSource); +} + + +XMLConfiguration::XMLConfiguration(Poco::XML::InputSource* pInputSource, char delim): + _delim(delim) +{ + load(pInputSource); +} + + +XMLConfiguration::XMLConfiguration(std::istream& istr): + _delim('.') +{ + load(istr); +} + + +XMLConfiguration::XMLConfiguration(std::istream& istr, char delim): + _delim(delim) +{ + load(istr); +} + + +XMLConfiguration::XMLConfiguration(const std::string& path): + _delim('.') +{ + load(path); +} + + +XMLConfiguration::XMLConfiguration(const std::string& path, char delim): + _delim(delim) +{ + load(path); +} + + +XMLConfiguration::XMLConfiguration(const Poco::XML::Document* pDocument): + _delim('.') +{ + load(pDocument); +} + + +XMLConfiguration::XMLConfiguration(const Poco::XML::Document* pDocument, char delim): + _delim(delim) +{ + load(pDocument); +} + + +XMLConfiguration::XMLConfiguration(const Poco::XML::Node* pNode): + _delim('.') +{ + load(pNode); +} + + +XMLConfiguration::XMLConfiguration(const Poco::XML::Node* pNode, char delim): + _delim(delim) +{ + load(pNode); +} + + +XMLConfiguration::~XMLConfiguration() +{ +} + + +void XMLConfiguration::load(Poco::XML::InputSource* pInputSource, unsigned long namePoolSize) +{ + poco_check_ptr (pInputSource); + + Poco::XML::DOMParser parser(namePoolSize); + parser.setFeature(Poco::XML::XMLReader::FEATURE_NAMESPACES, false); + parser.setFeature(Poco::XML::DOMParser::FEATURE_FILTER_WHITESPACE, true); + Poco::XML::AutoPtr<Poco::XML::Document> pDoc = parser.parse(pInputSource); + load(pDoc); +} + + +void XMLConfiguration::load(Poco::XML::InputSource* pInputSource) +{ + load(pInputSource, POCO_XML_NAMEPOOL_DEFAULT_SIZE); +} + + +void XMLConfiguration::load(std::istream& istr) +{ + Poco::XML::InputSource src(istr); + load(&src); +} + + +void XMLConfiguration::load(const std::string& path) +{ + Poco::XML::InputSource src(path); + load(&src); +} + + +void XMLConfiguration::load(const Poco::XML::Document* pDocument) +{ + poco_check_ptr (pDocument); + + _pDocument = Poco::XML::AutoPtr<Poco::XML::Document>(const_cast<Poco::XML::Document*>(pDocument), true); + _pRoot = Poco::XML::AutoPtr<Poco::XML::Node>(pDocument->documentElement(), true); +} + + +void XMLConfiguration::load(const Poco::XML::Node* pNode) +{ + poco_check_ptr (pNode); + + if (pNode->nodeType() == Poco::XML::Node::DOCUMENT_NODE) + { + load(static_cast<const Poco::XML::Document*>(pNode)); + } + else + { + _pDocument = Poco::XML::AutoPtr<Poco::XML::Document>(pNode->ownerDocument(), true); + _pRoot = Poco::XML::AutoPtr<Poco::XML::Node>(const_cast<Poco::XML::Node*>(pNode), true); + } +} + + +void XMLConfiguration::loadEmpty(const std::string& rootElementName) +{ + _pDocument = new Poco::XML::Document; + _pRoot = _pDocument->createElement(rootElementName); + _pDocument->appendChild(_pRoot); +} + + +void XMLConfiguration::save(const std::string& path) const +{ + Poco::XML::DOMWriter writer; + writer.setNewLine("\n"); + writer.setOptions(Poco::XML::XMLWriter::PRETTY_PRINT); + writer.writeNode(path, _pDocument); +} + + +void XMLConfiguration::save(std::ostream& ostr) const +{ + Poco::XML::DOMWriter writer; + writer.setNewLine("\n"); + writer.setOptions(Poco::XML::XMLWriter::PRETTY_PRINT); + writer.writeNode(ostr, _pDocument); +} + + +void XMLConfiguration::save(Poco::XML::DOMWriter& writer, const std::string& path) const +{ + writer.writeNode(path, _pDocument); +} + + +void XMLConfiguration::save(Poco::XML::DOMWriter& writer, std::ostream& ostr) const +{ + writer.writeNode(ostr, _pDocument); +} + + +bool XMLConfiguration::getRaw(const std::string& key, std::string& value) const +{ + const Poco::XML::Node* pNode = findNode(key); + if (pNode) + { + value = pNode->innerText(); + return true; + } + else return false; +} + + +void XMLConfiguration::setRaw(const std::string& key, const std::string& value) +{ + std::string::const_iterator it = key.begin(); + Poco::XML::Node* pNode = findNode(it, key.end(), _pRoot, true); + if (pNode) + { + unsigned short nodeType = pNode->nodeType(); + if (Poco::XML::Node::ATTRIBUTE_NODE == nodeType) + { + pNode->setNodeValue(value); + } + else if (Poco::XML::Node::ELEMENT_NODE == nodeType) + { + Poco::XML::Node* pChildNode = pNode->firstChild(); + if (pChildNode) + { + if (Poco::XML::Node::TEXT_NODE == pChildNode->nodeType()) + { + pChildNode->setNodeValue(value); + } + } + else + { + Poco::AutoPtr<Poco::XML::Node> pText = _pDocument->createTextNode(value); + pNode->appendChild(pText); + } + } + } + else throw NotFoundException("Node not found in XMLConfiguration", key); +} + + +void XMLConfiguration::enumerate(const std::string& key, Keys& range) const +{ + using Poco::NumberFormatter; + + std::multiset<std::string> keys; + const Poco::XML::Node* pNode = findNode(key); + if (pNode) + { + const Poco::XML::Node* pChild = pNode->firstChild(); + while (pChild) + { + if (pChild->nodeType() == Poco::XML::Node::ELEMENT_NODE) + { + const std::string& nodeName = pChild->nodeName(); + int n = (int) keys.count(nodeName); + if (n) + range.push_back(nodeName + "[" + NumberFormatter::format(n) + "]"); + else + range.push_back(nodeName); + keys.insert(nodeName); + } + pChild = pChild->nextSibling(); + } + } +} + + +void XMLConfiguration::removeRaw(const std::string& key) +{ + Poco::XML::Node* pNode = findNode(key); + + if (pNode) + { + if (pNode->nodeType() == Poco::XML::Node::ELEMENT_NODE) + { + Poco::XML::Node* pParent = pNode->parentNode(); + if (pParent) + { + pParent->removeChild(pNode); + } + } + else if (pNode->nodeType() == Poco::XML::Node::ATTRIBUTE_NODE) + { + Poco::XML::Attr* pAttr = dynamic_cast<Poco::XML::Attr*>(pNode); + Poco::XML::Element* pOwner = pAttr->ownerElement(); + if (pOwner) + { + pOwner->removeAttributeNode(pAttr); + } + } + } +} + + +const Poco::XML::Node* XMLConfiguration::findNode(const std::string& key) const +{ + std::string::const_iterator it = key.begin(); + Poco::XML::Node* pRoot = const_cast<Poco::XML::Node*>(_pRoot.get()); + return findNode(it, key.end(), pRoot); +} + + +Poco::XML::Node* XMLConfiguration::findNode(const std::string& key) +{ + std::string::const_iterator it = key.begin(); + Poco::XML::Node* pRoot = const_cast<Poco::XML::Node*>(_pRoot.get()); + return findNode(it, key.end(), pRoot); +} + + +Poco::XML::Node* XMLConfiguration::findNode(std::string::const_iterator& it, const std::string::const_iterator& end, Poco::XML::Node* pNode, bool create) const +{ + if (pNode && it != end) + { + if (*it == '[') + { + ++it; + if (it != end && *it == '@') + { + ++it; + std::string attr; + while (it != end && *it != ']' && *it != '=') attr += *it++; + if (it != end && *it == '=') + { + ++it; + std::string value; + if (it != end && *it == '\'') + { + ++it; + while (it != end && *it != '\'') value += *it++; + if (it != end) ++it; + } + else + { + while (it != end && *it != ']') value += *it++; + } + if (it != end) ++it; + return findNode(it, end, findElement(attr, value, pNode), create); + } + else + { + if (it != end) ++it; + return findAttribute(attr, pNode, create); + } + } + else + { + std::string index; + while (it != end && *it != ']') index += *it++; + if (it != end) ++it; + return findNode(it, end, findElement(Poco::NumberParser::parse(index), pNode, create), create); + } + } + else + { + while (it != end && *it == _delim) ++it; + std::string key; + while (it != end && *it != _delim && *it != '[') key += *it++; + return findNode(it, end, findElement(key, pNode, create), create); + } + } + else return pNode; +} + + +Poco::XML::Node* XMLConfiguration::findElement(const std::string& name, Poco::XML::Node* pNode, bool create) +{ + Poco::XML::Node* pChild = pNode->firstChild(); + while (pChild) + { + if (pChild->nodeType() == Poco::XML::Node::ELEMENT_NODE && pChild->nodeName() == name) + return pChild; + pChild = pChild->nextSibling(); + } + if (create) + { + Poco::AutoPtr<Poco::XML::Element> pElem = pNode->ownerDocument()->createElement(name); + pNode->appendChild(pElem); + return pElem; + } + else return 0; +} + + +Poco::XML::Node* XMLConfiguration::findElement(int index, Poco::XML::Node* pNode, bool create) +{ + Poco::XML::Node* pRefNode = pNode; + if (index > 0) + { + pNode = pNode->nextSibling(); + while (pNode) + { + if (pNode->nodeName() == pRefNode->nodeName()) + { + if (--index == 0) break; + } + pNode = pNode->nextSibling(); + } + } + if (!pNode && create) + { + if (index == 1) + { + Poco::AutoPtr<Poco::XML::Element> pElem = pRefNode->ownerDocument()->createElement(pRefNode->nodeName()); + pRefNode->parentNode()->appendChild(pElem); + return pElem; + } + else throw Poco::InvalidArgumentException("Element index out of range."); + } + return pNode; +} + + +Poco::XML::Node* XMLConfiguration::findElement(const std::string& attr, const std::string& value, Poco::XML::Node* pNode) +{ + Poco::XML::Node* pRefNode = pNode; + Poco::XML::Element* pElem = dynamic_cast<Poco::XML::Element*>(pNode); + if (!(pElem && pElem->getAttribute(attr) == value)) + { + pNode = pNode->nextSibling(); + while (pNode) + { + if (pNode->nodeName() == pRefNode->nodeName()) + { + pElem = dynamic_cast<Poco::XML::Element*>(pNode); + if (pElem && pElem->getAttribute(attr) == value) break; + } + pNode = pNode->nextSibling(); + } + } + return pNode; +} + + +Poco::XML::Node* XMLConfiguration::findAttribute(const std::string& name, Poco::XML::Node* pNode, bool create) +{ + Poco::XML::Node* pResult(0); + Poco::XML::Element* pElem = dynamic_cast<Poco::XML::Element*>(pNode); + if (pElem) + { + pResult = pElem->getAttributeNode(name); + if (!pResult && create) + { + Poco::AutoPtr<Poco::XML::Attr> pAttr = pNode->ownerDocument()->createAttribute(name); + pElem->setAttributeNode(pAttr); + return pAttr; + } + } + return pResult; +} + + +} } // namespace Poco::Util + +#endif // POCO_UTIL_NO_XMLCONFIGURATION diff --git a/contrib/libs/poco/Util/ya.make b/contrib/libs/poco/Util/ya.make index e5ce1ebbfb..3a295763c6 100644 --- a/contrib/libs/poco/Util/ya.make +++ b/contrib/libs/poco/Util/ya.make @@ -1,7 +1,7 @@ -# Generated by devtools/yamaker. - -LIBRARY() - +# Generated by devtools/yamaker. + +LIBRARY() + OWNER( orivej g:cpp-contrib @@ -14,54 +14,54 @@ LICENSE( LICENSE_TEXTS(.yandex_meta/licenses.list.txt) -PEERDIR( - contrib/libs/expat - contrib/libs/poco/Foundation - contrib/libs/poco/JSON - contrib/libs/poco/XML -) - -ADDINCL( - GLOBAL contrib/libs/poco/Util/include - contrib/libs/expat - contrib/libs/poco/Foundation/include - contrib/libs/poco/JSON/include - contrib/libs/poco/Util/src - contrib/libs/poco/XML/include -) - -NO_COMPILER_WARNINGS() - -NO_UTIL() - -SRCS( - src/AbstractConfiguration.cpp - src/Application.cpp - src/ConfigurationMapper.cpp - src/ConfigurationView.cpp - src/FilesystemConfiguration.cpp - src/HelpFormatter.cpp - src/IniFileConfiguration.cpp - src/IntValidator.cpp - src/JSONConfiguration.cpp - src/LayeredConfiguration.cpp - src/LoggingConfigurator.cpp - src/LoggingSubsystem.cpp - src/MapConfiguration.cpp - src/Option.cpp - src/OptionCallback.cpp - src/OptionException.cpp - src/OptionProcessor.cpp - src/OptionSet.cpp - src/PropertyFileConfiguration.cpp - src/RegExpValidator.cpp - src/ServerApplication.cpp - src/Subsystem.cpp - src/SystemConfiguration.cpp - src/Timer.cpp - src/TimerTask.cpp - src/Validator.cpp - src/XMLConfiguration.cpp -) - -END() +PEERDIR( + contrib/libs/expat + contrib/libs/poco/Foundation + contrib/libs/poco/JSON + contrib/libs/poco/XML +) + +ADDINCL( + GLOBAL contrib/libs/poco/Util/include + contrib/libs/expat + contrib/libs/poco/Foundation/include + contrib/libs/poco/JSON/include + contrib/libs/poco/Util/src + contrib/libs/poco/XML/include +) + +NO_COMPILER_WARNINGS() + +NO_UTIL() + +SRCS( + src/AbstractConfiguration.cpp + src/Application.cpp + src/ConfigurationMapper.cpp + src/ConfigurationView.cpp + src/FilesystemConfiguration.cpp + src/HelpFormatter.cpp + src/IniFileConfiguration.cpp + src/IntValidator.cpp + src/JSONConfiguration.cpp + src/LayeredConfiguration.cpp + src/LoggingConfigurator.cpp + src/LoggingSubsystem.cpp + src/MapConfiguration.cpp + src/Option.cpp + src/OptionCallback.cpp + src/OptionException.cpp + src/OptionProcessor.cpp + src/OptionSet.cpp + src/PropertyFileConfiguration.cpp + src/RegExpValidator.cpp + src/ServerApplication.cpp + src/Subsystem.cpp + src/SystemConfiguration.cpp + src/Timer.cpp + src/TimerTask.cpp + src/Validator.cpp + src/XMLConfiguration.cpp +) + +END() |