change EOL to 'native'

This commit is contained in:
Aleksandar Fabijanic
2012-04-29 18:52:25 +00:00
parent 056cbeb744
commit 5a639074d9
2420 changed files with 544743 additions and 544298 deletions

View File

@@ -1,425 +1,425 @@
//
// AbstractConfiguration.cpp
//
// $Id: //poco/1.4/Util/src/AbstractConfiguration.cpp#2 $
//
// Library: Util
// Package: Configuration
// Module: AbstractConfiguration
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#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::FastMutex;
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
{
FastMutex::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
{
FastMutex::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
{
FastMutex::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
{
FastMutex::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
{
FastMutex::ScopedLock lock(_mutex);
std::string value;
if (getRaw(key, value))
return value;
else
return defaultValue;
}
int AbstractConfiguration::getInt(const std::string& key) const
{
FastMutex::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
{
FastMutex::ScopedLock lock(_mutex);
std::string value;
if (getRaw(key, value))
return parseInt(internalExpand(value));
else
return defaultValue;
}
double AbstractConfiguration::getDouble(const std::string& key) const
{
FastMutex::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
{
FastMutex::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
{
FastMutex::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
{
FastMutex::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::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
{
FastMutex::ScopedLock lock(_mutex);
std::string key;
range.clear();
enumerate(key, range);
}
void AbstractConfiguration::keys(const std::string& key, Keys& range) const
{
FastMutex::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
{
FastMutex::ScopedLock lock(_mutex);
return internalExpand(value);
}
void AbstractConfiguration::remove(const std::string& key)
{
if (_eventsEnabled)
{
propertyRemoving(this, key);
}
{
FastMutex::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 value;
if (getRaw(prop, value))
{
result.append(internalExpand(value));
}
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)
return NumberParser::parseHex(value.substr(2));
else
return NumberParser::parse(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);
}
{
FastMutex::ScopedLock lock(_mutex);
setRaw(key, value);
}
if (_eventsEnabled)
{
propertyChanged(this, kv);
}
}
} } // namespace Poco::Util
//
// AbstractConfiguration.cpp
//
// $Id: //poco/1.4/Util/src/AbstractConfiguration.cpp#2 $
//
// Library: Util
// Package: Configuration
// Module: AbstractConfiguration
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#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::FastMutex;
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
{
FastMutex::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
{
FastMutex::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
{
FastMutex::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
{
FastMutex::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
{
FastMutex::ScopedLock lock(_mutex);
std::string value;
if (getRaw(key, value))
return value;
else
return defaultValue;
}
int AbstractConfiguration::getInt(const std::string& key) const
{
FastMutex::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
{
FastMutex::ScopedLock lock(_mutex);
std::string value;
if (getRaw(key, value))
return parseInt(internalExpand(value));
else
return defaultValue;
}
double AbstractConfiguration::getDouble(const std::string& key) const
{
FastMutex::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
{
FastMutex::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
{
FastMutex::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
{
FastMutex::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::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
{
FastMutex::ScopedLock lock(_mutex);
std::string key;
range.clear();
enumerate(key, range);
}
void AbstractConfiguration::keys(const std::string& key, Keys& range) const
{
FastMutex::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
{
FastMutex::ScopedLock lock(_mutex);
return internalExpand(value);
}
void AbstractConfiguration::remove(const std::string& key)
{
if (_eventsEnabled)
{
propertyRemoving(this, key);
}
{
FastMutex::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 value;
if (getRaw(prop, value))
{
result.append(internalExpand(value));
}
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)
return NumberParser::parseHex(value.substr(2));
else
return NumberParser::parse(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);
}
{
FastMutex::ScopedLock lock(_mutex);
setRaw(key, value);
}
if (_eventsEnabled)
{
propertyChanged(this, kv);
}
}
} } // namespace Poco::Util

File diff suppressed because it is too large Load Diff

View File

@@ -1,123 +1,123 @@
//
// ConfigurationMapper.cpp
//
// $Id: //poco/1.4/Util/src/ConfigurationMapper.cpp#1 $
//
// Library: Util
// Package: Configuration
// Module: ConfigurationMapper
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#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
//
// $Id: //poco/1.4/Util/src/ConfigurationMapper.cpp#1 $
//
// Library: Util
// Package: Configuration
// Module: ConfigurationMapper
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#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

View File

@@ -1,97 +1,97 @@
//
// ConfigurationView.cpp
//
// $Id: //poco/1.4/Util/src/ConfigurationView.cpp#1 $
//
// Library: Util
// Package: Configuration
// Module: ConfigurationView
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#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
//
// $Id: //poco/1.4/Util/src/ConfigurationView.cpp#1 $
//
// Library: Util
// Package: Configuration
// Module: ConfigurationView
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#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

View File

@@ -1,149 +1,149 @@
//
// FilesystemConfiguration.cpp
//
// $Id: //poco/1.4/Util/src/FilesystemConfiguration.cpp#1 $
//
// Library: Util
// Package: Configuration
// Module: FilesystemConfiguration
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#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
//
// $Id: //poco/1.4/Util/src/FilesystemConfiguration.cpp#1 $
//
// Library: Util
// Package: Configuration
// Module: FilesystemConfiguration
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#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

View File

@@ -1,318 +1,318 @@
//
// HelpFormatter.cpp
//
// $Id: //poco/1.4/Util/src/HelpFormatter.cpp#2 $
//
// Library: Util
// Package: Options
// Module: HelpFormatter
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#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
{
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
//
// HelpFormatter.cpp
//
// $Id: //poco/1.4/Util/src/HelpFormatter.cpp#2 $
//
// Library: Util
// Package: Options
// Module: HelpFormatter
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#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
{
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

View File

@@ -1,204 +1,204 @@
//
// IniFileConfiguration.cpp
//
// $Id: //poco/1.4/Util/src/IniFileConfiguration.cpp#1 $
//
// Library: Util
// Package: Configuration
// Module: IniFileConfiguration
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Util/IniFileConfiguration.h"
#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
//
// IniFileConfiguration.cpp
//
// $Id: //poco/1.4/Util/src/IniFileConfiguration.cpp#1 $
//
// Library: Util
// Package: Configuration
// Module: IniFileConfiguration
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Util/IniFileConfiguration.h"
#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

View File

@@ -1,76 +1,76 @@
//
// IntValidator.cpp
//
// $Id: //poco/1.4/Util/src/IntValidator.cpp#1 $
//
// Library: Util
// Package: Options
// Module: IntValidator
//
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#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
//
// $Id: //poco/1.4/Util/src/IntValidator.cpp#1 $
//
// Library: Util
// Package: Options
// Module: IntValidator
//
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#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

View File

@@ -1,211 +1,211 @@
//
// LayeredConfiguration.cpp
//
// $Id: //poco/1.4/Util/src/LayeredConfiguration.cpp#1 $
//
// Library: Util
// Package: Configuration
// Module: LayeredConfiguration
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#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, bool shared)
{
add(pConfig, highest(), false, shared);
}
void LayeredConfiguration::add(AbstractConfiguration* pConfig, int priority)
{
add(pConfig, priority, false, true);
}
void LayeredConfiguration::add(AbstractConfiguration* pConfig, int priority, bool shared)
{
add(pConfig, 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)
{
ConfigItem item;
item.pConfig = ConfigPtr(pConfig, shared);
item.priority = priority;
item.writeable = writeable;
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;
}
}
}
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
//
// $Id: //poco/1.4/Util/src/LayeredConfiguration.cpp#1 $
//
// Library: Util
// Package: Configuration
// Module: LayeredConfiguration
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#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, bool shared)
{
add(pConfig, highest(), false, shared);
}
void LayeredConfiguration::add(AbstractConfiguration* pConfig, int priority)
{
add(pConfig, priority, false, true);
}
void LayeredConfiguration::add(AbstractConfiguration* pConfig, int priority, bool shared)
{
add(pConfig, 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)
{
ConfigItem item;
item.pConfig = ConfigPtr(pConfig, shared);
item.priority = priority;
item.writeable = writeable;
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;
}
}
}
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

View File

@@ -1,225 +1,225 @@
//
// LoggingConfigurator.cpp
//
// $Id: //poco/1.4/Util/src/LoggingConfigurator.cpp#1 $
//
// Library: Util
// Package: Configuration
// Module: LoggingConfigurator
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#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
//
// $Id: //poco/1.4/Util/src/LoggingConfigurator.cpp#1 $
//
// Library: Util
// Package: Configuration
// Module: LoggingConfigurator
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#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

View File

@@ -1,80 +1,80 @@
//
// LoggingSubsystem.cpp
//
// $Id: //poco/1.4/Util/src/LoggingSubsystem.cpp#1 $
//
// Library: Util
// Package: Application
// Module: LoggingSubsystem
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#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
//
// $Id: //poco/1.4/Util/src/LoggingSubsystem.cpp#1 $
//
// Library: Util
// Package: Application
// Module: LoggingSubsystem
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#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

View File

@@ -1,135 +1,135 @@
//
// MapConfiguration.cpp
//
// $Id: //poco/1.4/Util/src/MapConfiguration.cpp#1 $
//
// Library: Util
// Package: Configuration
// Module: MapConfiguration
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Util/MapConfiguration.h"
#include <set>
namespace Poco {
namespace Util {
MapConfiguration::MapConfiguration()
{
}
MapConfiguration::~MapConfiguration()
{
}
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
//
// $Id: //poco/1.4/Util/src/MapConfiguration.cpp#1 $
//
// Library: Util
// Package: Configuration
// Module: MapConfiguration
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Util/MapConfiguration.h"
#include <set>
namespace Poco {
namespace Util {
MapConfiguration::MapConfiguration()
{
}
MapConfiguration::~MapConfiguration()
{
}
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

View File

@@ -1,314 +1,314 @@
//
// Option.cpp
//
// $Id: //poco/1.4/Util/src/Option.cpp#1 $
//
// Library: Util
// Package: Options
// Module: Option
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#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),
_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
//
// Option.cpp
//
// $Id: //poco/1.4/Util/src/Option.cpp#1 $
//
// Library: Util
// Package: Options
// Module: Option
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#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),
_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

View File

@@ -1,59 +1,59 @@
//
// OptionCallback.cpp
//
// $Id: //poco/1.4/Util/src/OptionCallback.cpp#1 $
//
// Library: Util
// Package: Options
// Module: OptionCallback
//
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Util/OptionCallback.h"
namespace Poco {
namespace Util {
AbstractOptionCallback::AbstractOptionCallback()
{
}
AbstractOptionCallback::AbstractOptionCallback(const AbstractOptionCallback&)
{
}
AbstractOptionCallback::~AbstractOptionCallback()
{
}
} } // namespace Poco::Util
//
// OptionCallback.cpp
//
// $Id: //poco/1.4/Util/src/OptionCallback.cpp#1 $
//
// Library: Util
// Package: Options
// Module: OptionCallback
//
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Util/OptionCallback.h"
namespace Poco {
namespace Util {
AbstractOptionCallback::AbstractOptionCallback()
{
}
AbstractOptionCallback::AbstractOptionCallback(const AbstractOptionCallback&)
{
}
AbstractOptionCallback::~AbstractOptionCallback()
{
}
} } // namespace Poco::Util

View File

@@ -1,57 +1,57 @@
//
// OptionException.cpp
//
// $Id: //poco/1.4/Util/src/OptionException.cpp#1 $
//
// Library: Util
// Package: Options
// Module: OptionException
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#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
//
// $Id: //poco/1.4/Util/src/OptionException.cpp#1 $
//
// Library: Util
// Package: Options
// Module: OptionException
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#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

View File

@@ -1,181 +1,181 @@
//
// OptionProcessor.cpp
//
// $Id: //poco/1.4/Util/src/OptionProcessor.cpp#2 $
//
// Library: Util
// Package: Options
// Module: OptionProcessor
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#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
//
// $Id: //poco/1.4/Util/src/OptionProcessor.cpp#2 $
//
// Library: Util
// Package: Options
// Module: OptionProcessor
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#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

View File

@@ -1,144 +1,144 @@
//
// OptionSet.cpp
//
// $Id: //poco/1.4/Util/src/OptionSet.cpp#1 $
//
// Library: Util
// Package: Options
// Module: OptionSet
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#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
//
// $Id: //poco/1.4/Util/src/OptionSet.cpp#1 $
//
// Library: Util
// Package: Options
// Module: OptionSet
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#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

View File

@@ -1,187 +1,187 @@
//
// PropertyFileConfiguration.cpp
//
// $Id: //poco/1.4/Util/src/PropertyFileConfiguration.cpp#1 $
//
// Library: Util
// Package: Configuration
// Module: PropertyFileConfiguration
//
// Copyright (c) 2004-2009, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#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 << ": " << it->second << "\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
//
// $Id: //poco/1.4/Util/src/PropertyFileConfiguration.cpp#1 $
//
// Library: Util
// Package: Configuration
// Module: PropertyFileConfiguration
//
// Copyright (c) 2004-2009, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#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 << ": " << it->second << "\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

View File

@@ -1,69 +1,69 @@
//
// RegExpValidator.cpp
//
// $Id: //poco/1.4/Util/src/RegExpValidator.cpp#1 $
//
// Library: Util
// Package: Options
// Module: RegExpValidator
//
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#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
//
// $Id: //poco/1.4/Util/src/RegExpValidator.cpp#1 $
//
// Library: Util
// Package: Options
// Module: RegExpValidator
//
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#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

File diff suppressed because it is too large Load Diff

View File

@@ -1,66 +1,66 @@
//
// Subsystem.cpp
//
// $Id: //poco/1.4/Util/src/Subsystem.cpp#1 $
//
// Library: Util
// Package: Application
// Module: Subsystem
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#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
//
// $Id: //poco/1.4/Util/src/Subsystem.cpp#1 $
//
// Library: Util
// Package: Application
// Module: Subsystem
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#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

View File

@@ -1,203 +1,203 @@
//
// SystemConfiguration.cpp
//
// $Id: //poco/1.4/Util/src/SystemConfiguration.cpp#2 $
//
// Library: Util
// Package: Configuration
// Module: SystemConfiguration
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#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::TEMPDIR = "system.tempDir";
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 == TEMPDIR)
{
value = Path::temp();
}
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("tempDir");
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
//
// $Id: //poco/1.4/Util/src/SystemConfiguration.cpp#2 $
//
// Library: Util
// Package: Configuration
// Module: SystemConfiguration
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#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::TEMPDIR = "system.tempDir";
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 == TEMPDIR)
{
value = Path::temp();
}
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("tempDir");
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

View File

@@ -1,54 +1,54 @@
//
// Validator.cpp
//
// $Id: //poco/1.4/Util/src/Validator.cpp#1 $
//
// Library: Util
// Package: Options
// Module: Validator
//
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Util/Validator.h"
namespace Poco {
namespace Util {
Validator::Validator()
{
}
Validator::~Validator()
{
}
} } // namespace Poco::Util
//
// Validator.cpp
//
// $Id: //poco/1.4/Util/src/Validator.cpp#1 $
//
// Library: Util
// Package: Options
// Module: Validator
//
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Util/Validator.h"
namespace Poco {
namespace Util {
Validator::Validator()
{
}
Validator::~Validator()
{
}
} } // namespace Poco::Util

View File

@@ -1,150 +1,150 @@
//
// WinRegistryConfiguration.cpp
//
// $Id: //poco/1.4/Util/src/WinRegistryConfiguration.cpp#3 $
//
// Library: Util
// Package: Windows
// Module: WinRegistryConfiguration
//
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#if !defined(_WIN32_WCE)
#include "Poco/Util/WinRegistryConfiguration.h"
#include "Poco/Util/WinRegistryKey.h"
#include "Poco/NumberFormatter.h"
#include "Poco/NumberParser.h"
#include "Poco/Exception.h"
namespace Poco {
namespace Util {
WinRegistryConfiguration::WinRegistryConfiguration(const std::string& rootPath, REGSAM extraSam): _rootPath(rootPath), _extraSam(extraSam)
{
// rootPath must end with backslash
std::string::iterator it = _rootPath.end();
if (*(--it) != '\\')
_rootPath.append("\\");
}
WinRegistryConfiguration::~WinRegistryConfiguration()
{
}
bool WinRegistryConfiguration::getRaw(const std::string& key, std::string& value) const
{
std::string keyName;
std::string fullPath = _rootPath + ConvertToRegFormat(key, keyName);
WinRegistryKey aKey(fullPath, true, _extraSam);
bool exists = aKey.exists(keyName);
if (exists)
{
WinRegistryKey::Type type = aKey.type(keyName);
switch (type)
{
case WinRegistryKey::REGT_STRING:
value = aKey.getString(keyName);
break;
case WinRegistryKey::REGT_STRING_EXPAND:
value = aKey.getStringExpand(keyName);
break;
case WinRegistryKey::REGT_DWORD:
value = Poco::NumberFormatter::format(aKey.getInt(keyName));
break;
default:
exists = false;
}
}
return exists;
}
void WinRegistryConfiguration::setRaw(const std::string& key, const std::string& value)
{
std::string keyName;
std::string fullPath = _rootPath+ConvertToRegFormat(key, keyName);
WinRegistryKey aKey(fullPath, false, _extraSam);
aKey.setString(keyName, value);
}
void WinRegistryConfiguration::enumerate(const std::string& key, Keys& range) const
{
if (key.empty())
{
// return all root level keys
range.push_back("HKEY_CLASSES_ROOT");
range.push_back("HKEY_CURRENT_CONFIG");
range.push_back("HKEY_CURRENT_USER");
range.push_back("HKEY_LOCAL_MACHINE");
range.push_back("HKEY_PERFORMANCE_DATA");
range.push_back("HKEY_USERS");
}
else
{
std::string keyName;
std::string fullPath = _rootPath+ConvertToRegFormat(key, keyName);
WinRegistryKey aKey(fullPath, true, _extraSam);
aKey.values(range);
aKey.subKeys(range);
}
}
void WinRegistryConfiguration::removeRaw(const std::string& key)
{
throw Poco::NotImplementedException("Removing a key in a WinRegistryConfiguration");
}
std::string WinRegistryConfiguration::ConvertToRegFormat(const std::string& key, std::string& value) const
{
std::size_t pos = key.rfind('.');
if (pos == std::string::npos)
{
value = key;
return std::string();
}
std::string prefix(key.substr(0,pos));
value = key.substr(pos+1);
Poco::translateInPlace(prefix, ".", "\\");
return prefix;
}
} } // namespace Poco::Util
#endif // !defined(_WIN32_WCE)
//
// WinRegistryConfiguration.cpp
//
// $Id: //poco/1.4/Util/src/WinRegistryConfiguration.cpp#3 $
//
// Library: Util
// Package: Windows
// Module: WinRegistryConfiguration
//
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#if !defined(_WIN32_WCE)
#include "Poco/Util/WinRegistryConfiguration.h"
#include "Poco/Util/WinRegistryKey.h"
#include "Poco/NumberFormatter.h"
#include "Poco/NumberParser.h"
#include "Poco/Exception.h"
namespace Poco {
namespace Util {
WinRegistryConfiguration::WinRegistryConfiguration(const std::string& rootPath, REGSAM extraSam): _rootPath(rootPath), _extraSam(extraSam)
{
// rootPath must end with backslash
std::string::iterator it = _rootPath.end();
if (*(--it) != '\\')
_rootPath.append("\\");
}
WinRegistryConfiguration::~WinRegistryConfiguration()
{
}
bool WinRegistryConfiguration::getRaw(const std::string& key, std::string& value) const
{
std::string keyName;
std::string fullPath = _rootPath + ConvertToRegFormat(key, keyName);
WinRegistryKey aKey(fullPath, true, _extraSam);
bool exists = aKey.exists(keyName);
if (exists)
{
WinRegistryKey::Type type = aKey.type(keyName);
switch (type)
{
case WinRegistryKey::REGT_STRING:
value = aKey.getString(keyName);
break;
case WinRegistryKey::REGT_STRING_EXPAND:
value = aKey.getStringExpand(keyName);
break;
case WinRegistryKey::REGT_DWORD:
value = Poco::NumberFormatter::format(aKey.getInt(keyName));
break;
default:
exists = false;
}
}
return exists;
}
void WinRegistryConfiguration::setRaw(const std::string& key, const std::string& value)
{
std::string keyName;
std::string fullPath = _rootPath+ConvertToRegFormat(key, keyName);
WinRegistryKey aKey(fullPath, false, _extraSam);
aKey.setString(keyName, value);
}
void WinRegistryConfiguration::enumerate(const std::string& key, Keys& range) const
{
if (key.empty())
{
// return all root level keys
range.push_back("HKEY_CLASSES_ROOT");
range.push_back("HKEY_CURRENT_CONFIG");
range.push_back("HKEY_CURRENT_USER");
range.push_back("HKEY_LOCAL_MACHINE");
range.push_back("HKEY_PERFORMANCE_DATA");
range.push_back("HKEY_USERS");
}
else
{
std::string keyName;
std::string fullPath = _rootPath+ConvertToRegFormat(key, keyName);
WinRegistryKey aKey(fullPath, true, _extraSam);
aKey.values(range);
aKey.subKeys(range);
}
}
void WinRegistryConfiguration::removeRaw(const std::string& key)
{
throw Poco::NotImplementedException("Removing a key in a WinRegistryConfiguration");
}
std::string WinRegistryConfiguration::ConvertToRegFormat(const std::string& key, std::string& value) const
{
std::size_t pos = key.rfind('.');
if (pos == std::string::npos)
{
value = key;
return std::string();
}
std::string prefix(key.substr(0,pos));
value = key.substr(pos+1);
Poco::translateInPlace(prefix, ".", "\\");
return prefix;
}
} } // namespace Poco::Util
#endif // !defined(_WIN32_WCE)

File diff suppressed because it is too large Load Diff

View File

@@ -1,352 +1,352 @@
//
// WinService.cpp
//
// $Id: //poco/1.4/Util/src/WinService.cpp#4 $
//
// Library: Util
// Package: Windows
// Module: WinService
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#if !defined(_WIN32_WCE)
#include "Poco/Util/WinService.h"
#include "Poco/Util/WinRegistryKey.h"
#include "Poco/Thread.h"
#include "Poco/Exception.h"
#if defined(POCO_WIN32_UTF8)
#include "Poco/UnicodeConverter.h"
#endif
using Poco::Thread;
using Poco::SystemException;
using Poco::NotFoundException;
using Poco::OutOfMemoryException;
namespace Poco {
namespace Util {
const int WinService::STARTUP_TIMEOUT = 30000;
const std::string WinService::REGISTRY_KEY("SYSTEM\\CurrentControlSet\\Services\\");
const std::string WinService::REGISTRY_DESCRIPTION("Description");
WinService::WinService(const std::string& name):
_name(name),
_svcHandle(0)
{
_scmHandle = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
if (!_scmHandle) throw SystemException("cannot open Service Control Manager");
}
WinService::~WinService()
{
close();
CloseServiceHandle(_scmHandle);
}
const std::string& WinService::name() const
{
return _name;
}
std::string WinService::displayName() const
{
POCO_LPQUERY_SERVICE_CONFIG pSvcConfig = config();
#if defined(POCO_WIN32_UTF8)
std::wstring udispName(pSvcConfig->lpDisplayName);
std::string dispName;
Poco::UnicodeConverter::toUTF8(udispName, dispName);
#else
std::string dispName(pSvcConfig->lpDisplayName);
#endif
LocalFree(pSvcConfig);
return dispName;
}
std::string WinService::path() const
{
POCO_LPQUERY_SERVICE_CONFIG pSvcConfig = config();
#if defined(POCO_WIN32_UTF8)
std::wstring upath(pSvcConfig->lpBinaryPathName);
std::string path;
UnicodeConverter::toUTF8(upath, path);
#else
std::string path(pSvcConfig->lpBinaryPathName);
#endif
LocalFree(pSvcConfig);
return path;
}
void WinService::registerService(const std::string& path, const std::string& displayName)
{
close();
#if defined(POCO_WIN32_UTF8)
std::wstring uname;
Poco::UnicodeConverter::toUTF16(_name, uname);
std::wstring udisplayName;
Poco::UnicodeConverter::toUTF16(displayName, udisplayName);
std::wstring upath;
Poco::UnicodeConverter::toUTF16(path, upath);
_svcHandle = CreateServiceW(
_scmHandle,
uname.c_str(),
udisplayName.c_str(),
SERVICE_ALL_ACCESS,
SERVICE_WIN32_OWN_PROCESS,
SERVICE_DEMAND_START,
SERVICE_ERROR_NORMAL,
upath.c_str(),
NULL, NULL, NULL, NULL, NULL);
#else
_svcHandle = CreateService(
_scmHandle,
_name.c_str(),
displayName.c_str(),
SERVICE_ALL_ACCESS,
SERVICE_WIN32_OWN_PROCESS,
SERVICE_DEMAND_START,
SERVICE_ERROR_NORMAL,
path.c_str(),
NULL, NULL, NULL, NULL, NULL);
#endif
if (!_svcHandle)
throw SystemException("cannot register service", _name);
}
void WinService::registerService(const std::string& path)
{
registerService(path, _name);
}
void WinService::unregisterService()
{
open();
if (!DeleteService(_svcHandle))
throw SystemException("cannot unregister service", _name);
}
bool WinService::isRegistered() const
{
return tryOpen();
}
bool WinService::isRunning() const
{
open();
SERVICE_STATUS ss;
if (!QueryServiceStatus(_svcHandle, &ss))
throw SystemException("cannot query service status", _name);
return ss.dwCurrentState == SERVICE_RUNNING;
}
void WinService::start()
{
open();
if (!StartService(_svcHandle, 0, NULL))
throw SystemException("cannot start service", _name);
SERVICE_STATUS svcStatus;
long msecs = 0;
while (msecs < STARTUP_TIMEOUT)
{
if (!QueryServiceStatus(_svcHandle, &svcStatus)) break;
if (svcStatus.dwCurrentState != SERVICE_START_PENDING) break;
Thread::sleep(250);
msecs += 250;
}
if (!QueryServiceStatus(_svcHandle, &svcStatus))
throw SystemException("cannot query status of starting service", _name);
else if (svcStatus.dwCurrentState != SERVICE_RUNNING)
throw SystemException("service failed to start within a reasonable time", _name);
}
void WinService::stop()
{
open();
SERVICE_STATUS svcStatus;
if (!ControlService(_svcHandle, SERVICE_CONTROL_STOP, &svcStatus))
throw SystemException("cannot stop service", _name);
}
void WinService::setStartup(WinService::Startup startup)
{
open();
DWORD startType;
switch (startup)
{
case SVC_AUTO_START:
startType = SERVICE_AUTO_START;
break;
case SVC_MANUAL_START:
startType = SERVICE_DEMAND_START;
break;
case SVC_DISABLED:
startType = SERVICE_DISABLED;
break;
default:
startType = SERVICE_NO_CHANGE;
}
if (!ChangeServiceConfig(_svcHandle, SERVICE_NO_CHANGE, startType, SERVICE_NO_CHANGE, NULL, NULL, NULL, NULL, NULL, NULL, NULL))
{
throw SystemException("cannot change service startup mode");
}
}
WinService::Startup WinService::getStartup() const
{
POCO_LPQUERY_SERVICE_CONFIG pSvcConfig = config();
Startup result;
switch (pSvcConfig->dwStartType)
{
case SERVICE_AUTO_START:
case SERVICE_BOOT_START:
case SERVICE_SYSTEM_START:
result = SVC_AUTO_START;
break;
case SERVICE_DEMAND_START:
result = SVC_MANUAL_START;
break;
case SERVICE_DISABLED:
result = SVC_DISABLED;
break;
default:
poco_debugger();
result = SVC_MANUAL_START;
}
LocalFree(pSvcConfig);
return result;
}
void WinService::setDescription(const std::string& description)
{
std::string key(REGISTRY_KEY);
key += _name;
WinRegistryKey regKey(HKEY_LOCAL_MACHINE, key);
regKey.setString(REGISTRY_DESCRIPTION, description);
}
std::string WinService::getDescription() const
{
std::string key(REGISTRY_KEY);
key += _name;
WinRegistryKey regKey(HKEY_LOCAL_MACHINE, key, true);
return regKey.getString(REGISTRY_DESCRIPTION);
}
void WinService::open() const
{
if (!tryOpen())
throw NotFoundException("service does not exist", _name);
}
bool WinService::tryOpen() const
{
if (!_svcHandle)
{
#if defined(POCO_WIN32_UTF8)
std::wstring uname;
Poco::UnicodeConverter::toUTF16(_name, uname);
_svcHandle = OpenServiceW(_scmHandle, uname.c_str(), SERVICE_ALL_ACCESS);
#else
_svcHandle = OpenService(_scmHandle, _name.c_str(), SERVICE_ALL_ACCESS);
#endif
}
return _svcHandle != 0;
}
void WinService::close() const
{
if (_svcHandle)
{
CloseServiceHandle(_svcHandle);
_svcHandle = 0;
}
}
POCO_LPQUERY_SERVICE_CONFIG WinService::config() const
{
open();
int size = 4096;
DWORD bytesNeeded;
POCO_LPQUERY_SERVICE_CONFIG pSvcConfig = (POCO_LPQUERY_SERVICE_CONFIG) LocalAlloc(LPTR, size);
if (!pSvcConfig) throw OutOfMemoryException("cannot allocate service config buffer");
try
{
#if defined(POCO_WIN32_UTF8)
while (!QueryServiceConfigW(_svcHandle, pSvcConfig, size, &bytesNeeded))
#else
while (!QueryServiceConfig(_svcHandle, pSvcConfig, size, &bytesNeeded))
#endif
{
if (GetLastError() == ERROR_INSUFFICIENT_BUFFER)
{
LocalFree(pSvcConfig);
size = bytesNeeded;
pSvcConfig = (POCO_LPQUERY_SERVICE_CONFIG) LocalAlloc(LPTR, size);
}
else throw SystemException("cannot query service configuration", _name);
}
}
catch (...)
{
LocalFree(pSvcConfig);
throw;
}
return pSvcConfig;
}
} } // namespace Poco::Util
#endif // !defined(_WIN32_WCE)
//
// WinService.cpp
//
// $Id: //poco/1.4/Util/src/WinService.cpp#4 $
//
// Library: Util
// Package: Windows
// Module: WinService
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#if !defined(_WIN32_WCE)
#include "Poco/Util/WinService.h"
#include "Poco/Util/WinRegistryKey.h"
#include "Poco/Thread.h"
#include "Poco/Exception.h"
#if defined(POCO_WIN32_UTF8)
#include "Poco/UnicodeConverter.h"
#endif
using Poco::Thread;
using Poco::SystemException;
using Poco::NotFoundException;
using Poco::OutOfMemoryException;
namespace Poco {
namespace Util {
const int WinService::STARTUP_TIMEOUT = 30000;
const std::string WinService::REGISTRY_KEY("SYSTEM\\CurrentControlSet\\Services\\");
const std::string WinService::REGISTRY_DESCRIPTION("Description");
WinService::WinService(const std::string& name):
_name(name),
_svcHandle(0)
{
_scmHandle = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
if (!_scmHandle) throw SystemException("cannot open Service Control Manager");
}
WinService::~WinService()
{
close();
CloseServiceHandle(_scmHandle);
}
const std::string& WinService::name() const
{
return _name;
}
std::string WinService::displayName() const
{
POCO_LPQUERY_SERVICE_CONFIG pSvcConfig = config();
#if defined(POCO_WIN32_UTF8)
std::wstring udispName(pSvcConfig->lpDisplayName);
std::string dispName;
Poco::UnicodeConverter::toUTF8(udispName, dispName);
#else
std::string dispName(pSvcConfig->lpDisplayName);
#endif
LocalFree(pSvcConfig);
return dispName;
}
std::string WinService::path() const
{
POCO_LPQUERY_SERVICE_CONFIG pSvcConfig = config();
#if defined(POCO_WIN32_UTF8)
std::wstring upath(pSvcConfig->lpBinaryPathName);
std::string path;
UnicodeConverter::toUTF8(upath, path);
#else
std::string path(pSvcConfig->lpBinaryPathName);
#endif
LocalFree(pSvcConfig);
return path;
}
void WinService::registerService(const std::string& path, const std::string& displayName)
{
close();
#if defined(POCO_WIN32_UTF8)
std::wstring uname;
Poco::UnicodeConverter::toUTF16(_name, uname);
std::wstring udisplayName;
Poco::UnicodeConverter::toUTF16(displayName, udisplayName);
std::wstring upath;
Poco::UnicodeConverter::toUTF16(path, upath);
_svcHandle = CreateServiceW(
_scmHandle,
uname.c_str(),
udisplayName.c_str(),
SERVICE_ALL_ACCESS,
SERVICE_WIN32_OWN_PROCESS,
SERVICE_DEMAND_START,
SERVICE_ERROR_NORMAL,
upath.c_str(),
NULL, NULL, NULL, NULL, NULL);
#else
_svcHandle = CreateService(
_scmHandle,
_name.c_str(),
displayName.c_str(),
SERVICE_ALL_ACCESS,
SERVICE_WIN32_OWN_PROCESS,
SERVICE_DEMAND_START,
SERVICE_ERROR_NORMAL,
path.c_str(),
NULL, NULL, NULL, NULL, NULL);
#endif
if (!_svcHandle)
throw SystemException("cannot register service", _name);
}
void WinService::registerService(const std::string& path)
{
registerService(path, _name);
}
void WinService::unregisterService()
{
open();
if (!DeleteService(_svcHandle))
throw SystemException("cannot unregister service", _name);
}
bool WinService::isRegistered() const
{
return tryOpen();
}
bool WinService::isRunning() const
{
open();
SERVICE_STATUS ss;
if (!QueryServiceStatus(_svcHandle, &ss))
throw SystemException("cannot query service status", _name);
return ss.dwCurrentState == SERVICE_RUNNING;
}
void WinService::start()
{
open();
if (!StartService(_svcHandle, 0, NULL))
throw SystemException("cannot start service", _name);
SERVICE_STATUS svcStatus;
long msecs = 0;
while (msecs < STARTUP_TIMEOUT)
{
if (!QueryServiceStatus(_svcHandle, &svcStatus)) break;
if (svcStatus.dwCurrentState != SERVICE_START_PENDING) break;
Thread::sleep(250);
msecs += 250;
}
if (!QueryServiceStatus(_svcHandle, &svcStatus))
throw SystemException("cannot query status of starting service", _name);
else if (svcStatus.dwCurrentState != SERVICE_RUNNING)
throw SystemException("service failed to start within a reasonable time", _name);
}
void WinService::stop()
{
open();
SERVICE_STATUS svcStatus;
if (!ControlService(_svcHandle, SERVICE_CONTROL_STOP, &svcStatus))
throw SystemException("cannot stop service", _name);
}
void WinService::setStartup(WinService::Startup startup)
{
open();
DWORD startType;
switch (startup)
{
case SVC_AUTO_START:
startType = SERVICE_AUTO_START;
break;
case SVC_MANUAL_START:
startType = SERVICE_DEMAND_START;
break;
case SVC_DISABLED:
startType = SERVICE_DISABLED;
break;
default:
startType = SERVICE_NO_CHANGE;
}
if (!ChangeServiceConfig(_svcHandle, SERVICE_NO_CHANGE, startType, SERVICE_NO_CHANGE, NULL, NULL, NULL, NULL, NULL, NULL, NULL))
{
throw SystemException("cannot change service startup mode");
}
}
WinService::Startup WinService::getStartup() const
{
POCO_LPQUERY_SERVICE_CONFIG pSvcConfig = config();
Startup result;
switch (pSvcConfig->dwStartType)
{
case SERVICE_AUTO_START:
case SERVICE_BOOT_START:
case SERVICE_SYSTEM_START:
result = SVC_AUTO_START;
break;
case SERVICE_DEMAND_START:
result = SVC_MANUAL_START;
break;
case SERVICE_DISABLED:
result = SVC_DISABLED;
break;
default:
poco_debugger();
result = SVC_MANUAL_START;
}
LocalFree(pSvcConfig);
return result;
}
void WinService::setDescription(const std::string& description)
{
std::string key(REGISTRY_KEY);
key += _name;
WinRegistryKey regKey(HKEY_LOCAL_MACHINE, key);
regKey.setString(REGISTRY_DESCRIPTION, description);
}
std::string WinService::getDescription() const
{
std::string key(REGISTRY_KEY);
key += _name;
WinRegistryKey regKey(HKEY_LOCAL_MACHINE, key, true);
return regKey.getString(REGISTRY_DESCRIPTION);
}
void WinService::open() const
{
if (!tryOpen())
throw NotFoundException("service does not exist", _name);
}
bool WinService::tryOpen() const
{
if (!_svcHandle)
{
#if defined(POCO_WIN32_UTF8)
std::wstring uname;
Poco::UnicodeConverter::toUTF16(_name, uname);
_svcHandle = OpenServiceW(_scmHandle, uname.c_str(), SERVICE_ALL_ACCESS);
#else
_svcHandle = OpenService(_scmHandle, _name.c_str(), SERVICE_ALL_ACCESS);
#endif
}
return _svcHandle != 0;
}
void WinService::close() const
{
if (_svcHandle)
{
CloseServiceHandle(_svcHandle);
_svcHandle = 0;
}
}
POCO_LPQUERY_SERVICE_CONFIG WinService::config() const
{
open();
int size = 4096;
DWORD bytesNeeded;
POCO_LPQUERY_SERVICE_CONFIG pSvcConfig = (POCO_LPQUERY_SERVICE_CONFIG) LocalAlloc(LPTR, size);
if (!pSvcConfig) throw OutOfMemoryException("cannot allocate service config buffer");
try
{
#if defined(POCO_WIN32_UTF8)
while (!QueryServiceConfigW(_svcHandle, pSvcConfig, size, &bytesNeeded))
#else
while (!QueryServiceConfig(_svcHandle, pSvcConfig, size, &bytesNeeded))
#endif
{
if (GetLastError() == ERROR_INSUFFICIENT_BUFFER)
{
LocalFree(pSvcConfig);
size = bytesNeeded;
pSvcConfig = (POCO_LPQUERY_SERVICE_CONFIG) LocalAlloc(LPTR, size);
}
else throw SystemException("cannot query service configuration", _name);
}
}
catch (...)
{
LocalFree(pSvcConfig);
throw;
}
return pSvcConfig;
}
} } // namespace Poco::Util
#endif // !defined(_WIN32_WCE)

View File

@@ -1,486 +1,486 @@
//
// XMLConfiguration.cpp
//
// $Id: //poco/1.4/Util/src/XMLConfiguration.cpp#2 $
//
// Library: Util
// Package: Configuration
// Module: XMLConfiguration
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Util/XMLConfiguration.h"
#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('.')
{
}
XMLConfiguration::XMLConfiguration(char delim):
_delim(delim)
{
}
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)
{
poco_check_ptr (pInputSource);
Poco::XML::DOMParser parser;
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(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
//
// XMLConfiguration.cpp
//
// $Id: //poco/1.4/Util/src/XMLConfiguration.cpp#2 $
//
// Library: Util
// Package: Configuration
// Module: XMLConfiguration
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Util/XMLConfiguration.h"
#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('.')
{
}
XMLConfiguration::XMLConfiguration(char delim):
_delim(delim)
{
}
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)
{
poco_check_ptr (pInputSource);
Poco::XML::DOMParser parser;
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(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