initial import

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

View File

@@ -0,0 +1,97 @@
//
// ASCIIEncoding.cpp
//
// $Id: //poco/1.1.0/Foundation/src/ASCIIEncoding.cpp#2 $
//
// Library: Foundation
// Package: Text
// Module: ASCIIEncoding
//
// 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 "Foundation/ASCIIEncoding.h"
Foundation_BEGIN
const TextEncoding::CharacterMap ASCIIEncoding::_charMap =
{
/* 00 */ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
/* 10 */ 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
/* 20 */ 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f,
/* 30 */ 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f,
/* 40 */ 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f,
/* 50 */ 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f,
/* 60 */ 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f,
/* 70 */ 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f,
/* 80 */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
/* 90 */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
/* a0 */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
/* b0 */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
/* c0 */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
/* d0 */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
/* e0 */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
/* f0 */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
};
ASCIIEncoding::ASCIIEncoding()
{
}
ASCIIEncoding::~ASCIIEncoding()
{
}
const TextEncoding::CharacterMap& ASCIIEncoding::characterMap() const
{
return _charMap;
}
int ASCIIEncoding::convert(const unsigned char* bytes) const
{
return *bytes;
}
int ASCIIEncoding::convert(int ch, unsigned char* bytes, int length) const
{
if (ch >= 0 && ch <= 127)
{
*bytes = (unsigned char) ch;
return 1;
}
else return 0;
}
Foundation_END

View File

@@ -0,0 +1,172 @@
//
// ArchiveStrategy.cpp
//
// $Id: //poco/1.1.0/Foundation/src/ArchiveStrategy.cpp#2 $
//
// Library: Foundation
// Package: Logging
// Module: FileChannel
//
// 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 "Foundation/ArchiveStrategy.h"
#include "Foundation/NumberFormatter.h"
#include "Foundation/File.h"
#include "Foundation/Path.h"
#include "Foundation/DeflatingStream.h"
#include "Foundation/StreamCopier.h"
#include "Foundation/Exception.h"
#include <fstream>
Foundation_BEGIN
//
// ArchiveStrategy
//
ArchiveStrategy::ArchiveStrategy(): _compress(false)
{
}
ArchiveStrategy::~ArchiveStrategy()
{
}
void ArchiveStrategy::compress(bool flag)
{
_compress = flag;
}
void ArchiveStrategy::moveFile(const std::string& oldPath, const std::string& newPath)
{
bool compressed = false;
Path p(oldPath);
File f(oldPath);
if (!f.exists())
{
f = oldPath + ".gz";
compressed = true;
}
std::string mvPath(newPath);
if (_compress || compressed)
mvPath.append(".gz");
if (!_compress || compressed)
{
f.renameTo(mvPath);
}
else
{
std::ifstream istr(f.path().c_str(), std::ios::binary | std::ios::in);
if (!istr.good()) throw OpenFileException(oldPath);
std::ofstream ostr(mvPath.c_str(), std::ios::binary | std::ios::out);
if (ostr.good())
{
DeflatingOutputStream deflater(ostr, DeflatingStreamBuf::STREAM_GZIP);
StreamCopier::copyStream(istr, deflater);
deflater.close();
ostr.close();
istr.close();
f.remove();
}
else throw CreateFileException(mvPath);
}
}
bool ArchiveStrategy::exists(const std::string& name)
{
File f(name);
if (f.exists())
{
return true;
}
else if (_compress)
{
std::string gzName(name);
gzName.append(".gz");
File gzf(gzName);
return gzf.exists();
}
else return false;
}
//
// ArchiveByNumberStrategy
//
ArchiveByNumberStrategy::ArchiveByNumberStrategy()
{
}
ArchiveByNumberStrategy::~ArchiveByNumberStrategy()
{
}
LogFile* ArchiveByNumberStrategy::archive(LogFile* pFile)
{
std::string basePath = pFile->path();
delete pFile;
int n = -1;
std::string path;
do
{
path = basePath;
path.append(".");
path.append(NumberFormatter::format(++n));
}
while (exists(path));
while (n >= 0)
{
std::string oldPath = basePath;
if (n > 0)
{
oldPath.append(".");
oldPath.append(NumberFormatter::format(n - 1));
}
std::string newPath = basePath;
newPath.append(".");
newPath.append(NumberFormatter::format(n));
moveFile(oldPath, newPath);
--n;
}
return new LogFile(basePath);
}
Foundation_END

View File

@@ -0,0 +1,147 @@
//
// AsyncChannel.cpp
//
// $Id: //poco/1.1.0/Foundation/src/AsyncChannel.cpp#2 $
//
// Library: Foundation
// Package: Logging
// Module: AsyncChannel
//
// 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 "Foundation/AsyncChannel.h"
#include "Foundation/Notification.h"
#include "Foundation/Message.h"
#include "Foundation/Formatter.h"
#include "Foundation/AutoPtr.h"
#include "Foundation/LoggingRegistry.h"
Foundation_BEGIN
class MessageNotification: public Notification
{
public:
MessageNotification(const Message& msg)
{
_msg = msg;
}
~MessageNotification()
{
}
const Message& message() const
{
return _msg;
}
private:
Message _msg;
};
AsyncChannel::AsyncChannel(Channel* pChannel): _pChannel(pChannel), _thread("AsyncChannel")
{
if (_pChannel) _pChannel->duplicate();
}
AsyncChannel::~AsyncChannel()
{
close();
if (_pChannel) _pChannel->release();
}
void AsyncChannel::setChannel(Channel* pChannel)
{
FastMutex::ScopedLock lock(_mutex);
if (_pChannel) _pChannel->release();
_pChannel = pChannel;
if (_pChannel) _pChannel->duplicate();
}
Channel* AsyncChannel::getChannel() const
{
return _pChannel;
}
void AsyncChannel::open()
{
_thread.start(*this);
}
void AsyncChannel::close()
{
if (_thread.isRunning())
{
while (!_queue.empty()) Thread::sleep(100);
_queue.wakeUpAll();
_thread.join();
}
}
void AsyncChannel::log(const Message& msg)
{
_queue.enqueueNotification(new MessageNotification(msg));
}
void AsyncChannel::setProperty(const std::string& name, const std::string& value)
{
if (name == "channel")
setChannel(LoggingRegistry::defaultRegistry().channelForName(value));
else
Channel::setProperty(name, value);
}
void AsyncChannel::run()
{
AutoPtr<Notification> nf = _queue.waitDequeueNotification();
while (nf)
{
MessageNotification* pNf = dynamic_cast<MessageNotification*>(nf.get());
{
FastMutex::ScopedLock lock(_mutex);
if (pNf && _pChannel) _pChannel->log(pNf->message());
}
nf = _queue.waitDequeueNotification();
}
}
Foundation_END

View File

@@ -0,0 +1,153 @@
//
// Base64Decoder.cpp
//
// $Id: //poco/1.1.0/Foundation/src/Base64Decoder.cpp#2 $
//
// Library: Foundation
// Package: Streams
// Module: Base64
//
// 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 "Foundation/Base64Decoder.h"
#include "Foundation/Base64Encoder.h"
#include "Foundation/Exception.h"
#include "Foundation/Mutex.h"
Foundation_BEGIN
unsigned char Base64DecoderBuf::IN_ENCODING[256];
bool Base64DecoderBuf::IN_ENCODING_INIT = false;
Base64DecoderBuf::Base64DecoderBuf(std::istream& istr):
_groupLength(0),
_groupIndex(0),
_istr(istr)
{
static FastMutex mutex;
FastMutex::ScopedLock lock(mutex);
if (!IN_ENCODING_INIT)
{
for (int i = 0; i < sizeof(IN_ENCODING); i++)
{
IN_ENCODING[i] = 0xFF;
}
for (int i = 0; i < sizeof(Base64EncoderBuf::OUT_ENCODING); i++)
{
IN_ENCODING[Base64EncoderBuf::OUT_ENCODING[i]] = i;
}
IN_ENCODING['='] = 0;
IN_ENCODING_INIT = true;
}
}
Base64DecoderBuf::~Base64DecoderBuf()
{
}
int Base64DecoderBuf::readFromDevice()
{
if (_groupIndex < _groupLength)
{
return _group[_groupIndex++];
}
else
{
unsigned char buffer[4];
int c;
if ((c = readOne()) == -1) return -1;
buffer[0] = (unsigned char) c;
if (IN_ENCODING[buffer[0]] == 0xFF) throw DataFormatException();
if ((c = readOne()) == -1) return -1;
buffer[1] = (unsigned char) c;
if (IN_ENCODING[buffer[1]] == 0xFF) throw DataFormatException();
if ((c = readOne()) == -1) return -1;
buffer[2] = c;
if (IN_ENCODING[buffer[2]] == 0xFF) throw DataFormatException();
if ((c = readOne()) == -1) return -1;
buffer[3] = c;
if (IN_ENCODING[buffer[3]] == 0xFF) throw DataFormatException();
_group[0] = (IN_ENCODING[buffer[0]] << 2) | (IN_ENCODING[buffer[1]] >> 4);
_group[1] = ((IN_ENCODING[buffer[1]] & 0x0F) << 4) | (IN_ENCODING[buffer[2]] >> 2);
_group[2] = (IN_ENCODING[buffer[2]] << 6) | IN_ENCODING[buffer[3]];
if (buffer[2] == '=')
_groupLength = 1;
else if (buffer[3] == '=')
_groupLength = 2;
else
_groupLength = 3;
_groupIndex = 1;
return _group[0];
}
}
int Base64DecoderBuf::readOne()
{
int ch = _istr.get();
while (ch == ' ' || ch == '\r' || ch == '\t' || ch == '\n')
ch = _istr.get();
return ch;
}
Base64DecoderIOS::Base64DecoderIOS(std::istream& istr): _buf(istr)
{
poco_ios_init(&_buf);
}
Base64DecoderIOS::~Base64DecoderIOS()
{
}
Base64DecoderBuf* Base64DecoderIOS::rdbuf()
{
return &_buf;
}
Base64Decoder::Base64Decoder(std::istream& istr): Base64DecoderIOS(istr), std::istream(&_buf)
{
}
Base64Decoder::~Base64Decoder()
{
}
Foundation_END

View File

@@ -0,0 +1,181 @@
//
// Base64Encoder.cpp
//
// $Id: //poco/1.1.0/Foundation/src/Base64Encoder.cpp#2 $
//
// Library: Foundation
// Package: Streams
// Module: Base64
//
// 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 "Foundation/Base64Encoder.h"
Foundation_BEGIN
const unsigned char Base64EncoderBuf::OUT_ENCODING[64] =
{
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
'w', 'x', 'y', 'z', '0', '1', '2', '3',
'4', '5', '6', '7', '8', '9', '+', '/'
};
Base64EncoderBuf::Base64EncoderBuf(std::ostream& ostr):
_groupLength(0),
_pos(0),
_lineLength(72),
_ostr(ostr)
{
}
Base64EncoderBuf::~Base64EncoderBuf()
{
try
{
close();
}
catch (...)
{
}
}
void Base64EncoderBuf::setLineLength(int lineLength)
{
poco_assert (lineLength > 0);
_lineLength = lineLength;
}
int Base64EncoderBuf::getLineLength() const
{
return _lineLength;
}
int Base64EncoderBuf::writeToDevice(char c)
{
_group[_groupLength++] = (unsigned char) c;
if (_groupLength == 3)
{
unsigned char idx;
idx = _group[0] >> 2;
_ostr.put(OUT_ENCODING[idx]);
idx = ((_group[0] & 0x03) << 4) | (_group[1] >> 4);
_ostr.put(OUT_ENCODING[idx]);
idx = ((_group[1] & 0x0F) << 2) | (_group[2] >> 6);
_ostr.put(OUT_ENCODING[idx]);
idx = _group[2] & 0x3F;
_ostr.put(OUT_ENCODING[idx]);
_pos += 4;
if (_pos >= _lineLength)
{
_ostr << "\r\n";
_pos = 0;
}
_groupLength = 0;
}
return _ostr ? charToInt(c) : -1;
}
int Base64EncoderBuf::close()
{
sync();
if (_groupLength == 1)
{
_group[1] = 0;
unsigned char idx;
idx = _group[0] >> 2;
_ostr.put(OUT_ENCODING[idx]);
idx = ((_group[0] & 0x03) << 4) | (_group[1] >> 4);
_ostr.put(OUT_ENCODING[idx]);
_ostr << "==";
}
else if (_groupLength == 2)
{
_group[2] = 0;
unsigned char idx;
idx = _group[0] >> 2;
_ostr.put(OUT_ENCODING[idx]);
idx = ((_group[0] & 0x03) << 4) | (_group[1] >> 4);
_ostr.put(OUT_ENCODING[idx]);
idx = ((_group[1] & 0x0F) << 2) | (_group[2] >> 6);
_ostr.put(OUT_ENCODING[idx]);
_ostr.put('=');
}
_ostr.flush();
_groupLength = 0;
return _ostr ? 0 : -1;
}
Base64EncoderIOS::Base64EncoderIOS(std::ostream& ostr): _buf(ostr)
{
poco_ios_init(&_buf);
}
Base64EncoderIOS::~Base64EncoderIOS()
{
}
int Base64EncoderIOS::close()
{
return _buf.close();
}
Base64EncoderBuf* Base64EncoderIOS::rdbuf()
{
return &_buf;
}
Base64Encoder::Base64Encoder(std::ostream& ostr): Base64EncoderIOS(ostr), std::ostream(&_buf)
{
}
Base64Encoder::~Base64Encoder()
{
}
Foundation_END

View File

@@ -0,0 +1,279 @@
//
// BinaryReader.cpp
//
// $Id: //poco/1.1.0/Foundation/src/BinaryReader.cpp#2 $
//
// Library: Foundation
// Package: Streams
// Module: BinaryReaderWriter
//
// 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 "Foundation/BinaryReader.h"
#include "Foundation/ByteOrder.h"
Foundation_BEGIN
BinaryReader::BinaryReader(std::istream& istr, StreamByteOrder byteOrder):
_istr(istr)
{
#if defined(POCO_ARCH_BIG_ENDIAN)
_flipBytes = (byteOrder == LITTLE_ENDIAN_BYTE_ORDER);
#else
_flipBytes = (byteOrder == BIG_ENDIAN_BYTE_ORDER);
#endif
}
BinaryReader::~BinaryReader()
{
}
BinaryReader& BinaryReader::operator >> (bool& value)
{
_istr.read((char*) &value, sizeof(value));
return *this;
}
BinaryReader& BinaryReader::operator >> (char& value)
{
_istr.read((char*) &value, sizeof(value));
return *this;
}
BinaryReader& BinaryReader::operator >> (unsigned char& value)
{
_istr.read((char*) &value, sizeof(value));
return *this;
}
BinaryReader& BinaryReader::operator >> (signed char& value)
{
_istr.read((char*) &value, sizeof(value));
return *this;
}
BinaryReader& BinaryReader::operator >> (short& value)
{
_istr.read((char*) &value, sizeof(value));
if (_flipBytes) value = ByteOrder::flipBytes(value);
return *this;
}
BinaryReader& BinaryReader::operator >> (unsigned short& value)
{
_istr.read((char*) &value, sizeof(value));
if (_flipBytes) value = ByteOrder::flipBytes(value);
return *this;
}
BinaryReader& BinaryReader::operator >> (int& value)
{
_istr.read((char*) &value, sizeof(value));
if (_flipBytes) value = ByteOrder::flipBytes(value);
return *this;
}
BinaryReader& BinaryReader::operator >> (unsigned int& value)
{
_istr.read((char*) &value, sizeof(value));
if (_flipBytes) value = ByteOrder::flipBytes(value);
return *this;
}
BinaryReader& BinaryReader::operator >> (long& value)
{
_istr.read((char*) &value, sizeof(value));
#if defined(POCO_LONG_IS_64_BIT)
if (_flipBytes) value = ByteOrder::flipBytes((Int64) value);
#else
if (_flipBytes) value = ByteOrder::flipBytes((Int32) value);
#endif
return *this;
}
BinaryReader& BinaryReader::operator >> (unsigned long& value)
{
_istr.read((char*) &value, sizeof(value));
#if defined(POCO_LONG_IS_64_BIT)
if (_flipBytes) value = ByteOrder::flipBytes((UInt64) value);
#else
if (_flipBytes) value = ByteOrder::flipBytes((UInt32) value);
#endif
return *this;
}
BinaryReader& BinaryReader::operator >> (float& value)
{
if (_flipBytes)
{
char* ptr = (char*) &value;
ptr += sizeof(value);
for (int i = 0; i < sizeof(value); ++i)
_istr.read(--ptr, 1);
}
else
{
_istr.read((char*) &value, sizeof(value));
}
return *this;
}
BinaryReader& BinaryReader::operator >> (double& value)
{
if (_flipBytes)
{
char* ptr = (char*) &value;
ptr += sizeof(value);
for (int i = 0; i < sizeof(value); ++i)
_istr.read(--ptr, 1);
}
else
{
_istr.read((char*) &value, sizeof(value));
}
return *this;
}
#if defined(POCO_HAVE_INT64) && !defined(POCO_LONG_IS_64_BIT)
BinaryReader& BinaryReader::operator >> (Int64& value)
{
_istr.read((char*) &value, sizeof(value));
if (_flipBytes) value = ByteOrder::flipBytes(value);
return *this;
}
BinaryReader& BinaryReader::operator >> (UInt64& value)
{
_istr.read((char*) &value, sizeof(value));
if (_flipBytes) value = ByteOrder::flipBytes(value);
return *this;
}
#endif
BinaryReader& BinaryReader::operator >> (std::string& value)
{
UInt32 size = 0;
read7BitEncoded(size);
value.clear();
value.reserve(size);
while (size--)
{
char c;
_istr.read(&c, 1);
value += c;
}
return *this;
}
void BinaryReader::read7BitEncoded(UInt32& value)
{
char c;
value = 0;
int s = 0;
do
{
c = 0;
_istr.read(&c, 1);
UInt32 x = (c & 0x7F);
x <<= s;
value += x;
s += 7;
}
while (c & 0x80);
}
#if defined(POCO_HAVE_INT64)
void BinaryReader::read7BitEncoded(UInt64& value)
{
char c;
value = 0;
int s = 0;
do
{
c = 0;
_istr.read(&c, 1);
UInt64 x = (c & 0x7F);
x <<= s;
value += x;
s += 7;
}
while (c & 0x80);
}
#endif
void BinaryReader::readRaw(int length, std::string& value)
{
value.clear();
value.reserve(length);
while (length--)
{
char c;
_istr.read(&c, 1);
value += c;
}
}
void BinaryReader::readBOM()
{
UInt32 bom;
_istr.read((char*) &bom, sizeof(bom));
_flipBytes = bom != 0xFEFF;
}
Foundation_END

View File

@@ -0,0 +1,328 @@
//
// BinaryWriter.cpp
//
// $Id: //poco/1.1.0/Foundation/src/BinaryWriter.cpp#2 $
//
// Library: Foundation
// Package: Streams
// Module: BinaryReaderWriter
//
// 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 "Foundation/BinaryWriter.h"
#include "Foundation/ByteOrder.h"
#include <string.h>
Foundation_BEGIN
BinaryWriter::BinaryWriter(std::ostream& ostr, StreamByteOrder byteOrder):
_ostr(ostr)
{
#if defined(POCO_ARCH_BIG_ENDIAN)
_flipBytes = (byteOrder == LITTLE_ENDIAN_BYTE_ORDER);
#else
_flipBytes = (byteOrder == BIG_ENDIAN_BYTE_ORDER);
#endif
}
BinaryWriter::~BinaryWriter()
{
}
BinaryWriter& BinaryWriter::operator << (bool value)
{
_ostr.write((const char*) &value, sizeof(value));
return *this;
}
BinaryWriter& BinaryWriter::operator << (char value)
{
_ostr.write((const char*) &value, sizeof(value));
return *this;
}
BinaryWriter& BinaryWriter::operator << (unsigned char value)
{
_ostr.write((const char*) &value, sizeof(value));
return *this;
}
BinaryWriter& BinaryWriter::operator << (signed char value)
{
_ostr.write((const char*) &value, sizeof(value));
return *this;
}
BinaryWriter& BinaryWriter::operator << (short value)
{
if (_flipBytes)
{
short fValue = ByteOrder::flipBytes(value);
_ostr.write((const char*) &fValue, sizeof(fValue));
}
else
{
_ostr.write((const char*) &value, sizeof(value));
}
return *this;
}
BinaryWriter& BinaryWriter::operator << (unsigned short value)
{
if (_flipBytes)
{
unsigned short fValue = ByteOrder::flipBytes(value);
_ostr.write((const char*) &fValue, sizeof(fValue));
}
else
{
_ostr.write((const char*) &value, sizeof(value));
}
return *this;
}
BinaryWriter& BinaryWriter::operator << (int value)
{
if (_flipBytes)
{
int fValue = ByteOrder::flipBytes(value);
_ostr.write((const char*) &fValue, sizeof(fValue));
}
else
{
_ostr.write((const char*) &value, sizeof(value));
}
return *this;
}
BinaryWriter& BinaryWriter::operator << (unsigned int value)
{
if (_flipBytes)
{
unsigned int fValue = ByteOrder::flipBytes(value);
_ostr.write((const char*) &fValue, sizeof(fValue));
}
else
{
_ostr.write((const char*) &value, sizeof(value));
}
return *this;
}
BinaryWriter& BinaryWriter::operator << (long value)
{
if (_flipBytes)
{
#if defined(POCO_LONG_IS_64_BIT)
long fValue = ByteOrder::flipBytes((Int64) value);
#else
long fValue = ByteOrder::flipBytes((Int32) value);
#endif
_ostr.write((const char*) &fValue, sizeof(fValue));
}
else
{
_ostr.write((const char*) &value, sizeof(value));
}
return *this;
}
BinaryWriter& BinaryWriter::operator << (unsigned long value)
{
if (_flipBytes)
{
#if defined(POCO_LONG_IS_64_BIT)
long fValue = ByteOrder::flipBytes((UInt64) value);
#else
long fValue = ByteOrder::flipBytes((UInt32) value);
#endif
_ostr.write((const char*) &fValue, sizeof(fValue));
}
else
{
_ostr.write((const char*) &value, sizeof(value));
}
return *this;
}
BinaryWriter& BinaryWriter::operator << (float value)
{
if (_flipBytes)
{
const char* ptr = (const char*) &value;
ptr += sizeof(value);
for (int i = 0; i < sizeof(value); ++i)
_ostr.write(--ptr, 1);
}
else
{
_ostr.write((const char*) &value, sizeof(value));
}
return *this;
}
BinaryWriter& BinaryWriter::operator << (double value)
{
if (_flipBytes)
{
const char* ptr = (const char*) &value;
ptr += sizeof(value);
for (int i = 0; i < sizeof(value); ++i)
_ostr.write(--ptr, 1);
}
else
{
_ostr.write((const char*) &value, sizeof(value));
}
return *this;
}
#if defined(POCO_HAVE_INT64) && !defined(POCO_LONG_IS_64_BIT)
BinaryWriter& BinaryWriter::operator << (Int64 value)
{
if (_flipBytes)
{
Int64 fValue = ByteOrder::flipBytes(value);
_ostr.write((const char*) &fValue, sizeof(fValue));
}
else
{
_ostr.write((const char*) &value, sizeof(value));
}
return *this;
}
BinaryWriter& BinaryWriter::operator << (UInt64 value)
{
if (_flipBytes)
{
UInt64 fValue = ByteOrder::flipBytes(value);
_ostr.write((const char*) &fValue, sizeof(fValue));
}
else
{
_ostr.write((const char*) &value, sizeof(value));
}
return *this;
}
#endif
BinaryWriter& BinaryWriter::operator << (const std::string& value)
{
UInt32 length = (UInt32) value.size();
write7BitEncoded(length);
_ostr.write(value.data(), length);
return *this;
}
BinaryWriter& BinaryWriter::operator << (const char* value)
{
poco_check_ptr (value);
UInt32 length = (UInt32) strlen(value);
write7BitEncoded(length);
_ostr.write(value, length);
return *this;
}
void BinaryWriter::write7BitEncoded(UInt32 value)
{
do
{
unsigned char c = (unsigned char) (value & 0x7F);
value >>= 7;
if (value) c |= 0x80;
_ostr.write((const char*) &c, 1);
}
while (value);
}
#if defined(POCO_HAVE_INT64)
void BinaryWriter::write7BitEncoded(UInt64 value)
{
do
{
unsigned char c = (unsigned char) (value & 0x7F);
value >>= 7;
if (value) c |= 0x80;
_ostr.write((const char*) &c, 1);
}
while (value);
}
#endif
void BinaryWriter::writeRaw(const std::string& rawData)
{
_ostr.write(rawData.data(), (std::streamsize) rawData.length());
}
void BinaryWriter::writeBOM()
{
UInt32 value = 0xFEFF;
if (_flipBytes) value = ByteOrder::flipBytes(value);
_ostr.write((const char*) &value, sizeof(value));
}
void BinaryWriter::flush()
{
_ostr.flush();
}
Foundation_END

103
Foundation/src/Bugcheck.cpp Normal file
View File

@@ -0,0 +1,103 @@
//
// Bugcheck.cpp
//
// $Id: //poco/1.1.0/Foundation/src/Bugcheck.cpp#2 $
//
// Library: Foundation
// Package: Core
// Module: Bugcheck
//
// 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 "Foundation/Bugcheck.h"
#include "Foundation/Debugger.h"
#include "Foundation/Exception.h"
#include <sstream>
Foundation_BEGIN
void Bugcheck::assertion(const char* cond, const char* file, int line)
{
Debugger::enter(std::string("Assertion violation: ") + cond, file, line);
throw AssertionViolationException(what(cond, file, line));
}
void Bugcheck::nullPointer(const char* ptr, const char* file, int line)
{
Debugger::enter(std::string("NULL pointer: ") + ptr, file, line);
throw NullPointerException(what(ptr, file, line));
}
void Bugcheck::bugcheck(const char* file, int line)
{
Debugger::enter("Bugcheck", file, line);
throw BugcheckException(what(0, file, line));
}
void Bugcheck::bugcheck(const char* msg, const char* file, int line)
{
std::string m("Bugcheck");
if (msg)
{
m.append(": ");
m.append(msg);
}
Debugger::enter(m, file, line);
throw BugcheckException(what(msg, file, line));
}
void Bugcheck::debugger(const char* file, int line)
{
Debugger::enter(file, line);
}
void Bugcheck::debugger(const char* msg, const char* file, int line)
{
Debugger::enter(msg, file, line);
}
std::string Bugcheck::what(const char* msg, const char* file, int line)
{
std::ostringstream str;
if (msg) str << msg << " ";
str << "in file \"" << file << "\", line " << line;
return str.str();
}
Foundation_END

View File

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

View File

@@ -0,0 +1,75 @@
//
// Channel.cpp
//
// $Id: //poco/1.1.0/Foundation/src/Channel.cpp#2 $
//
// Library: Foundation
// Package: Logging
// Module: Channel
//
// 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 "Foundation/Channel.h"
Foundation_BEGIN
Channel::Channel()
{
}
Channel::~Channel()
{
}
void Channel::open()
{
}
void Channel::close()
{
}
void Channel::setProperty(const std::string& name, const std::string& value)
{
throw PropertyNotSupportedException(name);
}
std::string Channel::getProperty(const std::string& name) const
{
throw PropertyNotSupportedException(name);
}
Foundation_END

View File

@@ -0,0 +1,53 @@
//
// Configurable.cpp
//
// $Id: //poco/1.1.0/Foundation/src/Configurable.cpp#2 $
//
// Library: Foundation
// Package: Logging
// Module: Configurable
//
// 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 "Foundation/Configurable.h"
Foundation_BEGIN
Configurable::Configurable()
{
}
Configurable::~Configurable()
{
}
Foundation_END

View File

@@ -0,0 +1,71 @@
//
// ConsoleChannel.cpp
//
// $Id: //poco/1.1.0/Foundation/src/ConsoleChannel.cpp#2 $
//
// Library: Foundation
// Package: Logging
// Module: ConsoleChannel
//
// 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 "Foundation/ConsoleChannel.h"
#include "Foundation/Message.h"
#include <iostream>
Foundation_BEGIN
FastMutex ConsoleChannel::_mutex;
ConsoleChannel::ConsoleChannel(): _str(std::clog)
{
}
ConsoleChannel::ConsoleChannel(std::ostream& str): _str(str)
{
}
ConsoleChannel::~ConsoleChannel()
{
}
void ConsoleChannel::log(const Message& msg)
{
FastMutex::ScopedLock lock(_mutex);
_str << msg.getText() << std::endl;
}
Foundation_END

View File

@@ -0,0 +1,185 @@
//
// CountingStream.cpp
//
// $Id: //poco/1.1.0/Foundation/src/CountingStream.cpp#2 $
//
// Library: Foundation
// Package: Streams
// Module: CountingStream
//
// 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 "Foundation/CountingStream.h"
Foundation_BEGIN
CountingStreamBuf::CountingStreamBuf():
_pIstr(0),
_pOstr(0),
_chars(0),
_lines(0),
_pos(0)
{
}
CountingStreamBuf::CountingStreamBuf(std::istream& istr):
_pIstr(&istr),
_pOstr(0),
_chars(0),
_lines(0),
_pos(0)
{
}
CountingStreamBuf::CountingStreamBuf(std::ostream& ostr):
_pIstr(0),
_pOstr(&ostr),
_chars(0),
_lines(0),
_pos(0)
{
}
CountingStreamBuf::~CountingStreamBuf()
{
}
int CountingStreamBuf::readFromDevice()
{
if (_pIstr)
{
int c = _pIstr->get();
if (c != -1)
{
++_chars;
if (_pos++ == 0) ++_lines;
if (c == '\n') _pos = 0;
}
return c;
}
return -1;
}
int CountingStreamBuf::writeToDevice(char c)
{
++_chars;
if (_pos++ == 0) ++_lines;
if (c == '\n') _pos = 0;
if (_pOstr) _pOstr->put(c);
return charToInt(c);
}
void CountingStreamBuf::reset()
{
_chars = 0;
_lines = 0;
_pos = 0;
}
void CountingStreamBuf::setCurrentLineNumber(int line)
{
_lines = line;
}
CountingIOS::CountingIOS()
{
poco_ios_init(&_buf);
}
CountingIOS::CountingIOS(std::istream& istr): _buf(istr)
{
poco_ios_init(&_buf);
}
CountingIOS::CountingIOS(std::ostream& ostr): _buf(ostr)
{
poco_ios_init(&_buf);
}
CountingIOS::~CountingIOS()
{
}
void CountingIOS::reset()
{
_buf.reset();
}
void CountingIOS::setCurrentLineNumber(int line)
{
_buf.setCurrentLineNumber(line);
}
CountingStreamBuf* CountingIOS::rdbuf()
{
return &_buf;
}
CountingInputStream::CountingInputStream(std::istream& istr): CountingIOS(istr), std::istream(&_buf)
{
}
CountingInputStream::~CountingInputStream()
{
}
CountingOutputStream::CountingOutputStream(): std::ostream(&_buf)
{
}
CountingOutputStream::CountingOutputStream(std::ostream& ostr): CountingIOS(ostr), std::ostream(&_buf)
{
}
CountingOutputStream::~CountingOutputStream()
{
}
Foundation_END

387
Foundation/src/DateTime.cpp Normal file
View File

@@ -0,0 +1,387 @@
//
// DateTime.cpp
//
// $Id: //poco/1.1.0/Foundation/src/DateTime.cpp#2 $
//
// Library: Foundation
// Package: DateTime
// Module: DateTime
//
// 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 "Foundation/DateTime.h"
#include <algorithm>
#include <math.h>
Foundation_BEGIN
inline double DateTime::toJulianDay(Timestamp::UtcTimeVal utcTime)
{
double utcDays = double(utcTime)/864000000000.0;
return utcDays + 2299160.5; // first day of Gregorian reform (Oct 15 1582)
}
inline Timestamp::UtcTimeVal DateTime::toUtcTime(double julianDay)
{
return Timestamp::UtcTimeVal((julianDay - 2299160.5)*864000000000.0);
}
DateTime::DateTime()
{
Timestamp now;
_utcTime = now.utcTime();
_julianDay = toJulianDay(_utcTime);
computeGregorian();
}
DateTime::DateTime(const Timestamp& timestamp):
_utcTime(timestamp.utcTime()),
_julianDay(toJulianDay(_utcTime))
{
computeGregorian();
}
DateTime::DateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int microsecond):
_year(year),
_month(month),
_day(day),
_hour(hour),
_minute(minute),
_second(second),
_millisecond(millisecond),
_microsecond(microsecond)
{
poco_assert (year >= 0 && year <= 9999);
poco_assert (month >= 1 && month <= 12);
poco_assert (day >= 1 && day <= daysOfMonth(year, month));
poco_assert (hour >= 0 && hour <= 23);
poco_assert (minute >= 0 && minute <= 59);
poco_assert (second >= 0 && second <= 59);
poco_assert (millisecond >= 0 && millisecond <= 999);
poco_assert (microsecond >= 0 && microsecond <= 999);
_julianDay = toJulianDay(year, month, day, hour, minute, second, millisecond, microsecond);
_utcTime = toUtcTime(_julianDay);
}
DateTime::DateTime(double julianDay):
_utcTime(toUtcTime(julianDay)),
_julianDay(julianDay)
{
computeGregorian();
}
DateTime::DateTime(Timestamp::UtcTimeVal utcTime, Timestamp::TimeDiff diff):
_utcTime(utcTime + diff*10),
_julianDay(toJulianDay(_utcTime))
{
computeGregorian();
}
DateTime::DateTime(const DateTime& dateTime):
_utcTime(dateTime._utcTime),
_julianDay(dateTime._julianDay),
_year(dateTime._year),
_month(dateTime._month),
_day(dateTime._day),
_hour(dateTime._hour),
_minute(dateTime._minute),
_second(dateTime._second),
_millisecond(dateTime._millisecond),
_microsecond(dateTime._microsecond)
{
}
DateTime::~DateTime()
{
}
DateTime& DateTime::operator = (const DateTime& dateTime)
{
if (&dateTime != this)
{
_utcTime = dateTime._utcTime;
_julianDay = dateTime._julianDay;
_year = dateTime._year;
_month = dateTime._month;
_day = dateTime._day;
_hour = dateTime._hour;
_minute = dateTime._minute;
_second = dateTime._second;
_millisecond = dateTime._millisecond;
_microsecond = dateTime._microsecond;
}
return *this;
}
DateTime& DateTime::operator = (const Timestamp& timestamp)
{
_utcTime = timestamp.utcTime();
_julianDay = toJulianDay(_utcTime);
computeGregorian();
return *this;
}
DateTime& DateTime::operator = (double julianDay)
{
_julianDay = julianDay;
_utcTime = toUtcTime(julianDay);
computeGregorian();
return *this;
}
DateTime& DateTime::assign(int year, int month, int day, int hour, int minute, int second, int millisecond, int microsecond)
{
poco_assert (year >= 0 && year <= 9999);
poco_assert (month >= 1 && month <= 12);
poco_assert (day >= 1 && day <= daysOfMonth(year, month));
poco_assert (hour >= 0 && hour <= 23);
poco_assert (minute >= 0 && minute <= 59);
poco_assert (second >= 0 && second <= 59);
poco_assert (millisecond >= 0 && millisecond <= 999);
poco_assert (microsecond >= 0 && microsecond <= 999);
_julianDay = toJulianDay(year, month, day, hour, minute, second, millisecond, microsecond);
_utcTime = toUtcTime(_julianDay);
_year = year;
_month = month;
_day = day;
_hour = hour;
_minute = minute;
_second = second;
_millisecond = millisecond;
_microsecond = microsecond;
return *this;
}
void DateTime::swap(DateTime& dateTime)
{
std::swap(_utcTime, dateTime._utcTime);
std::swap(_julianDay, dateTime._julianDay);
std::swap(_year, dateTime._year);
std::swap(_month, dateTime._month);
std::swap(_day, dateTime._day);
std::swap(_hour, dateTime._hour);
std::swap(_minute, dateTime._minute);
std::swap(_second, dateTime._second);
std::swap(_millisecond, dateTime._millisecond);
std::swap(_microsecond, dateTime._microsecond);
}
int DateTime::dayOfWeek() const
{
return int((floor(_julianDay + 1.5))) % 7;
}
int DateTime::dayOfYear() const
{
int doy = 0;
for (int month = 1; month < _month; ++month)
doy += daysOfMonth(_year, month);
doy += _day;
return doy;
}
int DateTime::daysOfMonth(int year, int month)
{
poco_assert (month >= 1 && month <= 12);
static int daysOfMonthTable[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
if (month == 2 && isLeapYear(year))
return 29;
else
return daysOfMonthTable[month];
}
int DateTime::week(int firstDayOfWeek) const
{
poco_assert (firstDayOfWeek >= 0 && firstDayOfWeek <= 6);
/// find the first firstDayOfWeek.
int baseDay = 1;
while (DateTime(_year, 1, baseDay).dayOfWeek() != firstDayOfWeek) ++baseDay;
int doy = dayOfYear();
int offs = baseDay <= 4 ? 0 : 1;
if (doy < baseDay)
return offs;
else
return (doy - baseDay)/7 + 1 + offs;
}
DateTime DateTime::operator + (const Timespan& span) const
{
return DateTime(_utcTime, span.totalMicroseconds());
}
DateTime DateTime::operator - (const Timespan& span) const
{
return DateTime(_utcTime, -span.totalMicroseconds());
}
Timespan DateTime::operator - (const DateTime& dateTime) const
{
return Timespan((_utcTime - dateTime._utcTime)/10);
}
DateTime& DateTime::operator += (const Timespan& span)
{
_utcTime += span.totalMicroseconds()*10;
_julianDay = toJulianDay(_utcTime);
computeGregorian();
return *this;
}
DateTime& DateTime::operator -= (const Timespan& span)
{
_utcTime -= span.totalMicroseconds()*10;
_julianDay = toJulianDay(_utcTime);
computeGregorian();
return *this;
}
double DateTime::toJulianDay(int year, int month, int day, int hour, int minute, int second, int millisecond, int microsecond)
{
// lookup table for (153*month - 457)/5 - note that 3 <= month <= 14.
static int lookup[] = {-91, -60, -30, 0, 31, 61, 92, 122, 153, 184, 214, 245, 275, 306, 337};
// day to double
double dday = double(day) + ((double((hour*60 + minute)*60 + second)*1000 + millisecond)*1000 + microsecond)/86400000000.0;
if (month < 3)
{
month += 12;
--year;
}
double dyear = double(year);
return dday + lookup[month] + 365*year + floor(dyear/4) - floor(dyear/100) + floor(dyear/400) + 1721118.5;
}
void DateTime::checkLimit(short& lower, short& higher, short limit)
{
if (lower > limit)
{
higher += short(lower / limit);
lower = short(lower % limit);
}
}
void DateTime::normalize()
{
checkLimit(_microsecond, _millisecond, 999);
checkLimit(_millisecond, _second, 999);
checkLimit(_second, _minute, 59);
checkLimit(_minute, _hour, 59);
checkLimit(_hour, _day, 23);
if (_day > daysOfMonth(_year, _month))
{
_day -= daysOfMonth(_year, _month);
if (++_month > 12)
{
++_year;
_month -= 12;
}
}
}
void DateTime::computeGregorian()
{
double z = floor(_julianDay - 1721118.5);
double r = _julianDay - 1721118.5 - z;
double g = z - 0.25;
double a = floor(g / 36524.25);
double b = a - floor(a/4);
_year = short(floor((b + g)/365.25));
double c = b + z - floor(365.25*_year);
_month = short(floor((5*c + 456)/153));
double dday = c - floor((153.0*_month - 457)/5) + r;
_day = short(dday);
if (_month > 12)
{
++_year;
_month -= 12;
}
r *= 24;
_hour = short(floor(r));
r -= floor(r);
r *= 60;
_minute = short(floor(r));
r -= floor(r);
r *= 60;
_second = short(floor(r));
r -= floor(r);
r *= 1000;
_millisecond = short(floor(r));
r -= floor(r);
r *= 1000;
_microsecond = short(r + 0.5);
normalize();
poco_assert_dbg (_month >= 1 && _month <= 12);
poco_assert_dbg (_day >= 1 && _day <= daysOfMonth(_year, _month));
poco_assert_dbg (_hour >= 0 && _hour <= 23);
poco_assert_dbg (_minute >= 0 && _minute <= 59);
poco_assert_dbg (_second >= 0 && _second <= 59);
poco_assert_dbg (_millisecond >= 0 && _millisecond <= 999);
poco_assert_dbg (_microsecond >= 0 && _microsecond <= 999);
}
Foundation_END

View File

@@ -0,0 +1,82 @@
//
// DateTimeFormat.cpp
//
// $Id: //poco/1.1.0/Foundation/src/DateTimeFormat.cpp#2 $
//
// Library: Foundation
// Package: DateTime
// Module: DateTimeFormat
//
// 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 "Foundation/DateTimeFormat.h"
Foundation_BEGIN
const std::string DateTimeFormat::ISO8601_FORMAT = "%Y-%m-%dT%H:%M:%S%z";
const std::string DateTimeFormat::RFC822_FORMAT = "%w, %e %b %y %H:%M:%S %Z";
const std::string DateTimeFormat::RFC1123_FORMAT = "%w, %e %b %Y %H:%M:%S %Z";
const std::string DateTimeFormat::HTTP_FORMAT = "%w, %d %b %Y %H:%M:%S %Z";
const std::string DateTimeFormat::RFC850_FORMAT = "%W, %e-%b-%y %H:%M:%S %Z";
const std::string DateTimeFormat::RFC1036_FORMAT = "%W, %e %b %y %H:%M:%S %Z";
const std::string DateTimeFormat::ASCTIME_FORMAT = "%w %b %f %H:%M:%S %Y";
const std::string DateTimeFormat::SORTABLE_FORMAT = "%Y-%m-%d %H:%M:%S";
const std::string DateTimeFormat::WEEKDAY_NAMES[] =
{
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday"
};
const std::string DateTimeFormat::MONTH_NAMES[] =
{
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
};
Foundation_END

View File

@@ -0,0 +1,188 @@
//
// DateTimeFormatter.cpp
//
// $Id: //poco/1.1.0/Foundation/src/DateTimeFormatter.cpp#2 $
//
// Library: Foundation
// Package: DateTime
// Module: DateTimeFormatter
//
// 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 "Foundation/DateTimeFormatter.h"
#include "Foundation/DateTimeFormat.h"
#include "Foundation/DateTime.h"
#include "Foundation/LocalDateTime.h"
#include "Foundation/Timestamp.h"
#include "Foundation/NumberFormatter.h"
Foundation_BEGIN
std::string DateTimeFormatter::format(const Timestamp& timestamp, const std::string& fmt, int timeZoneDifferential)
{
DateTime dateTime(timestamp);
return format(dateTime, fmt, timeZoneDifferential);
}
std::string DateTimeFormatter::format(const DateTime& dateTime, const std::string& fmt, int timeZoneDifferential)
{
std::string result;
std::string::const_iterator it = fmt.begin();
std::string::const_iterator end = fmt.end();
while (it != end)
{
if (*it == '%')
{
if (++it != end)
{
switch (*it)
{
case 'w': result.append(DateTimeFormat::WEEKDAY_NAMES[dateTime.dayOfWeek()], 0, 3); break;
case 'W': result.append(DateTimeFormat::WEEKDAY_NAMES[dateTime.dayOfWeek()]); break;
case 'b': result.append(DateTimeFormat::MONTH_NAMES[dateTime.month() - 1], 0, 3); break;
case 'B': result.append(DateTimeFormat::MONTH_NAMES[dateTime.month() - 1]); break;
case 'd': result.append(NumberFormatter::format0(dateTime.day(), 2)); break;
case 'e': result.append(NumberFormatter::format(dateTime.day())); break;
case 'f': result.append(NumberFormatter::format(dateTime.day(), 2)); break;
case 'm': result.append(NumberFormatter::format0(dateTime.month(), 2)); break;
case 'n': result.append(NumberFormatter::format(dateTime.month())); break;
case 'o': result.append(NumberFormatter::format(dateTime.month(), 2)); break;
case 'y': result.append(NumberFormatter::format0(dateTime.year() % 100, 2)); break;
case 'Y': result.append(NumberFormatter::format0(dateTime.year(), 4)); break;
case 'H': result.append(NumberFormatter::format0(dateTime.hour(), 2)); break;
case 'h': result.append(NumberFormatter::format0(dateTime.hourAMPM(), 2)); break;
case 'a': result.append(dateTime.isAM() ? "am" : "pm"); break;
case 'A': result.append(dateTime.isAM() ? "AM" : "PM"); break;
case 'M': result.append(NumberFormatter::format0(dateTime.minute(), 2)); break;
case 'S': result.append(NumberFormatter::format0(dateTime.second(), 2)); break;
case 'i': result.append(NumberFormatter::format0(dateTime.millisecond(), 3)); break;
case 'c': result.append(NumberFormatter::format(dateTime.millisecond()/100)); break;
case 'z': result.append(tzdISO(timeZoneDifferential)); break;
case 'Z': result.append(tzdRFC(timeZoneDifferential)); break;
default: result += *it;
}
++it;
}
}
else result += *it++;
}
return result;
}
std::string DateTimeFormatter::format(const LocalDateTime& dateTime, const std::string& fmt)
{
return format(dateTime._dateTime, fmt, dateTime._tzd);
}
std::string DateTimeFormatter::format(const Timespan& timespan, const std::string& fmt)
{
std::string result;
std::string::const_iterator it = fmt.begin();
std::string::const_iterator end = fmt.end();
while (it != end)
{
if (*it == '%')
{
if (++it != end)
{
switch (*it)
{
case 'd': result.append(NumberFormatter::format(timespan.days())); break;
case 'H': result.append(NumberFormatter::format0(timespan.hours(), 2)); break;
case 'h': result.append(NumberFormatter::format(timespan.totalHours())); break;
case 'M': result.append(NumberFormatter::format0(timespan.minutes(), 2)); break;
case 'm': result.append(NumberFormatter::format(timespan.totalMinutes())); break;
case 'S': result.append(NumberFormatter::format0(timespan.seconds(), 2)); break;
case 's': result.append(NumberFormatter::format(timespan.totalSeconds())); break;
case 'i': result.append(NumberFormatter::format0(timespan.milliseconds(), 3)); break;
case 'c': result.append(NumberFormatter::format(timespan.milliseconds()/100)); break;
default: result += *it;
}
++it;
}
}
else result += *it++;
}
return result;
}
std::string DateTimeFormatter::tzdISO(int timeZoneDifferential)
{
std::string tzd;
if (timeZoneDifferential != UTC)
{
if (timeZoneDifferential >= 0)
{
tzd += '+';
tzd += NumberFormatter::format0(timeZoneDifferential/3600, 2);
tzd += ':';
tzd += NumberFormatter::format0((timeZoneDifferential%3600)/60, 2);
}
else
{
tzd += '-';
tzd += NumberFormatter::format0(-timeZoneDifferential/3600, 2);
tzd += ':';
tzd += NumberFormatter::format0((-timeZoneDifferential%3600)/60, 2);
}
}
else tzd = "Z";
return tzd;
}
std::string DateTimeFormatter::tzdRFC(int timeZoneDifferential)
{
std::string tzd;
if (timeZoneDifferential != UTC)
{
if (timeZoneDifferential >= 0)
{
tzd += '+';
tzd += NumberFormatter::format0(timeZoneDifferential/3600, 2);
tzd += NumberFormatter::format0((timeZoneDifferential%3600)/60, 2);
}
else
{
tzd += '-';
tzd += NumberFormatter::format0(-timeZoneDifferential/3600, 2);
tzd += NumberFormatter::format0((-timeZoneDifferential%3600)/60, 2);
}
}
else tzd = "GMT";
return tzd;
}
Foundation_END

View File

@@ -0,0 +1,369 @@
//
// DateTimeParser.cpp
//
// $Id: //poco/1.1.0/Foundation/src/DateTimeParser.cpp#2 $
//
// Library: Foundation
// Package: DateTime
// Module: DateTimeParser
//
// 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 "Foundation/DateTimeParser.h"
#include "Foundation/DateTimeFormat.h"
#include "Foundation/DateTime.h"
#include "Foundation/Exception.h"
#include <ctype.h>
Foundation_BEGIN
#define SKIP_JUNK() \
while (it != end && !isdigit(*it)) ++it
#define PARSE_NUMBER(var) \
while (it != end && isdigit(*it)) var = var*10 + ((*it++) - '0')
#define PARSE_NUMBER_N(var, n) \
{ int i = 0; while (i++ < n && it != end && isdigit(*it)) var = var*10 + ((*it++) - '0'); }
void DateTimeParser::parse(const std::string& fmt, const std::string& str, DateTime& dateTime, int& timeZoneDifferential)
{
int year = 0;
int month = 0;
int day = 0;
int hour = 0;
int minute = 0;
int second = 0;
int millis = 0;
int tzd = 0;
std::string::const_iterator it = str.begin();
std::string::const_iterator end = str.end();
std::string::const_iterator itf = fmt.begin();
std::string::const_iterator endf = fmt.end();
while (itf != endf && it != end)
{
if (*itf == '%')
{
if (++itf != endf)
{
switch (*itf)
{
case 'w':
case 'W':
while (it != end && isspace(*it)) ++it;
while (it != end && isalpha(*it)) ++it;
break;
case 'b':
case 'B':
month = parseMonth(it, end);
break;
case 'd':
case 'e':
case 'f':
SKIP_JUNK();
PARSE_NUMBER_N(day, 2);
break;
case 'm':
case 'n':
case 'o':
SKIP_JUNK();
PARSE_NUMBER_N(month, 2);
break;
case 'y':
SKIP_JUNK();
PARSE_NUMBER(year);
if (year < 1000)
{
if (year >= 70)
year += 1900;
else
year += 2000;
}
break;
case 'Y':
SKIP_JUNK();
PARSE_NUMBER_N(year, 4);
break;
case 'H':
case 'h':
SKIP_JUNK();
PARSE_NUMBER_N(hour, 2);
break;
case 'a':
case 'A':
hour = parseAMPM(it, end, hour);
break;
case 'M':
SKIP_JUNK();
PARSE_NUMBER_N(minute, 2);
break;
case 'S':
SKIP_JUNK();
PARSE_NUMBER_N(second, 2);
break;
case 'i':
SKIP_JUNK();
PARSE_NUMBER_N(millis, 3);
break;
case 'c':
SKIP_JUNK();
PARSE_NUMBER_N(millis, 1);
millis *= 100;
break;
case 'z':
case 'Z':
tzd = parseTZD(it, end);
break;
}
++itf;
}
}
else ++itf;
}
if (month == 0) month = 1;
if (day == 0) day = 1;
dateTime.assign(year, month, day, hour, minute, second, millis);
timeZoneDifferential = tzd;
}
DateTime DateTimeParser::parse(const std::string& fmt, const std::string& str, int& timeZoneDifferential)
{
DateTime result;
parse(fmt, str, result, timeZoneDifferential);
return result;
}
bool DateTimeParser::tryParse(const std::string& fmt, const std::string& str, DateTime& dateTime, int& timeZoneDifferential)
{
try
{
parse(fmt, str, dateTime, timeZoneDifferential);
}
catch (Exception&)
{
return false;
}
return true;
}
void DateTimeParser::parse(const std::string& str, DateTime& dateTime, int& timeZoneDifferential)
{
if (!tryParse(str, dateTime, timeZoneDifferential))
throw SyntaxException("Unsupported or invalid date/time format");
}
DateTime DateTimeParser::parse(const std::string& str, int& timeZoneDifferential)
{
DateTime result;
if (tryParse(str, result, timeZoneDifferential))
return result;
else
throw SyntaxException("Unsupported or invalid date/time format");
}
bool DateTimeParser::tryParse(const std::string& str, DateTime& dateTime, int& timeZoneDifferential)
{
if (str.length() < 4) return false;
if (str[3] == ',')
return tryParse(DateTimeFormat::RFC822_FORMAT, str, dateTime, timeZoneDifferential);
else if (str[3] == ' ')
return tryParse(DateTimeFormat::ASCTIME_FORMAT, str, dateTime, timeZoneDifferential);
else if (str.find(',') != std::string::npos)
return tryParse(DateTimeFormat::RFC850_FORMAT, str, dateTime, timeZoneDifferential);
else if (isdigit(str[0]))
{
if (str.find(' ') != std::string::npos || str.length() == 10)
return tryParse(DateTimeFormat::SORTABLE_FORMAT, str, dateTime, timeZoneDifferential);
else
return tryParse(DateTimeFormat::ISO8601_FORMAT, str, dateTime, timeZoneDifferential);
}
else return false;
}
int DateTimeParser::parseTZD(std::string::const_iterator& it, const std::string::const_iterator& end)
{
struct Zone
{
const char* designator;
int timeZoneDifferential;
};
static Zone zones[] =
{
{"Z", 0},
{"UT", 0},
{"GMT", 0},
{"BST", 1*3600},
{"IST", 1*3600},
{"WET", 0},
{"WEST", 1*3600},
{"CET", 1*3600},
{"CEST", 2*3600},
{"EET", 2*3600},
{"EEST", 3*3600},
{"MSK", 3*3600},
{"MSD", 4*3600},
{"NST", -3*3600-1800},
{"NDT", -2*3600-1800},
{"AST", -4*3600},
{"ADT", -3*3600},
{"EST", -5*3600},
{"EDT", -4*3600},
{"CST", -6*3600},
{"CDT", -5*3600},
{"MST", -7*3600},
{"MDT", -6*3600},
{"PST", -8*3600},
{"PDT", -7*3600},
{"AKST", -9*3600},
{"AKDT", -8*3600},
{"HST", -10*3600},
{"AEST", 10*3600},
{"AEDT", 11*3600},
{"ACST", 9*3600+1800},
{"ACDT", 10*3600+1800},
{"AWST", 8*3600},
{"AWDT", 9*3600}
};
while (it != end && isspace(*it)) ++it;
if (it != end)
{
if (isalpha(*it))
{
std::string designator;
designator += *it++;
if (it != end && isalpha(*it)) designator += *it++;
if (it != end && isalpha(*it)) designator += *it++;
if (it != end && isalpha(*it)) designator += *it++;
for (int i = 0; i < sizeof(zones)/sizeof(Zone); ++i)
{
if (designator == zones[i].designator)
return zones[i].timeZoneDifferential;
}
}
else if (*it == '+' || *it == '-')
{
int sign = *it == '+' ? 1 : -1;
++it;
int hours = 0;
PARSE_NUMBER_N(hours, 2);
if (it != end && *it == ':') ++it;
int minutes = 0;
PARSE_NUMBER_N(minutes, 2);
return sign*(hours*3600 + minutes*60);
}
}
return 0;
}
int DateTimeParser::parseMonth(std::string::const_iterator& it, const std::string::const_iterator& end)
{
std::string month;
while (it != end && isspace(*it) || ispunct(*it)) ++it;
bool isFirst = true;
while (it != end && isalpha(*it))
{
char ch = (*it++);
if (isFirst) { month += toupper(ch); isFirst = false; }
else month += tolower(ch);
}
if (month.length() < 3) throw SyntaxException("Month name must be at least three characters long", month);
for (int i = 0; i < 12; ++i)
{
if (DateTimeFormat::MONTH_NAMES[i].find(month) == 0)
return i + 1;
}
throw SyntaxException("Not a valid month name", month);
}
int DateTimeParser::parseDayOfWeek(std::string::const_iterator& it, const std::string::const_iterator& end)
{
std::string dow;
while (it != end && isspace(*it) || ispunct(*it)) ++it;
bool isFirst = true;
while (it != end && isalpha(*it))
{
char ch = (*it++);
if (isFirst) { dow += toupper(ch); isFirst = false; }
else dow += tolower(ch);
}
if (dow.length() < 3) throw SyntaxException("Weekday name must be at least three characters long", dow);
for (int i = 0; i < 7; ++i)
{
if (DateTimeFormat::WEEKDAY_NAMES[i].find(dow) == 0)
return i;
}
throw SyntaxException("Not a valid weekday name", dow);
}
int DateTimeParser::parseAMPM(std::string::const_iterator& it, const std::string::const_iterator& end, int hour)
{
std::string ampm;
while (it != end && isspace(*it) || ispunct(*it)) ++it;
while (it != end && isalpha(*it))
{
char ch = (*it++);
ampm += toupper(ch);
}
if (ampm == "AM")
{
if (hour == 12)
return 0;
else
return hour;
}
else if (ampm == "PM")
{
if (hour < 12)
return hour + 12;
else
return hour;
}
else throw SyntaxException("Not a valid AM/PM designator", ampm);
}
Foundation_END

155
Foundation/src/Debugger.cpp Normal file
View File

@@ -0,0 +1,155 @@
//
// Debugger.cpp
//
// $Id: //poco/1.1.0/Foundation/src/Debugger.cpp#2 $
//
// Library: Foundation
// Package: Core
// Module: Debugger
//
// 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 "Foundation/Debugger.h"
#include <sstream>
#include <stdlib.h>
#include <stdio.h>
#if defined(POCO_OS_FAMILY_WINDOWS)
#include <windows.h>
#elif defined(POCO_OS_FAMILY_UNIX)
#include <unistd.h>
#include <signal.h>
#elif defined(POCO_OS_FAMILY_VMS)
#include <lib$routines.h>
#include <ssdef.h>
#endif
// NOTE: In this module, we use the C library functions (fputs) for,
// output since, at the time we're called, the C++ iostream objects std::cout, etc.
// might not have been initialized yet.
Foundation_BEGIN
bool Debugger::isAvailable()
{
#if defined(_DEBUG)
#if defined(POCO_OS_FAMILY_WINDOWS)
return IsDebuggerPresent() ? true : false;
#elif defined(POCO_OS_FAMILY_UNIX)
return getenv("POCO_ENABLE_DEBUGGER") ? true : false;
#elif defined(POCO_OS_FAMILY_VMS)
return true;
#endif
#else
return false;
#endif
}
void Debugger::message(const std::string& msg)
{
#if defined(_DEBUG)
fputs("\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n", stderr);
fputs(msg.c_str(), stderr);
fputs("\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n", stderr);
#if defined(POCO_OS_FAMILY_WINDOWS)
if (IsDebuggerPresent())
{
OutputDebugString(msg.c_str());
OutputDebugString("\n");
}
#elif defined(POCO_OS_FAMILY_UNIX)
#elif defined(POCO_OS_FAMILY_VMS)
#endif
#endif
}
void Debugger::message(const std::string& msg, const char* file, int line)
{
#if defined(_DEBUG)
std::ostringstream str;
str << msg << " [in file \"" << file << "\", line " << line << "]";
message(str.str());
#endif
}
void Debugger::enter()
{
#if defined(_DEBUG)
#if defined(POCO_OS_FAMILY_WINDOWS)
if (IsDebuggerPresent())
{
DebugBreak();
}
#elif defined(POCO_OS_FAMILY_UNIX)
if (isAvailable())
{
kill(getpid(), SIGINT);
}
#elif defined(POCO_OS_FAMILY_VMS)
{
const char* cmd = "\012SHOW CALLS";
lib$signal(SS$_DEBUG, 1, cmd);
}
#endif
#endif
}
void Debugger::enter(const std::string& msg)
{
#if defined(_DEBUG)
message(msg);
enter();
#endif
}
void Debugger::enter(const std::string& msg, const char* file, int line)
{
#if defined(_DEBUG)
message(msg, file, line);
enter();
#endif
}
void Debugger::enter(const char* file, int line)
{
#if defined(_DEBUG)
message("BREAK", file, line);
enter();
#endif
}
Foundation_END

View File

@@ -0,0 +1,292 @@
//
// DeflatingStream.cpp
//
// $Id: //poco/1.1.0/Foundation/src/DeflatingStream.cpp#2 $
//
// Library: Foundation
// Package: Streams
// Module: ZLibStream
//
// 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 "Foundation/DeflatingStream.h"
#include "Foundation/Exception.h"
Foundation_BEGIN
DeflatingStreamBuf::DeflatingStreamBuf(std::istream& istr, StreamType type, int level):
BufferedStreamBuf(STREAM_BUFFER_SIZE, std::ios::in),
_pIstr(&istr),
_pOstr(0),
_eof(false)
{
_zstr.zalloc = Z_NULL;
_zstr.zfree = Z_NULL;
_zstr.opaque = Z_NULL;
_zstr.next_in = 0;
_zstr.avail_in = 0;
_zstr.next_out = 0;
_zstr.avail_out = 0;
int rc = deflateInit2(&_zstr, level, Z_DEFLATED, 15 + (type == STREAM_GZIP ? 16 : 0), 8, Z_DEFAULT_STRATEGY);
if (rc != Z_OK) throw IOException(zError(rc));
_buffer = new char[DEFLATE_BUFFER_SIZE];
}
DeflatingStreamBuf::DeflatingStreamBuf(std::ostream& ostr, StreamType type, int level):
BufferedStreamBuf(STREAM_BUFFER_SIZE, std::ios::out),
_pIstr(0),
_pOstr(&ostr),
_eof(false)
{
_zstr.zalloc = Z_NULL;
_zstr.zfree = Z_NULL;
_zstr.opaque = Z_NULL;
_zstr.next_in = 0;
_zstr.avail_in = 0;
_zstr.next_out = 0;
_zstr.avail_out = 0;
int rc = deflateInit2(&_zstr, level, Z_DEFLATED, 15 + (type == STREAM_GZIP ? 16 : 0), 8, Z_DEFAULT_STRATEGY);
if (rc != Z_OK) throw IOException(zError(rc));
_buffer = new char[DEFLATE_BUFFER_SIZE];
}
DeflatingStreamBuf::~DeflatingStreamBuf()
{
try
{
close();
}
catch (...)
{
}
delete [] _buffer;
}
int DeflatingStreamBuf::close()
{
sync();
if (_pIstr)
{
int rc = deflateEnd(&_zstr);
if (rc != Z_OK) throw IOException(zError(rc));
_pIstr = 0;
}
else if (_pOstr)
{
if (_zstr.next_out)
{
int rc = deflate(&_zstr, Z_FINISH);
if (rc != Z_OK && rc != Z_STREAM_END) throw IOException(zError(rc));
_pOstr->write(_buffer, DEFLATE_BUFFER_SIZE - _zstr.avail_out);
if (!_pOstr->good()) throw IOException(zError(rc));
_zstr.next_out = (unsigned char*) _buffer;
_zstr.avail_out = DEFLATE_BUFFER_SIZE;
while (rc != Z_STREAM_END)
{
rc = deflate(&_zstr, Z_FINISH);
if (rc != Z_OK && rc != Z_STREAM_END) throw IOException(zError(rc));
_pOstr->write(_buffer, DEFLATE_BUFFER_SIZE - _zstr.avail_out);
if (!_pOstr->good()) throw IOException(zError(rc));
_zstr.next_out = (unsigned char*) _buffer;
_zstr.avail_out = DEFLATE_BUFFER_SIZE;
}
rc = deflateEnd(&_zstr);
if (rc != Z_OK) throw IOException(zError(rc));
}
_pOstr = 0;
}
return 0;
}
int DeflatingStreamBuf::readFromDevice(char* buffer, std::streamsize length)
{
if (!_pIstr) return 0;
if (!_zstr.next_in && !_eof)
{
int n = 0;
if (_pIstr->good())
{
_pIstr->read(_buffer, DEFLATE_BUFFER_SIZE);
n = _pIstr->gcount();
}
if (n > 0)
{
_zstr.next_in = (unsigned char*) _buffer;
_zstr.avail_in = n;
}
else
{
_zstr.next_in = 0;
_zstr.avail_in = 0;
_eof = true;
}
_zstr.next_out = (unsigned char*) buffer;
_zstr.avail_out = length;
}
else if (_zstr.avail_out == 0)
{
_zstr.next_out = (unsigned char*) buffer;
_zstr.avail_out = length;
}
for (;;)
{
int rc = deflate(&_zstr, _eof ? Z_FINISH : Z_NO_FLUSH);
if (_eof && rc == Z_STREAM_END)
{
rc = deflateEnd(&_zstr);
if (rc != Z_OK) throw IOException(zError(rc));
_pIstr = 0;
return length - _zstr.avail_out;
}
if (rc != Z_OK) throw IOException(zError(rc));
if (_zstr.avail_out == 0)
{
return length;
}
if (_zstr.avail_in == 0)
{
int n = 0;
if (_pIstr->good())
{
_pIstr->read(_buffer, DEFLATE_BUFFER_SIZE);
n = _pIstr->gcount();
}
if (n > 0)
{
_zstr.next_in = (unsigned char*) _buffer;
_zstr.avail_in = n;
}
else
{
_zstr.next_in = 0;
_zstr.avail_in = 0;
_eof = true;
}
}
}
}
int DeflatingStreamBuf::writeToDevice(const char* buffer, std::streamsize length)
{
if (length == 0 || !_pOstr) return 0;
_zstr.next_in = (unsigned char*) buffer;
_zstr.avail_in = length;
_zstr.next_out = (unsigned char*) _buffer;
_zstr.avail_out = DEFLATE_BUFFER_SIZE;
for (;;)
{
int rc = deflate(&_zstr, Z_NO_FLUSH);
if (rc != Z_OK) throw IOException(zError(rc));
if (_zstr.avail_out == 0)
{
_pOstr->write(_buffer, DEFLATE_BUFFER_SIZE);
if (!_pOstr->good()) throw IOException(zError(rc));
_zstr.next_out = (unsigned char*) _buffer;
_zstr.avail_out = DEFLATE_BUFFER_SIZE;
}
if (_zstr.avail_in == 0)
{
_pOstr->write(_buffer, DEFLATE_BUFFER_SIZE - _zstr.avail_out);
if (!_pOstr->good()) throw IOException(zError(rc));
_zstr.next_out = (unsigned char*) _buffer;
_zstr.avail_out = DEFLATE_BUFFER_SIZE;
break;
}
}
return length;
}
DeflatingIOS::DeflatingIOS(std::ostream& ostr, DeflatingStreamBuf::StreamType type, int level):
_buf(ostr, type, level)
{
poco_ios_init(&_buf);
}
DeflatingIOS::DeflatingIOS(std::istream& istr, DeflatingStreamBuf::StreamType type, int level):
_buf(istr, type, level)
{
poco_ios_init(&_buf);
}
DeflatingIOS::~DeflatingIOS()
{
}
DeflatingStreamBuf* DeflatingIOS::rdbuf()
{
return &_buf;
}
DeflatingOutputStream::DeflatingOutputStream(std::ostream& ostr, DeflatingStreamBuf::StreamType type, int level):
DeflatingIOS(ostr, type, level),
std::ostream(&_buf)
{
}
DeflatingOutputStream::~DeflatingOutputStream()
{
}
int DeflatingOutputStream::close()
{
return _buf.close();
}
DeflatingInputStream::DeflatingInputStream(std::istream& istr, DeflatingStreamBuf::StreamType type, int level):
DeflatingIOS(istr, type, level),
std::istream(&_buf)
{
}
DeflatingInputStream::~DeflatingInputStream()
{
}
Foundation_END

View File

@@ -0,0 +1,68 @@
//
// DigestEngine.cpp
//
// $Id: //poco/1.1.0/Foundation/src/DigestEngine.cpp#2 $
//
// Library: Foundation
// Package: Crypt
// Module: DigestEngine
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Foundation/DigestEngine.h"
Foundation_BEGIN
DigestEngine::DigestEngine()
{
}
DigestEngine::~DigestEngine()
{
}
std::string DigestEngine::digestToHex(const Digest& bytes)
{
static const char digits[] = "0123456789abcdef";
std::string result;
result.reserve(bytes.size()*2);
for (Digest::const_iterator it = bytes.begin(); it != bytes.end(); ++it)
{
unsigned char c = *it;
result += digits[(c >> 4) & 0xF];
result += digits[c & 0xF];
}
return result;
}
Foundation_END

View File

@@ -0,0 +1,172 @@
//
// DigestStream.cpp
//
// $Id: //poco/1.1.0/Foundation/src/DigestStream.cpp#2 $
//
// Library: Foundation
// Package: Crypt
// Module: DigestStream
//
// 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 "Foundation/DigestStream.h"
Foundation_BEGIN
const int DigestBuf::BUFFER_SIZE = 256;
DigestBuf::DigestBuf(DigestEngine& eng):
BufferedStreamBuf(BUFFER_SIZE, std::ios::out),
_eng(eng),
_pOstr(0),
_pIstr(0)
{
}
DigestBuf::DigestBuf(DigestEngine& eng, std::istream& istr):
BufferedStreamBuf(BUFFER_SIZE, std::ios::in),
_eng(eng),
_pIstr(&istr),
_pOstr(0)
{
}
DigestBuf::DigestBuf(DigestEngine& eng, std::ostream& ostr):
BufferedStreamBuf(BUFFER_SIZE, std::ios::in),
_eng(eng),
_pIstr(0),
_pOstr(&ostr)
{
}
DigestBuf::~DigestBuf()
{
}
int DigestBuf::readFromDevice(char* buffer, std::streamsize length)
{
if (_pIstr && _pIstr->good())
{
_pIstr->read(buffer, length);
std::streamsize n = _pIstr->gcount();
if (n > 0) _eng.update(buffer, n);
return n;
}
return -1;
}
int DigestBuf::writeToDevice(const char* buffer, std::streamsize length)
{
_eng.update(buffer, (unsigned) length);
if (_pOstr) _pOstr->write(buffer, length);
return length;
}
void DigestBuf::close()
{
sync();
if (_pOstr) _pOstr->flush();
}
DigestIOS::DigestIOS(DigestEngine& eng): _buf(eng)
{
poco_ios_init(&_buf);
}
DigestIOS::DigestIOS(DigestEngine& eng, std::istream& istr): _buf(eng, istr)
{
poco_ios_init(&_buf);
}
DigestIOS::DigestIOS(DigestEngine& eng, std::ostream& ostr): _buf(eng, ostr)
{
poco_ios_init(&_buf);
}
DigestIOS::~DigestIOS()
{
}
DigestBuf* DigestIOS::rdbuf()
{
return &_buf;
}
DigestInputStream::DigestInputStream(DigestEngine& eng, std::istream& istr):
DigestIOS(eng, istr),
std::istream(&_buf)
{
}
DigestInputStream::~DigestInputStream()
{
}
DigestOutputStream::DigestOutputStream(DigestEngine& eng):
DigestIOS(eng),
std::ostream(&_buf)
{
}
DigestOutputStream::DigestOutputStream(DigestEngine& eng, std::ostream& ostr):
DigestIOS(eng, ostr),
std::ostream(&_buf)
{
}
DigestOutputStream::~DigestOutputStream()
{
}
void DigestOutputStream::close()
{
_buf.close();
}
Foundation_END

View File

@@ -0,0 +1,171 @@
//
// DirectoryIterator.cpp
//
// $Id: //poco/1.1.0/Foundation/src/DirectoryIterator.cpp#2 $
//
// Library: Foundation
// Package: Filesystem
// Module: DirectoryIterator
//
// 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 "Foundation/DirectoryIterator.h"
#if defined(POCO_OS_FAMILY_WINDOWS) && defined(POCO_WIN32_UTF8)
#include "DirectoryIterator_WIN32U.cpp"
#elif defined(POCO_OS_FAMILY_WINDOWS)
#include "DirectoryIterator_WIN32.cpp"
#elif defined(POCO_OS_FAMILY_UNIX)
#include "DirectoryIterator_UNIX.cpp"
#else
#include "DirectoryIterator_VMS.cpp"
#endif
Foundation_BEGIN
DirectoryIterator::DirectoryIterator(): _pImpl(0)
{
}
DirectoryIterator::DirectoryIterator(const std::string& path): _path(path), _pImpl(new DirectoryIteratorImpl(path))
{
_path.makeDirectory();
_path.setFileName(_pImpl->get());
_file = _path;
}
DirectoryIterator::DirectoryIterator(const DirectoryIterator& iterator): _path(iterator._path), _pImpl(iterator._pImpl)
{
_path.makeDirectory();
if (_pImpl)
{
_pImpl->duplicate();
_path.setFileName(_pImpl->get());
_file = _path;
}
}
DirectoryIterator::DirectoryIterator(const File& file): _path(file.path()), _pImpl(new DirectoryIteratorImpl(file.path()))
{
_path.makeDirectory();
_path.setFileName(_pImpl->get());
_file = _path;
}
DirectoryIterator::DirectoryIterator(const Path& path): _path(path), _pImpl(new DirectoryIteratorImpl(path.toString()))
{
_path.makeDirectory();
_path.setFileName(_pImpl->get());
_file = _path;
}
DirectoryIterator::~DirectoryIterator()
{
if (_pImpl) _pImpl->release();
}
DirectoryIterator& DirectoryIterator::operator = (const DirectoryIterator& it)
{
if (_pImpl) _pImpl->release();
_pImpl = it._pImpl;
if (_pImpl)
{
_pImpl->duplicate();
_path = it._path;
_file = _path;
}
return *this;
}
DirectoryIterator& DirectoryIterator::operator = (const File& file)
{
if (_pImpl) _pImpl->release();
_pImpl = new DirectoryIteratorImpl(file.path());
_path.parseDirectory(file.path());
_path.setFileName(_pImpl->get());
_file = _path;
return *this;
}
DirectoryIterator& DirectoryIterator::operator = (const Path& path)
{
if (_pImpl) _pImpl->release();
_pImpl = new DirectoryIteratorImpl(path.toString());
_path = path;
_path.makeDirectory();
_path.setFileName(_pImpl->get());
_file = _path;
return *this;
}
DirectoryIterator& DirectoryIterator::operator = (const std::string& path)
{
if (_pImpl) _pImpl->release();
_pImpl = new DirectoryIteratorImpl(path);
_path.parseDirectory(path);
_path.setFileName(_pImpl->get());
_file = _path;
return *this;
}
DirectoryIterator& DirectoryIterator::operator ++ ()
{
if (_pImpl)
{
_path.setFileName(_pImpl->next());
_file = _path;
}
return *this;
}
DirectoryIterator DirectoryIterator::operator ++ (int dummy)
{
if (_pImpl)
{
_path.setFileName(_pImpl->next());
_file = _path;
}
return *this;
}
Foundation_END

View File

@@ -0,0 +1,78 @@
//
// DirectoryIterator_UNIX.cpp
//
// $Id: //poco/1.1.0/Foundation/src/DirectoryIterator_UNIX.cpp#2 $
//
// Library: Foundation
// Package: Filesystem
// Module: DirectoryIterator
//
// 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 "Foundation/DirectoryIterator_UNIX.h"
#include "Foundation/File_UNIX.h"
#include "Foundation/Path.h"
Foundation_BEGIN
DirectoryIteratorImpl::DirectoryIteratorImpl(const std::string& path): _pDir(0), _rc(1)
{
Path p(path);
p.makeFile();
_pDir = opendir(p.toString().c_str());
if (!_pDir) FileImpl::handleError(path);
next();
}
DirectoryIteratorImpl::~DirectoryIteratorImpl()
{
if (_pDir) closedir(_pDir);
}
const std::string& DirectoryIteratorImpl::next()
{
do
{
struct dirent* pEntry = readdir(_pDir);
if (pEntry)
_current = pEntry->d_name;
else
_current.clear();
}
while (_current == "." || _current == "..");
return _current;
}
Foundation_END

View File

@@ -0,0 +1,87 @@
//
// DirectoryIterator_VMS.cpp
//
// $Id: //poco/1.1.0/Foundation/src/DirectoryIterator_VMS.cpp#2 $
//
// Library: Foundation
// Package: Filesystem
// Module: DirectoryIterator
//
// 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 "Foundation/DirectoryIterator_VMS.h"
#include "Foundation/Path.h"
#include "Foundation/Exception.h"
#include <iodef.h>
#include <atrdef.h>
#include <fibdef.h>
#include <starlet.h>
Foundation_BEGIN
DirectoryIteratorImpl::DirectoryIteratorImpl(const std::string& path): _rc(1)
{
Path p(path);
p.makeDirectory();
_search = p.toString();
_search.append("*.*;*");
_fab = cc$rms_fab;
_fab.fab$l_fna = (char*) _search.c_str();
_fab.fab$b_fns = _search.size();
_fab.fab$l_nam = &_nam;
_nam = cc$rms_nam;
_nam.nam$l_esa = _spec;
_nam.nam$b_ess = sizeof(_spec);
if (sys$parse(&_fab) & 1)
throw OpenFileException(path);
next();
}
DirectoryIteratorImpl::~DirectoryIteratorImpl()
{
}
const std::string& DirectoryIteratorImpl::next()
{
if (sys$search(&_fab) & 1)
_current.clear();
else
_current.assign(_fab.fab$l_nam->nam$l_name, _fab.fab$l_nam->nam$b_name + _fab.fab$l_nam->nam$b_type);
return _current;
}
Foundation_END

View File

@@ -0,0 +1,85 @@
//
// DirectoryIterator_WIN32.cpp
//
// $Id: //poco/1.1.0/Foundation/src/DirectoryIterator_WIN32.cpp#2 $
//
// Library: Foundation
// Package: Filesystem
// Module: DirectoryIterator
//
// 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 "Foundation/DirectoryIterator_WIN32.h"
#include "Foundation/File_WIN32.h"
#include "Foundation/Path.h"
Foundation_BEGIN
DirectoryIteratorImpl::DirectoryIteratorImpl(const std::string& path): _fh(INVALID_HANDLE_VALUE), _rc(1)
{
Path p(path);
p.makeDirectory();
std::string findPath = p.toString();
findPath.append("*");
_fh = FindFirstFile(findPath.c_str(), &_fd);
if (_fh == INVALID_HANDLE_VALUE)
{
if (GetLastError() != ERROR_NO_MORE_FILES)
FileImpl::handleError(path);
}
_current = _fd.cFileName;
if (_current == "." || _current == "..")
next();
}
DirectoryIteratorImpl::~DirectoryIteratorImpl()
{
if (_fh != INVALID_HANDLE_VALUE)
FindClose(_fh);
}
const std::string& DirectoryIteratorImpl::next()
{
do
{
if (FindNextFile(_fh, &_fd) != 0)
_current = _fd.cFileName;
else
_current.clear();
}
while (_current == "." || _current == "..");
return _current;
}
Foundation_END

View File

@@ -0,0 +1,90 @@
//
// DirectoryIterator_WIN32U.cpp
//
// $Id: //poco/1.1.0/Foundation/src/DirectoryIterator_WIN32U.cpp#2 $
//
// Library: Foundation
// Package: Filesystem
// Module: DirectoryIterator
//
// 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 "Foundation/DirectoryIterator_WIN32U.h"
#include "Foundation/File_WIN32U.h"
#include "Foundation/Path.h"
#include "Foundation/UnicodeConverter.h"
#include <string.h>
Foundation_BEGIN
DirectoryIteratorImpl::DirectoryIteratorImpl(const std::string& path): _fh(INVALID_HANDLE_VALUE), _rc(1)
{
Path p(path);
p.makeDirectory();
std::string findPath = p.toString();
findPath.append("*");
std::wstring uFindPath;
UnicodeConverter::toUTF16(findPath, uFindPath);
_fh = FindFirstFileW(uFindPath.c_str(), &_fd);
if (_fh == INVALID_HANDLE_VALUE)
{
if (GetLastError() != ERROR_NO_MORE_FILES)
FileImpl::handleError(path);
}
UnicodeConverter::toUTF8(_fd.cFileName, _current);
if (_current == "." || _current == "..")
next();
}
DirectoryIteratorImpl::~DirectoryIteratorImpl()
{
if (_fh != INVALID_HANDLE_VALUE)
FindClose(_fh);
}
const std::string& DirectoryIteratorImpl::next()
{
do
{
_current.clear();
if (FindNextFileW(_fh, &_fd) != 0)
{
UnicodeConverter::toUTF8(_fd.cFileName, _current);
}
}
while (_current == "." || _current == "..");
return _current;
}
Foundation_END

View File

@@ -0,0 +1,96 @@
//
// Environment.cpp
//
// $Id: //poco/1.1.0/Foundation/src/Environment.cpp#2 $
//
// Library: Foundation
// Package: Core
// Module: Environment
//
// 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 "Foundation/Environment.h"
#if defined(POCO_OS_FAMILY_VMS)
#include "Environment_VMS.cpp"
#elif defined(POCO_OS_FAMILY_UNIX)
#include "Environment_UNIX.cpp"
#elif defined(POCO_OS_FAMILY_WINDOWS) && defined(POCO_WIN32_UTF8)
#include "Environment_WIN32U.cpp"
#elif defined(POCO_OS_FAMILY_WINDOWS)
#include "Environment_WIN32.cpp"
#endif
Foundation_BEGIN
std::string Environment::get(const std::string& name)
{
return EnvironmentImpl::getImpl(name);
}
bool Environment::has(const std::string& name)
{
return EnvironmentImpl::hasImpl(name);
}
void Environment::set(const std::string& name, const std::string& value)
{
EnvironmentImpl::setImpl(name, value);
}
std::string Environment::osName()
{
return EnvironmentImpl::osNameImpl();
}
std::string Environment::osVersion()
{
return EnvironmentImpl::osVersionImpl();
}
std::string Environment::osArchitecture()
{
return EnvironmentImpl::osArchitectureImpl();
}
std::string Environment::nodeName()
{
return EnvironmentImpl::nodeNameImpl();
}
Foundation_END

View File

@@ -0,0 +1,120 @@
//
// Environment_UNIX.cpp
//
// $Id: //poco/1.1.0/Foundation/src/Environment_UNIX.cpp#2 $
//
// Library: Foundation
// Package: Core
// Module: Environment
//
// 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 "Foundation/Environment_UNIX.h"
#include "Foundation/Exception.h"
#include <unistd.h>
#include <stdlib.h>
#include <sys/utsname.h>
Foundation_BEGIN
EnvironmentImpl::StringMap EnvironmentImpl::_map;
FastMutex EnvironmentImpl::_mutex;
std::string EnvironmentImpl::getImpl(const std::string& name)
{
FastMutex::ScopedLock lock(_mutex);
const char* val = getenv(name.c_str());
if (val)
return std::string(val);
else
throw NotFoundException(name);
}
bool EnvironmentImpl::hasImpl(const std::string& name)
{
FastMutex::ScopedLock lock(_mutex);
return getenv(name.c_str()) != 0;
}
void EnvironmentImpl::setImpl(const std::string& name, const std::string& value)
{
FastMutex::ScopedLock lock(_mutex);
std::string var = name;
var.append("=");
var.append(value);
_map[name] = var;
if (putenv((char*) _map[name].c_str()))
{
std::string msg = "cannot set environment variable: ";
msg.append(name);
throw SystemException(msg);
}
}
std::string EnvironmentImpl::osNameImpl()
{
struct utsname uts;
uname(&uts);
return uts.sysname;
}
std::string EnvironmentImpl::osVersionImpl()
{
struct utsname uts;
uname(&uts);
return uts.release;
}
std::string EnvironmentImpl::osArchitectureImpl()
{
struct utsname uts;
uname(&uts);
return uts.machine;
}
std::string EnvironmentImpl::nodeNameImpl()
{
struct utsname uts;
uname(&uts);
return uts.nodename;
}
Foundation_END

View File

@@ -0,0 +1,171 @@
//
// Environment_VMS.cpp
//
// $Id: //poco/1.1.0/Foundation/src/Environment_VMS.cpp#2 $
//
// Library: Foundation
// Package: Core
// Module: Environment
//
// 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 "Foundation/Environment_VMS.h"
#include "Foundation/Exception.h"
#include <stdlib.h>
#include <starlet.h>
#include <descrip.h>
#include <ssdef.h>
#include <syidef.h>
#include <iledef.h>
#include <lnmdef.h>
Foundation_BEGIN
FastMutex EnvironmentImpl::_mutex;
std::string EnvironmentImpl::getImpl(const std::string& name)
{
FastMutex::ScopedLock lock(_mutex);
const char* val = getenv(name.c_str());
if (val)
return std::string(val);
else
throw NotFoundException(name);
}
bool EnvironmentImpl::hasImpl(const std::string& name)
{
FastMutex::ScopedLock lock(_mutex);
return getenv(name.c_str()) != 0;
}
void EnvironmentImpl::setImpl(const std::string& name, const std::string& value)
{
FastMutex::ScopedLock lock(_mutex);
if (setenv(name.c_str(), value.c_str(), 1))
{
std::string msg = "cannot set environment variable: ";
msg.append(name);
throw SystemException(msg);
}
}
std::string EnvironmentImpl::osNameImpl()
{
return getsyi(SYI$_NODE_SWTYPE);
}
std::string EnvironmentImpl::osVersionImpl()
{
return getsyi(SYI$_VERSION);
}
std::string EnvironmentImpl::osArchitectureImpl()
{
return getsyi(SYI$_ARCH_NAME);
}
std::string EnvironmentImpl::nodeNameImpl()
{
return getsyi(SYI$_NODENAME);
}
std::string EnvironmentImpl::getsyi(unsigned short code)
{
#pragma pointer_size save
#pragma pointer_size 32
unsigned char result[16];
unsigned short length;
ILE3 items[2];
items[0].ile3$w_code = code;
items[0].ile3$w_length = sizeof(result);
items[0].ile3$ps_bufaddr = result;
items[0].ile3$ps_retlen_addr = &length;
items[1].ile3$w_code = 0;
items[1].ile3$w_length = 0;
if (sys$getsyiw(0, 0, 0, items, 0, 0, 0) == 1)
return std::string((char*) result, length);
else
throw SystemException("$GETSYI failed");
#pragma pointer_size restore
}
std::string EnvironmentImpl::trnlnm(const std::string& name)
{
#pragma pointer_size save
#pragma pointer_size 32
unsigned char result[LNM$C_NAMLENGTH];
unsigned short length;
ILE3 items[2];
items[0].ile3$w_code = LNM$_STRING;
items[0].ile3$w_length = sizeof(result);
items[0].ile3$ps_bufaddr = result;
items[0].ile3$ps_retlen_addr = &length;
items[1].ile3$w_code = 0;
items[1].ile3$w_length = 0;
#pragma pointer_size restore
unsigned int trnAttr = LNM$M_CASE_BLIND;
POCO_DESCRIPTOR_LITERAL(tableDsc, "LNM$FILE_DEV");
POCO_DESCRIPTOR_STRING(nameDsc, name);
if (sys$trnlnm(&trnAttr, &tableDsc, &nameDsc, 0, &items) == 1)
{
if (result[0] == 0x1B)
return std::string((char*) result + 4, length - 4);
else
return std::string((char*) result, length);
}
else
{
return std::string();
}
}
Foundation_END

View File

@@ -0,0 +1,147 @@
//
// Environment_WIN32.cpp
//
// $Id: //poco/1.1.0/Foundation/src/Environment_WIN32.cpp#2 $
//
// Library: Foundation
// Package: Core
// Module: Environment
//
// 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 "Foundation/Environment_WIN32.h"
#include "Foundation/Exception.h"
#include <sstream>
#include <windows.h>
Foundation_BEGIN
std::string EnvironmentImpl::getImpl(const std::string& name)
{
DWORD len = GetEnvironmentVariable(name.c_str(), 0, 0);
if (len == 0) throw NotFoundException(name);
char* buffer = new char[len];
GetEnvironmentVariable(name.c_str(), buffer, len);
std::string result(buffer);
delete [] buffer;
return result;
}
bool EnvironmentImpl::hasImpl(const std::string& name)
{
DWORD len = GetEnvironmentVariable(name.c_str(), 0, 0);
return len > 0;
}
void EnvironmentImpl::setImpl(const std::string& name, const std::string& value)
{
if (SetEnvironmentVariable(name.c_str(), value.c_str()) == 0)
{
std::string msg = "cannot set environment variable: ";
msg.append(name);
throw SystemException(msg);
}
}
std::string EnvironmentImpl::osNameImpl()
{
OSVERSIONINFO vi;
vi.dwOSVersionInfoSize = sizeof(vi);
if (GetVersionEx(&vi) == 0) throw SystemException("Cannot get OS version information");
switch (vi.dwPlatformId)
{
case VER_PLATFORM_WIN32s:
return "Windows 3.x";
case VER_PLATFORM_WIN32_WINDOWS:
return vi.dwMinorVersion == 0 ? "Windows 95" : "Windows 98";
case VER_PLATFORM_WIN32_NT:
return "Windows NT";
default:
return "Unknown";
}
}
std::string EnvironmentImpl::osVersionImpl()
{
OSVERSIONINFO vi;
vi.dwOSVersionInfoSize = sizeof(vi);
if (GetVersionEx(&vi) == 0) throw SystemException("Cannot get OS version information");
std::ostringstream str;
str << vi.dwMajorVersion << "." << vi.dwMinorVersion << " (Build " << (vi.dwBuildNumber & 0xFFFF);
if (vi.szCSDVersion[0]) str << ": " << vi.szCSDVersion;
str << ")";
return str.str();
}
std::string EnvironmentImpl::osArchitectureImpl()
{
SYSTEM_INFO si;
GetSystemInfo(&si);
switch (si.wProcessorArchitecture)
{
case PROCESSOR_ARCHITECTURE_INTEL:
return "IA32";
case PROCESSOR_ARCHITECTURE_MIPS:
return "MIPS";
case PROCESSOR_ARCHITECTURE_ALPHA:
return "ALPHA";
case PROCESSOR_ARCHITECTURE_PPC:
return "PPC";
case PROCESSOR_ARCHITECTURE_IA64:
return "IA64";
#ifdef PROCESSOR_ARCHITECTURE_IA32_ON_WIN64
case PROCESSOR_ARCHITECTURE_IA32_ON_WIN64:
return "IA64/32";
#endif
#ifdef PROCESSOR_ARCHITECTURE_AMD64
case PROCESSOR_ARCHITECTURE_AMD64:
return "AMD64";
#endif
default:
return "Unknown";
}
}
std::string EnvironmentImpl::nodeNameImpl()
{
char name[MAX_COMPUTERNAME_LENGTH + 1];
DWORD size = sizeof(name);
if (GetComputerName(name, &size) == 0) throw SystemException("Cannot get computer name");
return std::string(name);
}
Foundation_END

View File

@@ -0,0 +1,160 @@
//
// Environment_WIN32U.cpp
//
// $Id: //poco/1.1.0/Foundation/src/Environment_WIN32U.cpp#2 $
//
// Library: Foundation
// Package: Core
// Module: Environment
//
// 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 "Foundation/Environment_WIN32U.h"
#include "Foundation/Exception.h"
#include "Foundation/UnicodeConverter.h"
#include "Foundation/Buffer.h"
#include <sstream>
#include <string.h>
#include <windows.h>
Foundation_BEGIN
std::string EnvironmentImpl::getImpl(const std::string& name)
{
std::wstring uname;
UnicodeConverter::toUTF16(name, uname);
DWORD len = GetEnvironmentVariableW(uname.c_str(), 0, 0);
if (len == 0) throw NotFoundException(name);
Buffer<wchar_t> buffer(len);
GetEnvironmentVariableW(uname.c_str(), buffer.begin(), len);
std::string result;
UnicodeConverter::toUTF8(buffer.begin(), len - 1, result);
return result;
}
bool EnvironmentImpl::hasImpl(const std::string& name)
{
std::wstring uname;
UnicodeConverter::toUTF16(name, uname);
DWORD len = GetEnvironmentVariableW(uname.c_str(), 0, 0);
return len > 0;
}
void EnvironmentImpl::setImpl(const std::string& name, const std::string& value)
{
std::wstring uname;
std::wstring uvalue;
UnicodeConverter::toUTF16(name, uname);
UnicodeConverter::toUTF16(value, uvalue);
if (SetEnvironmentVariableW(uname.c_str(), uvalue.c_str()) == 0)
{
std::string msg = "cannot set environment variable: ";
msg.append(name);
throw SystemException(msg);
}
}
std::string EnvironmentImpl::osNameImpl()
{
OSVERSIONINFO vi;
vi.dwOSVersionInfoSize = sizeof(vi);
if (GetVersionEx(&vi) == 0) throw SystemException("Cannot get OS version information");
switch (vi.dwPlatformId)
{
case VER_PLATFORM_WIN32s:
return "Windows 3.x";
case VER_PLATFORM_WIN32_WINDOWS:
return vi.dwMinorVersion == 0 ? "Windows 95" : "Windows 98";
case VER_PLATFORM_WIN32_NT:
return "Windows NT";
default:
return "Unknown";
}
}
std::string EnvironmentImpl::osVersionImpl()
{
OSVERSIONINFO vi;
vi.dwOSVersionInfoSize = sizeof(vi);
if (GetVersionEx(&vi) == 0) throw SystemException("Cannot get OS version information");
std::ostringstream str;
str << vi.dwMajorVersion << "." << vi.dwMinorVersion << " (Build " << (vi.dwBuildNumber & 0xFFFF);
if (vi.szCSDVersion[0]) str << ": " << vi.szCSDVersion;
str << ")";
return str.str();
}
std::string EnvironmentImpl::osArchitectureImpl()
{
SYSTEM_INFO si;
GetSystemInfo(&si);
switch (si.wProcessorArchitecture)
{
case PROCESSOR_ARCHITECTURE_INTEL:
return "IA32";
case PROCESSOR_ARCHITECTURE_MIPS:
return "MIPS";
case PROCESSOR_ARCHITECTURE_ALPHA:
return "ALPHA";
case PROCESSOR_ARCHITECTURE_PPC:
return "PPC";
case PROCESSOR_ARCHITECTURE_IA64:
return "IA64";
#ifdef PROCESSOR_ARCHITECTURE_IA32_ON_WIN64
case PROCESSOR_ARCHITECTURE_IA32_ON_WIN64:
return "IA64/32";
#endif
#ifdef PROCESSOR_ARCHITECTURE_AMD64
case PROCESSOR_ARCHITECTURE_AMD64:
return "AMD64";
#endif
default:
return "Unknown";
}
}
std::string EnvironmentImpl::nodeNameImpl()
{
wchar_t name[MAX_COMPUTERNAME_LENGTH + 1];
DWORD size = MAX_COMPUTERNAME_LENGTH + 1;
if (GetComputerNameW(name, &size) == 0) throw SystemException("Cannot get computer name");
std::string result;
UnicodeConverter::toUTF8(name, result);
return result;
}
Foundation_END

View File

@@ -0,0 +1,133 @@
//
// ErrorHandler.cpp
//
// $Id: //poco/1.1.0/Foundation/src/ErrorHandler.cpp#2 $
//
// Library: Foundation
// Package: Threading
// Module: ErrorHandler
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Foundation/ErrorHandler.h"
#include "Foundation/SingletonHolder.h"
Foundation_BEGIN
ErrorHandler* ErrorHandler::_pHandler = ErrorHandler::defaultHandler();
FastMutex ErrorHandler::_mutex;
ErrorHandler::ErrorHandler()
{
}
ErrorHandler::~ErrorHandler()
{
}
void ErrorHandler::exception(const Exception& exc)
{
poco_debugger_msg(exc.what());
}
void ErrorHandler::exception(const std::exception& exc)
{
poco_debugger_msg(exc.what());
}
void ErrorHandler::exception()
{
poco_debugger_msg("unknown exception");
}
void ErrorHandler::handle(const Exception& exc)
{
FastMutex::ScopedLock lock(_mutex);
try
{
_pHandler->exception(exc);
}
catch (...)
{
}
}
void ErrorHandler::handle(const std::exception& exc)
{
FastMutex::ScopedLock lock(_mutex);
try
{
_pHandler->exception(exc);
}
catch (...)
{
}
}
void ErrorHandler::handle()
{
FastMutex::ScopedLock lock(_mutex);
try
{
_pHandler->exception();
}
catch (...)
{
}
}
ErrorHandler* ErrorHandler::set(ErrorHandler* pHandler)
{
poco_check_ptr(pHandler);
FastMutex::ScopedLock lock(_mutex);
ErrorHandler* pOld = _pHandler;
_pHandler = pHandler;
return pOld;
}
ErrorHandler* ErrorHandler::defaultHandler()
{
static SingletonHolder<ErrorHandler> sh;
return sh.get();
}
Foundation_END

60
Foundation/src/Event.cpp Normal file
View File

@@ -0,0 +1,60 @@
//
// Event.cpp
//
// $Id: //poco/1.1.0/Foundation/src/Event.cpp#2 $
//
// Library: Foundation
// Package: Threading
// Module: Event
//
// 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 "Foundation/Event.h"
#if defined(POCO_OS_FAMILY_WINDOWS)
#include "Event_WIN32.cpp"
#else
#include "Event_POSIX.cpp"
#endif
Foundation_BEGIN
Event::Event(bool autoReset): EventImpl(autoReset)
{
}
Event::~Event()
{
}
Foundation_END

View File

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

View File

@@ -0,0 +1,236 @@
//
// EventLogChannel.cpp
//
// $Id: //poco/1.1.0/Foundation/src/EventLogChannel.cpp#2 $
//
// Library: Foundation
// Package: Logging
// Module: EventLogChannel
//
// 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 "Foundation/EventLogChannel.h"
#include "Foundation/Message.h"
#include "pocomsg.h"
Foundation_BEGIN
const std::string EventLogChannel::PROP_NAME = "name";
const std::string EventLogChannel::PROP_HOST = "host";
const std::string EventLogChannel::PROP_LOGFILE = "logFile";
EventLogChannel::EventLogChannel():
_logFile("Application"),
_h(0)
{
char name[256];
int n = GetModuleFileName(NULL, name, sizeof(name));
if (n > 0)
{
char* end = name + n - 1;
while (end > name && *end != '\\') --end;
if (*end == '\\') ++end;
_name = end;
}
}
EventLogChannel::EventLogChannel(const std::string& name):
_name(name),
_logFile("Application"),
_h(0)
{
}
EventLogChannel::EventLogChannel(const std::string& name, const std::string& host):
_name(name),
_host(host),
_logFile("Application"),
_h(0)
{
}
EventLogChannel::~EventLogChannel()
{
close();
}
void EventLogChannel::open()
{
setUpRegistry();
_h = RegisterEventSource(_host.empty() ? NULL : _host.c_str(), _name.c_str());
if (!_h) throw SystemException("cannot register event source");
}
void EventLogChannel::close()
{
if (_h) DeregisterEventSource(_h);
_h = 0;
}
void EventLogChannel::log(const Message& msg)
{
if (!_h) open();
const char* pMsg = msg.getText().c_str();
ReportEvent(_h, getType(msg), getCategory(msg), POCO_MSG_LOG, NULL, 1, 0, &pMsg, NULL);
}
void EventLogChannel::setProperty(const std::string& name, const std::string& value)
{
if (name == PROP_NAME)
_name = value;
else if (name == PROP_HOST)
_host = value;
else if (name == PROP_LOGFILE)
_logFile = value;
else
Channel::setProperty(name, value);
}
std::string EventLogChannel::getProperty(const std::string& name) const
{
if (name == PROP_NAME)
return _name;
else if (name == PROP_HOST)
return _host;
else if (name == PROP_LOGFILE)
return _logFile;
else
return Channel::getProperty(name);
}
int EventLogChannel::getType(const Message& msg)
{
switch (msg.getPriority())
{
case Message::PRIO_TRACE:
case Message::PRIO_DEBUG:
case Message::PRIO_INFORMATION:
return EVENTLOG_INFORMATION_TYPE;
case Message::PRIO_NOTICE:
case Message::PRIO_WARNING:
return EVENTLOG_WARNING_TYPE;
default:
return EVENTLOG_ERROR_TYPE;
}
}
int EventLogChannel::getCategory(const Message& msg)
{
switch (msg.getPriority())
{
case Message::PRIO_TRACE:
return POCO_CTG_TRACE;
case Message::PRIO_DEBUG:
return POCO_CTG_DEBUG;
case Message::PRIO_INFORMATION:
return POCO_CTG_INFORMATION;
case Message::PRIO_NOTICE:
return POCO_CTG_NOTICE;
case Message::PRIO_WARNING:
return POCO_CTG_WARNING;
case Message::PRIO_ERROR:
return POCO_CTG_ERROR;
case Message::PRIO_CRITICAL:
return POCO_CTG_CRITICAL;
case Message::PRIO_FATAL:
return POCO_CTG_FATAL;
default:
return 0;
}
}
void EventLogChannel::setUpRegistry() const
{
std::string key = "SYSTEM\\CurrentControlSet\\Services\\EventLog\\";
key.append(_logFile);
key.append("\\");
key.append(_name);
HKEY hKey;
DWORD disp;
DWORD rc = RegCreateKeyEx(HKEY_LOCAL_MACHINE, key.c_str(), 0, NULL, REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &hKey, &disp);
if (rc != ERROR_SUCCESS) return;
if (disp == REG_CREATED_NEW_KEY)
{
std::string path;
#if defined(POCO_DLL)
#if defined(_DEBUG)
path = findLibrary("PocoFoundationd.dll");
#else
path = findLibrary("PocoFoundation.dll");
#endif
#endif
if (path.empty())
path = findLibrary("PocoMsg.dll");
if (!path.empty())
{
DWORD count = 8;
DWORD types = 7;
RegSetValueEx(hKey, "CategoryMessageFile", 0, REG_SZ, (const BYTE*) path.c_str(), (DWORD) path.size() + 1);
RegSetValueEx(hKey, "EventMessageFile", 0, REG_SZ, (const BYTE*) path.c_str(), (DWORD) path.size() + 1);
RegSetValueEx(hKey, "CategoryCount", 0, REG_DWORD, (const BYTE*) &count, (DWORD) sizeof(count));
RegSetValueEx(hKey, "TypesSupported", 0, REG_DWORD, (const BYTE*) &types, (DWORD) sizeof(types));
}
}
RegCloseKey(hKey);
}
std::string EventLogChannel::findLibrary(const char* name)
{
std::string path;
HMODULE dll = LoadLibrary(name);
if (dll)
{
char name[MAX_PATH + 1];
int n = GetModuleFileName(dll, name, sizeof(name));
if (n > 0) path = name;
FreeLibrary(dll);
}
return path;
}
Foundation_END

View File

@@ -0,0 +1,117 @@
//
// Event_POSIX.cpp
//
// $Id: //poco/1.1.0/Foundation/src/Event_POSIX.cpp#2 $
//
// Library: Foundation
// Package: Threading
// Module: Event
//
// 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 "Foundation/Event_POSIX.h"
#include <sys/time.h>
Foundation_BEGIN
EventImpl::EventImpl(bool autoReset): _auto(autoReset), _state(false)
{
if (pthread_mutex_init(&_mutex, NULL))
throw SystemException("cannot create event (mutex)");
if (pthread_cond_init(&_cond, NULL))
throw SystemException("cannot create event (condition)");
}
EventImpl::~EventImpl()
{
pthread_cond_destroy(&_cond);
pthread_mutex_destroy(&_mutex);
}
void EventImpl::waitImpl()
{
if (pthread_mutex_lock(&_mutex))
throw SystemException("wait for event failed (lock)");
while (!_state)
{
if (pthread_cond_wait(&_cond, &_mutex))
{
pthread_mutex_unlock(&_mutex);
throw SystemException("wait for event failed");
}
}
if (_auto)
_state = false;
pthread_mutex_unlock(&_mutex);
}
bool EventImpl::waitImpl(long milliseconds)
{
int rc = 0;
struct timespec abstime;
#if defined(__VMS)
struct timespec delta;
delta.tv_sec = milliseconds / 1000;
delta.tv_nsec = (milliseconds % 1000)*1000000;
pthread_get_expiration_np(&delta, &abstime);
#else
struct timeval tv;
gettimeofday(&tv, NULL);
abstime.tv_sec = tv.tv_sec + milliseconds / 1000;
abstime.tv_nsec = tv.tv_usec*1000 + (milliseconds % 1000)*1000000;
if (abstime.tv_nsec >= 1000000000)
{
abstime.tv_nsec -= 1000000000;
abstime.tv_sec++;
}
#endif
if (pthread_mutex_lock(&_mutex) != 0)
throw SystemException("wait for event failed (lock)");
while (!_state)
{
if ((rc = pthread_cond_timedwait(&_cond, &_mutex, &abstime)))
{
if (rc == ETIMEDOUT) break;
pthread_mutex_unlock(&_mutex);
throw SystemException("cannot wait for event");
}
}
if (rc == 0 && _auto) _state = false;
pthread_mutex_unlock(&_mutex);
return rc == 0;
}
Foundation_END

View File

@@ -0,0 +1,83 @@
//
// Event_WIN32.cpp
//
// $Id: //poco/1.1.0/Foundation/src/Event_WIN32.cpp#2 $
//
// Library: Foundation
// Package: Threading
// Module: Event
//
// 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 "Foundation/Event_WIN32.h"
Foundation_BEGIN
EventImpl::EventImpl(bool autoReset)
{
_event = CreateEvent(NULL, autoReset ? FALSE : TRUE, FALSE, NULL);
if (!_event)
throw SystemException("cannot create event");
}
EventImpl::~EventImpl()
{
CloseHandle(_event);
}
void EventImpl::waitImpl()
{
switch (WaitForSingleObject(_event, INFINITE))
{
case WAIT_OBJECT_0:
return;
default:
throw SystemException("wait for event failed");
}
}
bool EventImpl::waitImpl(long milliseconds)
{
switch (WaitForSingleObject(_event, milliseconds + 1))
{
case WAIT_TIMEOUT:
return false;
case WAIT_OBJECT_0:
return true;
default:
throw SystemException("wait for event failed");
}
}
Foundation_END

View File

@@ -0,0 +1,189 @@
//
// Exception.cpp
//
// $Id: //poco/1.1.0/Foundation/src/Exception.cpp#2 $
//
// Library: Foundation
// Package: Core
// Module: Exception
//
// 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 "Foundation/Exception.h"
#include <typeinfo>
Foundation_BEGIN
Exception::Exception(): _pNested(0)
{
}
Exception::Exception(const std::string& msg): _msg(msg), _pNested(0)
{
}
Exception::Exception(const std::string& msg, const std::string& arg): _msg(msg), _pNested(0)
{
if (!arg.empty())
{
_msg.append(": ");
_msg.append(arg);
}
}
Exception::Exception(const std::string& msg, const Exception& nested): _msg(msg), _pNested(nested.clone())
{
}
Exception::Exception(const Exception& exc)
{
_msg = exc._msg;
_pNested = exc._pNested ? exc._pNested->clone() : 0;
}
Exception::~Exception() throw()
{
delete _pNested;
}
Exception& Exception::operator = (const Exception& exc)
{
if (&exc != this)
{
delete _pNested;
_msg = exc._msg;
_pNested = exc._pNested ? exc._pNested->clone() : 0;
}
return *this;
}
const char* Exception::name() const throw()
{
return "Exception";
}
const char* Exception::className() const throw()
{
return typeid(*this).name();
}
const char* Exception::what() const throw()
{
return _msg.c_str();
}
const Exception* Exception::nested() const
{
return _pNested;
}
const std::string& Exception::message() const
{
return _msg;
}
std::string Exception::displayText() const
{
std::string txt = name();
if (!_msg.empty())
{
txt.append(": ");
txt.append(_msg);
}
return txt;
}
Exception* Exception::clone() const
{
return new Exception(*this);
}
POCO_IMPLEMENT_EXCEPTION(LogicException, Exception, "Logic exception")
POCO_IMPLEMENT_EXCEPTION(AssertionViolationException, LogicException, "Assertion violation")
POCO_IMPLEMENT_EXCEPTION(NullPointerException, LogicException, "Null pointer")
POCO_IMPLEMENT_EXCEPTION(BugcheckException, LogicException, "Bugcheck")
POCO_IMPLEMENT_EXCEPTION(InvalidArgumentException, LogicException, "Invalid argument")
POCO_IMPLEMENT_EXCEPTION(NotImplementedException, LogicException, "Not implemented")
POCO_IMPLEMENT_EXCEPTION(RangeException, LogicException, "Out of range")
POCO_IMPLEMENT_EXCEPTION(IllegalStateException, LogicException, "Illegal state")
POCO_IMPLEMENT_EXCEPTION(InvalidAccessException, LogicException, "Invalid access")
POCO_IMPLEMENT_EXCEPTION(SignalException, LogicException, "Signal received")
POCO_IMPLEMENT_EXCEPTION(RuntimeException, Exception, "Runtime exception")
POCO_IMPLEMENT_EXCEPTION(NotFoundException, RuntimeException, "Not found")
POCO_IMPLEMENT_EXCEPTION(ExistsException, RuntimeException, "Exists")
POCO_IMPLEMENT_EXCEPTION(TimeoutException, RuntimeException, "Timeout")
POCO_IMPLEMENT_EXCEPTION(SystemException, RuntimeException, "System exception")
POCO_IMPLEMENT_EXCEPTION(RegularExpressionException, RuntimeException, "Error in regular exception")
POCO_IMPLEMENT_EXCEPTION(LibraryLoadException, RuntimeException, "Cannot load library")
POCO_IMPLEMENT_EXCEPTION(LibraryAlreadyLoadedException, RuntimeException, "Library already loaded")
POCO_IMPLEMENT_EXCEPTION(NoThreadAvailableException, RuntimeException, "No thread available")
POCO_IMPLEMENT_EXCEPTION(PropertyNotSupportedException, RuntimeException, "Property not supported")
POCO_IMPLEMENT_EXCEPTION(PoolOverflowException, RuntimeException, "Pool overflow")
POCO_IMPLEMENT_EXCEPTION(NoPermissionException, RuntimeException, "No permission")
POCO_IMPLEMENT_EXCEPTION(OutOfMemoryException, RuntimeException, "Out of memory")
POCO_IMPLEMENT_EXCEPTION(DataException, RuntimeException, "Data error")
POCO_IMPLEMENT_EXCEPTION(DataFormatException, DataException, "Bad data format")
POCO_IMPLEMENT_EXCEPTION(SyntaxException, DataException, "Syntax error")
POCO_IMPLEMENT_EXCEPTION(CircularReferenceException, DataException, "Circular reference")
POCO_IMPLEMENT_EXCEPTION(PathSyntaxException, SyntaxException, "Bad path syntax")
POCO_IMPLEMENT_EXCEPTION(IOException, RuntimeException, "I/O error")
POCO_IMPLEMENT_EXCEPTION(FileException, IOException, "File access error")
POCO_IMPLEMENT_EXCEPTION(FileExistsException, FileException, "File exists")
POCO_IMPLEMENT_EXCEPTION(FileNotFoundException, FileException, "File not found")
POCO_IMPLEMENT_EXCEPTION(PathNotFoundException, FileException, "Path not found")
POCO_IMPLEMENT_EXCEPTION(FileReadOnlyException, FileException, "File is read-only")
POCO_IMPLEMENT_EXCEPTION(FileAccessDeniedException, FileException, "Access to file denied")
POCO_IMPLEMENT_EXCEPTION(CreateFileException, FileException, "Cannot create file")
POCO_IMPLEMENT_EXCEPTION(OpenFileException, FileException, "Cannot open file")
POCO_IMPLEMENT_EXCEPTION(WriteFileException, FileException, "Cannot write file")
POCO_IMPLEMENT_EXCEPTION(ReadFileException, FileException, "Cannot read file")
POCO_IMPLEMENT_EXCEPTION(UnknownURISchemeException, RuntimeException, "Unknown URI scheme")
POCO_IMPLEMENT_EXCEPTION(ApplicationException, Exception, "Application exception")
POCO_IMPLEMENT_EXCEPTION(BadCastException, RuntimeException, "Bad cast exception")
Foundation_END

View File

@@ -0,0 +1,107 @@
//
// FPEnvironment.cpp
//
// $Id: //poco/1.1.0/Foundation/src/FPEnvironment.cpp#2 $
//
// Library: Foundation
// Package: Core
// Module: FPEnvironment
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
// pull in platform identification macros needed below
#include "Foundation/Platform.h"
#if defined(__osf__) || defined(__VMS)
#include "FPEnvironment_DEC.cpp"
#elif defined(sun) || defined(__sun)
#include "FPEnvironment_SUN.cpp"
#elif defined(__CYGWIN__) || (defined(__GNUC__) && __GNUC__ < 3)
#include "FPEnvironment_DUMMY.cpp"
#elif defined(POCO_OS_FAMILY_UNIX)
#include "FPEnvironment_C99.cpp"
#elif defined(POCO_OS_FAMILY_WINDOWS)
#include "FPEnvironment_WIN32.cpp"
#else
#include "FPEnvironment_DUMMY.cpp"
#endif
// header file must be included after platform-specific part
// due to _XOPEN_SOURCE conflict on Tru64 (see FPEnvironment_DEC.cpp)
#include "Foundation/FPEnvironment.h"
Foundation_BEGIN
FPEnvironment::FPEnvironment()
{
}
FPEnvironment::FPEnvironment(RoundingMode rm)
{
setRoundingMode(rm);
}
FPEnvironment::FPEnvironment(const FPEnvironment& env): FPEnvironmentImpl(env)
{
}
FPEnvironment::~FPEnvironment()
{
}
FPEnvironment& FPEnvironment::operator = (const FPEnvironment& env)
{
if (&env != this)
{
FPEnvironmentImpl::operator = (env);
}
return *this;
}
void FPEnvironment::keepCurrent()
{
keepCurrentImpl();
}
void FPEnvironment::clearFlags()
{
clearFlagsImpl();
}
Foundation_END

View File

@@ -0,0 +1,104 @@
//
// FPEnvironment_C99.cpp
//
// $Id: //poco/1.1.0/Foundation/src/FPEnvironment_C99.cpp#2 $
//
// Library: Foundation
// Package: Core
// Module: FPEnvironment
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Foundation/FPEnvironment_C99.h"
Foundation_BEGIN
FPEnvironmentImpl::FPEnvironmentImpl()
{
fegetenv(&_env);
}
FPEnvironmentImpl::FPEnvironmentImpl(const FPEnvironmentImpl& env)
{
_env = env._env;
}
FPEnvironmentImpl::~FPEnvironmentImpl()
{
fesetenv(&_env);
}
FPEnvironmentImpl& FPEnvironmentImpl::operator = (const FPEnvironmentImpl& env)
{
_env = env._env;
return *this;
}
void FPEnvironmentImpl::keepCurrentImpl()
{
fegetenv(&_env);
}
void FPEnvironmentImpl::clearFlagsImpl()
{
feclearexcept(FE_ALL_EXCEPT);
}
bool FPEnvironmentImpl::isFlagImpl(FlagImpl flag)
{
return fetestexcept(flag) != 0;
}
void FPEnvironmentImpl::setRoundingModeImpl(RoundingModeImpl mode)
{
fesetround(mode);
}
FPEnvironmentImpl::RoundingModeImpl FPEnvironmentImpl::getRoundingModeImpl()
{
return (RoundingModeImpl) fegetround();
}
long double FPEnvironmentImpl::copySignImpl(long double target, long double source)
{
return (source >= 0 && target >= 0) || (source < 0 && target < 0) ? target : -target;
}
Foundation_END

View File

@@ -0,0 +1,217 @@
//
// FPEnvironment_DEC.cpp
//
// $Id: //poco/1.1.0/Foundation/src/FPEnvironment_DEC.cpp#2 $
//
// Library: Foundation
// Package: Core
// Module: FPEnvironment
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
//
// _XOPEN_SOURCE disables the ieee fp functions
// in <math.h>, therefore we undefine it for this file.
//
#undef _XOPEN_SOURCE
#include <math.h>
#include <fp.h>
#include <fp_class.h>
#if defined(__VMS)
#include <starlet.h>
#endif
#include "Foundation/FPEnvironment_DEC.h"
Foundation_BEGIN
FPEnvironmentImpl::FPEnvironmentImpl()
{
#if defined(__VMS)
#pragma pointer_size save
#pragma pointer_size 32
struct _ieee env;
sys$ieee_set_fp_control(0, 0, &env);
#pragma pointer_size restore
_env = env;
#else
_env = ieee_get_fp_control();
#endif
}
FPEnvironmentImpl::FPEnvironmentImpl(const FPEnvironmentImpl& env)
{
_env = env._env;
}
FPEnvironmentImpl::~FPEnvironmentImpl()
{
#if defined(__VMS)
#pragma pointer_size save
#pragma pointer_size 32
struct _ieee mask;
mask.ieee$q_flags = 0xFFFFFFFFFFFFFFFF;
struct _ieee env = _env;
sys$ieee_set_fp_control(&mask, &env, 0);
#pragma pointer_size restore
#else
ieee_set_fp_control(_env);
#endif
}
FPEnvironmentImpl& FPEnvironmentImpl::operator = (const FPEnvironmentImpl& env)
{
_env = env._env;
return *this;
}
bool FPEnvironmentImpl::isInfiniteImpl(float value)
{
int cls = fp_classf(value);
return cls == FP_POS_INF || cls == FP_NEG_INF;
}
bool FPEnvironmentImpl::isInfiniteImpl(double value)
{
int cls = fp_class(value);
return cls == FP_POS_INF || cls == FP_NEG_INF;
}
bool FPEnvironmentImpl::isInfiniteImpl(long double value)
{
int cls = fp_classl(value);
return cls == FP_POS_INF || cls == FP_NEG_INF;
}
bool FPEnvironmentImpl::isNaNImpl(float value)
{
return isnanf(value) != 0;
}
bool FPEnvironmentImpl::isNaNImpl(double value)
{
return isnan(value) != 0;
}
bool FPEnvironmentImpl::isNaNImpl(long double value)
{
return isnanl(value) != 0;
}
float FPEnvironmentImpl::copySignImpl(float target, float source)
{
return copysignf(target, source);
}
double FPEnvironmentImpl::copySignImpl(double target, double source)
{
return copysign(target, source);
}
long double FPEnvironmentImpl::copySignImpl(long double target, long double source)
{
return copysignl(target, source);
}
void FPEnvironmentImpl::keepCurrentImpl()
{
#if defined(__VMS)
#pragma pointer_size save
#pragma pointer_size 32
struct _ieee env;
sys$ieee_set_fp_control(0, 0, &env);
#pragma pointer_size restore
_env = env;
#else
ieee_set_fp_control(_env);
#endif
}
void FPEnvironmentImpl::clearFlagsImpl()
{
#if defined(__VMS)
#pragma pointer_size save
#pragma pointer_size 32
struct _ieee mask;
mask.ieee$q_flags = 0xFFFFFFFFFFFFFFFF;
struct _ieee clr;
clr.ieee$q_flags = 0;
sys$ieee_set_fp_control(&mask, &clr, 0);
#pragma pointer_size restore
#else
ieee_set_fp_control(0);
#endif
}
bool FPEnvironmentImpl::isFlagImpl(FlagImpl flag)
{
#if defined(__VMS)
#pragma pointer_size save
#pragma pointer_size 32
struct _ieee flags;
sys$ieee_set_fp_control(0, 0, &flags);
return (flags.ieee$q_flags & flag) != 0;
#pragma pointer_size restore
#else
return (ieee_get_fp_control() & flag) != 0;
#endif
}
void FPEnvironmentImpl::setRoundingModeImpl(RoundingModeImpl mode)
{
// not supported
}
FPEnvironmentImpl::RoundingModeImpl FPEnvironmentImpl::getRoundingModeImpl()
{
// not supported
return FPEnvironmentImpl::RoundingModeImpl(0);
}
Foundation_END

View File

@@ -0,0 +1,101 @@
//
// FPEnvironment_C99.cpp
//
// $Id: //poco/1.1.0/Foundation/src/FPEnvironment_DUMMY.cpp#2 $
//
// Library: Foundation
// Package: Core
// Module: FPEnvironment
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Foundation/FPEnvironment_DUMMY.h"
Foundation_BEGIN
FPEnvironmentImpl::RoundingModeImpl FPEnvironmentImpl::_roundingMode;
FPEnvironmentImpl::FPEnvironmentImpl()
{
}
FPEnvironmentImpl::FPEnvironmentImpl(const FPEnvironmentImpl& env)
{
}
FPEnvironmentImpl::~FPEnvironmentImpl()
{
}
FPEnvironmentImpl& FPEnvironmentImpl::operator = (const FPEnvironmentImpl& env)
{
return *this;
}
void FPEnvironmentImpl::keepCurrentImpl()
{
}
void FPEnvironmentImpl::clearFlagsImpl()
{
}
bool FPEnvironmentImpl::isFlagImpl(FlagImpl flag)
{
return false;
}
void FPEnvironmentImpl::setRoundingModeImpl(RoundingModeImpl mode)
{
_roundingMode = mode;
}
FPEnvironmentImpl::RoundingModeImpl FPEnvironmentImpl::getRoundingModeImpl()
{
return _roundingMode;
}
long double FPEnvironmentImpl::copySignImpl(long double target, long double source)
{
return (source >= 0 && target >= 0) || (source < 0 && target < 0) ? target : -target;
}
Foundation_END

View File

@@ -0,0 +1,161 @@
//
// FPEnvironment_SUN.cpp
//
// $Id: //poco/1.1.0/Foundation/src/FPEnvironment_SUN.cpp#2 $
//
// Library: Foundation
// Package: Core
// Module: FPEnvironment
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include <math.h>
#include "Foundation/FPEnvironment_SUN.h"
Foundation_BEGIN
FPEnvironmentImpl::FPEnvironmentImpl()
{
_rnd = fpgetround();
_exc = fpgetmask();
}
FPEnvironmentImpl::FPEnvironmentImpl(const FPEnvironmentImpl& env)
{
_rnd = env._rnd;
_exc = env._exc;
}
FPEnvironmentImpl::~FPEnvironmentImpl()
{
fpsetround(_rnd);
fpsetmask(_exc);
}
FPEnvironmentImpl& FPEnvironmentImpl::operator = (const FPEnvironmentImpl& env)
{
_rnd = env._rnd;
_exc = env._exc;
return *this;
}
bool FPEnvironmentImpl::isInfiniteImpl(float value)
{
int cls = fpclass(value);
return cls == FP_PINF || cls == FP_NINF;
}
bool FPEnvironmentImpl::isInfiniteImpl(double value)
{
int cls = fpclass(value);
return cls == FP_PINF || cls == FP_NINF;
}
bool FPEnvironmentImpl::isInfiniteImpl(long double value)
{
int cls = fpclass(value);
return cls == FP_PINF || cls == FP_NINF;
}
bool FPEnvironmentImpl::isNaNImpl(float value)
{
return isnanf(value) != 0;
}
bool FPEnvironmentImpl::isNaNImpl(double value)
{
return isnan(value) != 0;
}
bool FPEnvironmentImpl::isNaNImpl(long double value)
{
return isnan((double) value) != 0;
}
float FPEnvironmentImpl::copySignImpl(float target, float source)
{
return (float) copysign(target, source);
}
double FPEnvironmentImpl::copySignImpl(double target, double source)
{
return (float) copysign(target, source);
}
long double FPEnvironmentImpl::copySignImpl(long double target, long double source)
{
return (source > 0 && target > 0) || (source < 0 && target < 0) ? target : -target;
}
void FPEnvironmentImpl::keepCurrentImpl()
{
fpsetround(_rnd);
fpsetmask(_exc);
}
void FPEnvironmentImpl::clearFlagsImpl()
{
fpsetsticky(0);
}
bool FPEnvironmentImpl::isFlagImpl(FlagImpl flag)
{
return (fpgetsticky() & flag) != 0;
}
void FPEnvironmentImpl::setRoundingModeImpl(RoundingModeImpl mode)
{
fpsetround((fp_rnd) mode);
}
FPEnvironmentImpl::RoundingModeImpl FPEnvironmentImpl::getRoundingModeImpl()
{
return (FPEnvironmentImpl::RoundingModeImpl) fpgetround();
}
Foundation_END

View File

@@ -0,0 +1,98 @@
//
// FPEnvironment_WIN32.cpp
//
// $Id: //poco/1.1.0/Foundation/src/FPEnvironment_WIN32.cpp#2 $
//
// Library: Foundation
// Package: Core
// Module: FPEnvironment
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Foundation/FPEnvironment_WIN32.h"
Foundation_BEGIN
FPEnvironmentImpl::FPEnvironmentImpl()
{
_env = _controlfp(0, 0);
}
FPEnvironmentImpl::FPEnvironmentImpl(const FPEnvironmentImpl& env)
{
_env = env._env;
}
FPEnvironmentImpl::~FPEnvironmentImpl()
{
_controlfp(_env, MCW_RC);
}
FPEnvironmentImpl& FPEnvironmentImpl::operator = (const FPEnvironmentImpl& env)
{
_env = env._env;
return *this;
}
void FPEnvironmentImpl::keepCurrentImpl()
{
_env = _controlfp(0, 0);
}
void FPEnvironmentImpl::clearFlagsImpl()
{
_clearfp();
}
bool FPEnvironmentImpl::isFlagImpl(FlagImpl flag)
{
return (_statusfp() & flag) != 0;
}
void FPEnvironmentImpl::setRoundingModeImpl(RoundingModeImpl mode)
{
_controlfp(mode, MCW_RC);
}
FPEnvironmentImpl::RoundingModeImpl FPEnvironmentImpl::getRoundingModeImpl()
{
return RoundingModeImpl(_controlfp(0, 0) & MCW_RC);
}
Foundation_END

295
Foundation/src/File.cpp Normal file
View File

@@ -0,0 +1,295 @@
//
// File.cpp
//
// $Id: //poco/1.1.0/Foundation/src/File.cpp#2 $
//
// Library: Foundation
// Package: Filesystem
// Module: File
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Foundation/File.h"
#include "Foundation/Path.h"
#include "Foundation/DirectoryIterator.h"
#if defined(POCO_OS_FAMILY_WINDOWS) && defined(POCO_WIN32_UTF8)
#include "File_WIN32U.cpp"
#elif defined(POCO_OS_FAMILY_WINDOWS)
#include "File_WIN32.cpp"
#elif defined(POCO_OS_FAMILY_UNIX)
#include "File_UNIX.cpp"
#else
#include "File_VMS.cpp"
#endif
Foundation_BEGIN
File::File()
{
}
File::File(const std::string& path): FileImpl(path)
{
}
File::File(const char* path): FileImpl(std::string(path))
{
}
File::File(const Path& path): FileImpl(path.toString())
{
}
File::File(const File& file): FileImpl(file.getPathImpl())
{
}
File::~File()
{
}
File& File::operator = (const File& file)
{
setPathImpl(file.getPathImpl());
return *this;
}
File& File::operator = (const std::string& path)
{
setPathImpl(path);
return *this;
}
File& File::operator = (const char* path)
{
poco_check_ptr (path);
setPathImpl(path);
return *this;
}
File& File::operator = (const Path& path)
{
setPathImpl(path.toString());
return *this;
}
void File::swap(File& file)
{
swapImpl(file);
}
bool File::exists() const
{
return existsImpl();
}
bool File::canRead() const
{
return canReadImpl();
}
bool File::canWrite() const
{
return canWriteImpl();
}
bool File::isFile() const
{
return isFileImpl();
}
bool File::isDirectory() const
{
return isDirectoryImpl();
}
Timestamp File::created() const
{
return createdImpl();
}
Timestamp File::getLastModified() const
{
return getLastModifiedImpl();
}
void File::setLastModified(const Timestamp& ts)
{
setLastModifiedImpl(ts);
}
File::FileSize File::getSize() const
{
return getSizeImpl();
}
void File::setSize(FileSizeImpl size)
{
setSizeImpl(size);
}
void File::setWriteable(bool flag)
{
setWriteableImpl(flag);
}
void File::setReadOnly(bool flag)
{
setWriteableImpl(!flag);
}
void File::copyTo(const std::string& path) const
{
Path src(getPathImpl());
File srcFile(src);
if (srcFile.isDirectory())
throw OpenFileException("cannot copy directory", src.toString());
Path dest(path);
if (dest.isDirectory())
{
dest.makeDirectory();
dest.setFileName(src.getFileName());
}
copyToImpl(dest.toString());
}
void File::moveTo(const std::string& path)
{
copyToImpl(path);
removeImpl();
setPathImpl(path);
}
void File::renameTo(const std::string& path)
{
renameToImpl(path);
setPathImpl(path);
}
void File::remove(bool recursive)
{
if (recursive && isDirectory())
{
std::vector<File> files;
list(files);
for (std::vector<File>::iterator it = files.begin(); it != files.end(); ++it)
{
it->remove(true);
}
}
removeImpl();
}
bool File::createFile()
{
return createFileImpl();
}
bool File::createDirectory()
{
return createDirectoryImpl();
}
void File::createDirectories()
{
if (!exists())
{
Path p(getPathImpl());
p.makeDirectory();
if (p.depth() > 1)
{
p.makeParent();
File f(p);
f.createDirectories();
}
createDirectoryImpl();
}
}
void File::list(std::vector<std::string>& files) const
{
files.clear();
DirectoryIterator it(*this);
DirectoryIterator end;
while (it != end)
{
files.push_back(it.name());
++it;
}
}
void File::list(std::vector<File>& files) const
{
files.clear();
DirectoryIterator it(*this);
DirectoryIterator end;
while (it != end)
{
files.push_back(*it);
++it;
}
}
Foundation_END

View File

@@ -0,0 +1,358 @@
//
// FileChannel.cpp
//
// $Id: //poco/1.1.0/Foundation/src/FileChannel.cpp#2 $
//
// Library: Foundation
// Package: Logging
// Module: FileChannel
//
// 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 "Foundation/FileChannel.h"
#include "Foundation/ArchiveStrategy.h"
#include "Foundation/RotateStrategy.h"
#include "Foundation/PurgeStrategy.h"
#include "Foundation/Message.h"
#include "Foundation/NumberParser.h"
#include "Foundation/DateTimeFormatter.h"
#include "Foundation/DateTime.h"
#include "Foundation/LocalDateTime.h"
#include "Foundation/String.h"
#include "Foundation/Timespan.h"
#include "Foundation/Exception.h"
#include <ctype.h>
Foundation_BEGIN
const std::string FileChannel::PROP_PATH = "path";
const std::string FileChannel::PROP_ROTATION = "rotation";
const std::string FileChannel::PROP_ARCHIVE = "archive";
const std::string FileChannel::PROP_TIMES = "times";
const std::string FileChannel::PROP_COMPRESS = "compress";
const std::string FileChannel::PROP_PURGEAGE = "purgeAge";
const std::string FileChannel::PROP_PURGECOUNT = "purgeCount";
FileChannel::FileChannel():
_times("utc"),
_compress(false),
_pFile(0),
_pRotateStrategy(0),
_pArchiveStrategy(new ArchiveByNumberStrategy),
_pPurgeStrategy(0)
{
}
FileChannel::FileChannel(const std::string& path):
_times("utc"),
_compress(false),
_path(path),
_pFile(0),
_pRotateStrategy(0),
_pArchiveStrategy(new ArchiveByNumberStrategy),
_pPurgeStrategy(0)
{
}
FileChannel::~FileChannel()
{
close();
delete _pRotateStrategy;
delete _pArchiveStrategy;
delete _pPurgeStrategy;
}
void FileChannel::open()
{
FastMutex::ScopedLock lock(_mutex);
if (!_pFile)
{
_pFile = new LogFile(_path);
}
}
void FileChannel::close()
{
FastMutex::ScopedLock lock(_mutex);
delete _pFile;
_pFile = 0;
}
void FileChannel::log(const Message& msg)
{
open();
FastMutex::ScopedLock lock(_mutex);
if (_pRotateStrategy && _pArchiveStrategy && _pRotateStrategy->mustRotate(_pFile))
{
try
{
_pFile = _pArchiveStrategy->archive(_pFile);
purge();
}
catch (...)
{
_pFile = new LogFile(_path);
}
}
_pFile->write(msg.getText());
}
void FileChannel::setProperty(const std::string& name, const std::string& value)
{
FastMutex::ScopedLock lock(_mutex);
if (name == PROP_TIMES)
{
_times = value;
if(!_rotation.empty())
setRotation(_rotation);
if(!_archive.empty())
setArchive(_archive);
}
else if (name == PROP_PATH)
_path = value;
else if (name == PROP_ROTATION)
setRotation(value);
else if (name == PROP_ARCHIVE)
setArchive(value);
else if (name == PROP_COMPRESS)
setCompress(value);
else if (name == PROP_PURGEAGE)
setPurgeAge(value);
else if (name == PROP_PURGECOUNT)
setPurgeCount(value);
else
Channel::setProperty(name, value);
}
std::string FileChannel::getProperty(const std::string& name) const
{
if (name == PROP_TIMES)
return _times;
else if (name == PROP_PATH)
return _path;
else if (name == PROP_ROTATION)
return _rotation;
else if (name == PROP_ARCHIVE)
return _archive;
else if (name == PROP_COMPRESS)
return std::string(_compress ? "true" : "false");
else if (name == PROP_PURGEAGE)
return _purgeAge;
else if (name == PROP_PURGECOUNT)
return _purgeCount;
else
return Channel::getProperty(name);
}
Timestamp FileChannel::creationDate() const
{
if (_pFile)
return _pFile->creationDate();
else
return 0;
}
UInt64 FileChannel::size() const
{
if (_pFile)
return _pFile->size();
else
return 0;
}
const std::string& FileChannel::path() const
{
return _path;
}
void FileChannel::setRotation(const std::string& rotation)
{
std::string::const_iterator it = rotation.begin();
std::string::const_iterator end = rotation.end();
int n = 0;
while (it != end && isspace(*it)) ++it;
while (it != end && isdigit(*it)) { n *= 10; n += *it++ - '0'; }
while (it != end && isspace(*it)) ++it;
std::string unit;
while (it != end && isalpha(*it)) unit += *it++;
RotateStrategy* pStrategy = 0;
if ((rotation.find(',') != std::string::npos) || (rotation.find(':') != std::string::npos))
{
if(_times == "utc")
pStrategy = new RotateAtTimeStrategy<DateTime>(rotation);
else if(_times == "local")
pStrategy = new RotateAtTimeStrategy<LocalDateTime>(rotation);
else
throw PropertyNotSupportedException("times", _times);
}
else if (unit == "daily")
pStrategy = new RotateByIntervalStrategy(Timespan(1*Timespan::DAYS));
else if (unit == "weekly")
pStrategy = new RotateByIntervalStrategy(Timespan(7*Timespan::DAYS));
else if (unit == "monthly")
pStrategy = new RotateByIntervalStrategy(Timespan(30*Timespan::DAYS));
else if (unit == "seconds") // for testing only
pStrategy = new RotateByIntervalStrategy(Timespan(n*Timespan::SECONDS));
else if (unit == "hours")
pStrategy = new RotateByIntervalStrategy(Timespan(n*Timespan::HOURS));
else if (unit == "days")
pStrategy = new RotateByIntervalStrategy(Timespan(n*Timespan::DAYS));
else if (unit == "weeks")
pStrategy = new RotateByIntervalStrategy(Timespan(n*7*Timespan::DAYS));
else if (unit == "months")
pStrategy = new RotateByIntervalStrategy(Timespan(n*30*Timespan::DAYS));
else if (unit == "K")
pStrategy = new RotateBySizeStrategy(n*1024);
else if (unit == "M")
pStrategy = new RotateBySizeStrategy(n*1024*1024);
else if (unit.empty())
pStrategy = new RotateBySizeStrategy(n);
else if (unit != "never")
throw InvalidArgumentException("rotation", rotation);
delete _pRotateStrategy;
_pRotateStrategy = pStrategy;
_rotation = rotation;
}
void FileChannel::setArchive(const std::string& archive)
{
ArchiveStrategy* pStrategy = 0;
if (archive == "number")
{
pStrategy = new ArchiveByNumberStrategy;
}
else if (archive == "timestamp")
{
if(_times == "utc")
pStrategy = new ArchiveByTimestampStrategy<DateTime>;
else if(_times == "local")
pStrategy = new ArchiveByTimestampStrategy<LocalDateTime>;
else
throw PropertyNotSupportedException("times", _times);
}
else throw InvalidArgumentException("archive", archive);
delete _pArchiveStrategy;
pStrategy->compress(_compress);
_pArchiveStrategy = pStrategy;
_archive = archive;
}
void FileChannel::setCompress(const std::string& compress)
{
_compress = icompare(compress, "true") == 0;
if (_pArchiveStrategy)
_pArchiveStrategy->compress(_compress);
}
void FileChannel::setPurgeAge(const std::string& age)
{
std::string::const_iterator it = age.begin();
std::string::const_iterator end = age.end();
int n = 0;
while (it != end && isspace(*it)) ++it;
while (it != end && isdigit(*it)) { n *= 10; n += *it++ - '0'; }
while (it != end && isspace(*it)) ++it;
std::string unit;
while (it != end && isalpha(*it)) unit += *it++;
Timespan::TimeDiff factor = Timespan::SECONDS;
if (unit == "minutes")
factor = Timespan::MINUTES;
else if (unit == "hours")
factor = Timespan::HOURS;
else if (unit == "days")
factor = Timespan::DAYS;
else if (unit == "weeks")
factor = 7*Timespan::DAYS;
else if (unit == "months")
factor *= 30*Timespan::DAYS;
else if (unit != "seconds")
throw InvalidArgumentException("purgeAge", age);
delete _pPurgeStrategy;
_pPurgeStrategy = new PurgeByAgeStrategy(Timespan(factor*n));
_purgeAge = age;
}
void FileChannel::setPurgeCount(const std::string& count)
{
std::string::const_iterator it = count.begin();
std::string::const_iterator end = count.end();
int n = 0;
while (it != end && isspace(*it)) ++it;
while (it != end && isdigit(*it)) { n *= 10; n += *it++ - '0'; }
while (it != end && isspace(*it)) ++it;
delete _pPurgeStrategy;
_pPurgeStrategy = new PurgeByCountStrategy(n);
_purgeCount = count;
}
void FileChannel::purge()
{
if (_pPurgeStrategy)
{
try
{
_pPurgeStrategy->purge(_path);
}
catch (...)
{
}
}
}
Foundation_END

View File

@@ -0,0 +1,86 @@
//
// FileStreamFactory.cpp
//
// $Id: //poco/1.1.0/Foundation/src/FileStreamFactory.cpp#2 $
//
// Library: Foundation
// Package: URI
// Module: FileStreamFactory
//
// 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 "Foundation/FileStreamFactory.h"
#include "Foundation/URI.h"
#include "Foundation/Path.h"
#include "Foundation/File.h"
#include "Foundation/Exception.h"
#include <fstream>
Foundation_BEGIN
FileStreamFactory::FileStreamFactory()
{
}
FileStreamFactory::~FileStreamFactory()
{
}
std::istream* FileStreamFactory::open(const URI& uri)
{
poco_assert (uri.isRelative() || uri.getScheme() == "file");
std::string uriPath = uri.getPath();
if (uriPath.substr(0, 2) == "./")
uriPath.erase(0, 2);
Path p(uriPath, Path::PATH_UNIX);
p.setNode(uri.getHost());
return open(p);
}
std::istream* FileStreamFactory::open(const Path& path)
{
File file(path);
if (!file.exists()) throw FileNotFoundException(path.toString());
std::ifstream* istr = new std::ifstream(path.toString().c_str(), std::ios::binary);
if (!istr->good())
{
delete istr;
throw OpenFileException(path.toString());
}
return istr;
}
Foundation_END

View File

@@ -0,0 +1,375 @@
//
// File_UNIX.cpp
//
// $Id: //poco/1.1.0/Foundation/src/File_UNIX.cpp#2 $
//
// Library: Foundation
// Package: Filesystem
// Module: File
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Foundation/File_UNIX.h"
#include "Foundation/Buffer.h"
#include "Foundation/Exception.h"
#include <algorithm>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <errno.h>
#include <unistd.h>
#include <stdio.h>
#include <utime.h>
#include <string.h>
Foundation_BEGIN
FileImpl::FileImpl()
{
}
FileImpl::FileImpl(const std::string& path): _path(path)
{
std::string::size_type n = _path.size();
if (n > 0 && _path[n - 1] == '/')
_path.resize(n - 1);
}
FileImpl::~FileImpl()
{
}
void FileImpl::swapImpl(FileImpl& file)
{
std::swap(_path, file._path);
}
void FileImpl::setPathImpl(const std::string& path)
{
_path = path;
}
bool FileImpl::existsImpl() const
{
poco_assert (!_path.empty());
struct stat st;
return stat(_path.c_str(), &st) == 0;
}
bool FileImpl::canReadImpl() const
{
poco_assert (!_path.empty());
struct stat st;
if (stat(_path.c_str(), &st) == 0)
{
if (st.st_uid == geteuid())
return (st.st_mode & S_IRUSR) != 0;
else if (st.st_gid == getegid())
return (st.st_mode & S_IRGRP) != 0;
else
return (st.st_mode & S_IROTH) != 0;
}
else handleError(_path);
return false;
}
bool FileImpl::canWriteImpl() const
{
poco_assert (!_path.empty());
struct stat st;
if (stat(_path.c_str(), &st) == 0)
{
if (st.st_uid == geteuid())
return (st.st_mode & S_IWUSR) != 0;
else if (st.st_gid == getegid())
return (st.st_mode & S_IWGRP) != 0;
else
return (st.st_mode & S_IWOTH) != 0;
}
else handleError(_path);
return false;
}
bool FileImpl::isFileImpl() const
{
poco_assert (!_path.empty());
struct stat st;
if (stat(_path.c_str(), &st) == 0)
return S_ISREG(st.st_mode);
else
handleError(_path);
return false;
}
bool FileImpl::isDirectoryImpl() const
{
poco_assert (!_path.empty());
struct stat st;
if (stat(_path.c_str(), &st) == 0)
return S_ISDIR(st.st_mode);
else
handleError(_path);
return false;
}
Timestamp FileImpl::createdImpl() const
{
poco_assert (!_path.empty());
struct stat st;
if (stat(_path.c_str(), &st) == 0)
return Timestamp::fromEpochTime(st.st_mtime);
else
handleError(_path);
return 0;
}
Timestamp FileImpl::getLastModifiedImpl() const
{
poco_assert (!_path.empty());
struct stat st;
if (stat(_path.c_str(), &st) == 0)
return Timestamp::fromEpochTime(st.st_mtime);
else
handleError(_path);
return 0;
}
void FileImpl::setLastModifiedImpl(const Timestamp& ts)
{
poco_assert (!_path.empty());
struct utimbuf tb;
tb.actime = ts.epochTime();
tb.modtime = ts.epochTime();
if (utime(_path.c_str(), &tb) != 0)
handleError(_path);
}
FileImpl::FileSizeImpl FileImpl::getSizeImpl() const
{
poco_assert (!_path.empty());
struct stat st;
if (stat(_path.c_str(), &st) == 0)
return st.st_size;
else
handleError(_path);
return 0;
}
void FileImpl::setSizeImpl(FileSizeImpl size)
{
poco_assert (!_path.empty());
if (truncate(_path.c_str(), size) != 0)
handleError(_path);
}
void FileImpl::setWriteableImpl(bool flag)
{
poco_assert (!_path.empty());
struct stat st;
if (stat(_path.c_str(), &st) != 0)
handleError(_path);
mode_t mode;
if (flag)
{
mode = st.st_mode | S_IWUSR;
}
else
{
mode_t wmask = S_IWUSR | S_IWGRP | S_IWOTH;
mode = st.st_mode & ~wmask;
}
if (chmod(_path.c_str(), mode) != 0)
handleError(_path);
}
void FileImpl::copyToImpl(const std::string& path) const
{
poco_assert (!_path.empty());
int sd = open(_path.c_str(), O_RDONLY);
if (sd == -1) handleError(_path);
struct stat st;
if (fstat(sd, &st) != 0)
{
close(sd);
handleError(_path);
}
const long blockSize = st.st_blksize;
int dd = open(path.c_str(), O_CREAT | O_TRUNC | O_WRONLY, st.st_mode & S_IRWXU);
if (dd == -1)
{
close(sd);
handleError(path);
}
Buffer<char> buffer(blockSize);
try
{
int n;
while ((n = read(sd, buffer.begin(), blockSize)) > 0)
{
if (write(dd, buffer.begin(), n) != n)
handleError(path);
}
if (n < 0)
handleError(_path);
}
catch (...)
{
close(sd);
close(dd);
throw;
}
close(sd);
if (fsync(dd) != 0)
{
close(dd);
handleError(path);
}
if (close(dd) != 0)
handleError(path);
}
void FileImpl::renameToImpl(const std::string& path)
{
poco_assert (!_path.empty());
if (rename(_path.c_str(), path.c_str()) != 0)
handleError(_path);
}
void FileImpl::removeImpl()
{
poco_assert (!_path.empty());
int rc;
if (isDirectoryImpl())
rc = rmdir(_path.c_str());
else
rc = unlink(_path.c_str());
if (rc) handleError(_path);
}
bool FileImpl::createFileImpl()
{
poco_assert (!_path.empty());
int n = open(_path.c_str(), O_WRONLY | O_CREAT | O_EXCL, S_IRUSR | S_IWUSR);
if (n != -1)
{
close(n);
return true;
}
if (n == -1 && errno == EEXIST)
return false;
else
handleError(_path);
return false;
}
bool FileImpl::createDirectoryImpl()
{
poco_assert (!_path.empty());
if (existsImpl() && isDirectoryImpl())
return false;
if (mkdir(_path.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) != 0)
handleError(_path);
return true;
}
void FileImpl::handleError(const std::string& path)
{
switch (errno)
{
case EIO:
throw IOException(path);
case EPERM:
throw FileAccessDeniedException("insufficient permissions", path);
case EACCES:
throw FileAccessDeniedException(path);
case ENOENT:
throw FileNotFoundException(path);
case ENOTDIR:
throw OpenFileException("not a directory", path);
case EISDIR:
throw OpenFileException("not a file", path);
case EROFS:
throw FileReadOnlyException(path);
case EEXIST:
throw FileExistsException(path);
case ENOSPC:
throw FileException("no space left on device", path);
case EDQUOT:
throw FileException("disk quota exceeded", path);
case ENOTEMPTY:
throw FileException("directory not empty", path);
case ENAMETOOLONG:
throw PathSyntaxException(path);
default:
throw FileException(strerror(errno), path);
}
}
Foundation_END

375
Foundation/src/File_VMS.cpp Normal file
View File

@@ -0,0 +1,375 @@
//
// File_VMS.cpp
//
// $Id: //poco/1.1.0/Foundation/src/File_VMS.cpp#2 $
//
// Library: Foundation
// Package: Filesystem
// Module: File
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Foundation/File_VMS.h"
#include "Foundation/Exception.h"
#include "Foundation/Path.h"
#include <stdio.h>
#include <unistd.h>
#include <unixio.h>
#include <file.h>
#include <stat.h>
#include <errno.h>
#include <utime.h>
#include <lib$routines.h>
#include <rmsdef.h>
#include <starlet.h>
#include <lnmdef.h>
#include <ssdef.h>
#include <descrip.h>
Foundation_BEGIN
FileImpl::FileImpl()
{
}
FileImpl::FileImpl(const std::string& path): _path(path)
{
if (!_path.empty())
{
Path p(_path);
p.makeFile();
_path = p.toString();
}
}
FileImpl::~FileImpl()
{
}
void FileImpl::swapImpl(FileImpl& file)
{
std::swap(_path, file._path);
}
void FileImpl::setPathImpl(const std::string& path)
{
_path = path;
}
bool FileImpl::existsImpl() const
{
poco_assert (!_path.empty());
return access(_path.c_str(), F_OK) == 0;
}
bool FileImpl::canReadImpl() const
{
poco_assert (!_path.empty());
struct stat st;
if (stat(_path.c_str(), &st) == 0)
{
if (st.st_uid == geteuid())
return (st.st_mode & S_IRUSR) != 0;
else if (st.st_gid == getegid())
return (st.st_mode & S_IRGRP) != 0;
else
return (st.st_mode & S_IROTH) != 0;
}
else handleError(_path);
return false;
}
bool FileImpl::canWriteImpl() const
{
poco_assert (!_path.empty());
struct stat st;
if (stat(_path.c_str(), &st) == 0)
{
if (st.st_uid == geteuid())
return (st.st_mode & S_IWUSR) != 0;
else if (st.st_gid == getegid())
return (st.st_mode & S_IWGRP) != 0;
else
return (st.st_mode & S_IWOTH) != 0;
}
else handleError(_path);
return false;
}
bool FileImpl::isFileImpl() const
{
poco_assert (!_path.empty());
struct stat st;
if (stat(_path.c_str(), &st) == 0)
return S_ISREG(st.st_mode);
else
handleError(_path);
return false;
}
bool FileImpl::isDirectoryImpl() const
{
poco_assert (!_path.empty());
struct stat st;
if (stat(_path.c_str(), &st) == 0)
return S_ISDIR(st.st_mode);
else
handleError(_path);
return false;
}
Timestamp FileImpl::createdImpl() const
{
poco_assert (!_path.empty());
struct stat st;
if (stat(_path.c_str(), &st) == 0)
return Timestamp(st.st_mtime);
else
handleError(_path);
return 0;
}
Timestamp FileImpl::getLastModifiedImpl() const
{
poco_assert (!_path.empty());
struct stat st;
if (stat(_path.c_str(), &st) == 0)
return Timestamp(st.st_mtime);
else
handleError(_path);
return 0;
}
void FileImpl::setLastModifiedImpl(const Timestamp& ts)
{
poco_assert (!_path.empty());
struct utimbuf tb;
tb.actime = ts.epochTime();
tb.modtime = ts.epochTime();
if (utime(_path.c_str(), &tb) != 0)
handleError(_path);
}
FileImpl::FileSizeImpl FileImpl::getSizeImpl() const
{
poco_assert (!_path.empty());
struct stat st;
if (stat(_path.c_str(), &st) == 0)
return st.st_size;
else
handleError(_path);
return 0;
}
void FileImpl::setSizeImpl(FileSizeImpl size)
{
poco_assert (!_path.empty());
if (truncate(_path.c_str(), size) != 0)
handleError(_path);
}
void FileImpl::setWriteableImpl(bool flag)
{
poco_assert (!_path.empty());
struct stat st;
if (stat(_path.c_str(), &st) != 0)
handleError(_path);
mode_t mode;
if (flag)
{
mode = st.st_mode | S_IWUSR;
}
else
{
mode_t wmask = S_IWUSR | S_IWGRP | S_IWOTH;
mode = st.st_mode & ~wmask;
}
if (chmod(_path.c_str(), mode) != 0)
handleError(_path);
}
void FileImpl::copyToImpl(const std::string& path) const
{
poco_assert (!_path.empty());
// copying a file correctly under OpenVMS is non-trivial,
// so we just invoke the COPY program.
std::string cmd = "COPY ";
cmd.append(_path);
cmd.append(" ");
cmd.append(path);
if (system(cmd.c_str()) != 0)
throw FileException("COPY command failed", _path);
}
void FileImpl::renameToImpl(const std::string& path)
{
poco_assert (!_path.empty());
POCO_DESCRIPTOR_STRING(oldNameDsc, _path);
POCO_DESCRIPTOR_STRING(newNameDsc, path);
int res;
if ((res = lib$rename_file(&oldNameDsc, &newNameDsc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)) != 1)
{
switch (res & 0x0FFFFFFF)
{
case RMS$_FNF:
throw FileNotFoundException(_path);
case RMS$_DEV:
case RMS$_DNF:
throw PathNotFoundException(_path);
case RMS$_SYN:
throw PathSyntaxException(path);
case RMS$_RMV:
throw FileAccessDeniedException(_path);
case RMS$_PRV:
throw FileAccessDeniedException("insufficient privileges", _path);
default:
throw FileException(path);
}
}
}
void FileImpl::removeImpl()
{
poco_assert (!_path.empty());
int rc;
if (isDirectoryImpl())
{
setWriteableImpl(true);
rc = rmdir(_path.c_str());
}
else
{
rc = unlink(_path.c_str());
}
if (rc) handleError(_path);
}
bool FileImpl::createFileImpl()
{
poco_assert (!_path.empty());
int n = open(_path.c_str(), O_WRONLY | O_CREAT | O_EXCL);
if (n != -1)
{
close(n);
return true;
}
if (n == -1 && errno == EEXIST)
return false;
else
handleError(_path);
return false;
}
bool FileImpl::createDirectoryImpl()
{
poco_assert (!_path.empty());
if (existsImpl() && isDirectoryImpl())
return false;
Path p(_path);
p.makeDirectory();
if (mkdir(p.toString().c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) != 0)
handleError(_path);
return true;
}
void FileImpl::handleError(const std::string& path)
{
switch (errno)
{
case EIO:
throw IOException(path);
case EPERM:
throw FileAccessDeniedException("insufficient permissions", path);
case EACCES:
throw FileAccessDeniedException(path);
case ENOENT:
throw FileNotFoundException(path);
case ENOTDIR:
throw OpenFileException("not a directory", path);
case EISDIR:
throw OpenFileException("not a file", path);
case EROFS:
throw FileReadOnlyException(path);
case EEXIST:
throw FileExistsException(path);
case ENOSPC:
throw FileException("no space left on device", path);
case EDQUOT:
throw FileException("disk quota exceeded", path);
case ENOTEMPTY:
throw FileException("directory not empty", path);
case ENAMETOOLONG:
throw PathSyntaxException(path);
default:
throw FileException(strerror(errno), path);
}
}
Foundation_END

View File

@@ -0,0 +1,353 @@
//
// File_WIN32.cpp
//
// $Id: //poco/1.1.0/Foundation/src/File_WIN32.cpp#2 $
//
// Library: Foundation
// Package: Filesystem
// Module: File
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Foundation/File_WIN32.h"
#include "Foundation/Exception.h"
#include <windows.h>
Foundation_BEGIN
class FileHandle
{
public:
FileHandle(const std::string& path, DWORD access, DWORD share, DWORD disp)
{
_h = CreateFile(path.c_str(), access, share, 0, disp, 0, 0);
if (!_h) FileImpl::handleError(path);
}
~FileHandle()
{
if (_h) CloseHandle(_h);
}
HANDLE get() const
{
return _h;
}
private:
HANDLE _h;
};
FileImpl::FileImpl()
{
}
FileImpl::FileImpl(const std::string& path): _path(path)
{
std::string::size_type n = _path.size();
if (n > 0 && (_path[n - 1] == '\\' || _path[n - 1] == '/'))
_path.resize(n - 1);
}
FileImpl::~FileImpl()
{
}
void FileImpl::swapImpl(FileImpl& file)
{
std::swap(_path, file._path);
}
void FileImpl::setPathImpl(const std::string& path)
{
_path = path;
}
bool FileImpl::existsImpl() const
{
poco_assert (!_path.empty());
DWORD attr = GetFileAttributes(_path.c_str());
if (attr == 0xFFFFFFFF)
{
switch (GetLastError())
{
case ERROR_FILE_NOT_FOUND:
case ERROR_PATH_NOT_FOUND:
case ERROR_NOT_READY:
case ERROR_INVALID_DRIVE:
return false;
default:
handleError(_path);
}
}
return true;
}
bool FileImpl::canReadImpl() const
{
poco_assert (!_path.empty());
DWORD attr = GetFileAttributes(_path.c_str());
if (attr == 0xFFFFFFFF)
{
switch (GetLastError())
{
case ERROR_ACCESS_DENIED:
return false;
default:
handleError(_path);
}
}
return true;
}
bool FileImpl::canWriteImpl() const
{
poco_assert (!_path.empty());
DWORD attr = GetFileAttributes(_path.c_str());
if (attr == 0xFFFFFFFF)
handleError(_path);
return (attr & FILE_ATTRIBUTE_READONLY) == 0;
}
bool FileImpl::isFileImpl() const
{
poco_assert (!_path.empty());
DWORD attr = GetFileAttributes(_path.c_str());
if (attr == 0xFFFFFFFF)
handleError(_path);
return (attr & FILE_ATTRIBUTE_DIRECTORY) == 0;
}
bool FileImpl::isDirectoryImpl() const
{
poco_assert (!_path.empty());
DWORD attr = GetFileAttributes(_path.c_str());
if (attr == 0xFFFFFFFF)
handleError(_path);
return (attr & FILE_ATTRIBUTE_DIRECTORY) != 0;
}
Timestamp FileImpl::createdImpl() const
{
poco_assert (!_path.empty());
WIN32_FILE_ATTRIBUTE_DATA fad;
if (GetFileAttributesEx(_path.c_str(), GetFileExInfoStandard, &fad) == 0)
handleError(_path);
return Timestamp::fromFileTimeNP(fad.ftCreationTime.dwLowDateTime, fad.ftCreationTime.dwHighDateTime);
}
Timestamp FileImpl::getLastModifiedImpl() const
{
poco_assert (!_path.empty());
WIN32_FILE_ATTRIBUTE_DATA fad;
if (GetFileAttributesEx(_path.c_str(), GetFileExInfoStandard, &fad) == 0)
handleError(_path);
return Timestamp::fromFileTimeNP(fad.ftLastWriteTime.dwLowDateTime, fad.ftLastWriteTime.dwHighDateTime);
}
void FileImpl::setLastModifiedImpl(const Timestamp& ts)
{
poco_assert (!_path.empty());
UInt32 low;
UInt32 high;
ts.toFileTimeNP(low, high);
FILETIME ft;
ft.dwLowDateTime = low;
ft.dwHighDateTime = high;
FileHandle fh(_path, FILE_ALL_ACCESS, FILE_SHARE_WRITE, OPEN_EXISTING);
if (SetFileTime(fh.get(), 0, &ft, &ft) == 0)
handleError(_path);
}
FileImpl::FileSizeImpl FileImpl::getSizeImpl() const
{
poco_assert (!_path.empty());
WIN32_FILE_ATTRIBUTE_DATA fad;
if (GetFileAttributesEx(_path.c_str(), GetFileExInfoStandard, &fad) == 0)
handleError(_path);
LARGE_INTEGER li;
li.LowPart = fad.nFileSizeLow;
li.HighPart = fad.nFileSizeHigh;
return li.QuadPart;
}
void FileImpl::setSizeImpl(FileSizeImpl size)
{
poco_assert (!_path.empty());
FileHandle fh(_path, GENERIC_WRITE, FILE_SHARE_WRITE, OPEN_EXISTING);
LARGE_INTEGER li;
li.QuadPart = size;
if (SetFilePointer(fh.get(), li.LowPart, &li.HighPart, FILE_BEGIN) == -1)
handleError(_path);
if (SetEndOfFile(fh.get()) == 0)
handleError(_path);
}
void FileImpl::setWriteableImpl(bool flag)
{
poco_assert (!_path.empty());
DWORD attr = GetFileAttributes(_path.c_str());
if (attr == -1)
handleError(_path);
if (flag)
attr &= ~FILE_ATTRIBUTE_READONLY;
else
attr |= FILE_ATTRIBUTE_READONLY;
if (SetFileAttributes(_path.c_str(), attr) == 0)
handleError(_path);
}
void FileImpl::copyToImpl(const std::string& path) const
{
poco_assert (!_path.empty());
if (CopyFile(_path.c_str(), path.c_str(), FALSE) == 0)
handleError(_path);
}
void FileImpl::renameToImpl(const std::string& path)
{
poco_assert (!_path.empty());
if (MoveFile(_path.c_str(), path.c_str()) == 0)
handleError(_path);
}
void FileImpl::removeImpl()
{
poco_assert (!_path.empty());
if (isDirectoryImpl())
{
if (RemoveDirectory(_path.c_str()) == 0)
handleError(_path);
}
else
{
if (DeleteFile(_path.c_str()) == 0)
handleError(_path);
}
}
bool FileImpl::createFileImpl()
{
poco_assert (!_path.empty());
HANDLE hFile = CreateFile(_path.c_str(), GENERIC_WRITE, 0, 0, CREATE_NEW, 0, 0);
if (hFile)
{
CloseHandle(hFile);
return true;
}
else if (GetLastError() == ERROR_ALREADY_EXISTS)
return false;
else
handleError(_path);
return false;
}
bool FileImpl::createDirectoryImpl()
{
poco_assert (!_path.empty());
if (existsImpl() && isDirectoryImpl())
return false;
if (CreateDirectory(_path.c_str(), 0) == 0)
handleError(_path);
return true;
}
void FileImpl::handleError(const std::string& path)
{
switch (GetLastError())
{
case ERROR_FILE_NOT_FOUND:
throw FileNotFoundException(path);
case ERROR_PATH_NOT_FOUND:
case ERROR_BAD_NETPATH:
case ERROR_CANT_RESOLVE_FILENAME:
case ERROR_INVALID_DRIVE:
throw PathNotFoundException(path);
case ERROR_ACCESS_DENIED:
throw FileAccessDeniedException(path);
case ERROR_ALREADY_EXISTS:
case ERROR_FILE_EXISTS:
throw FileExistsException(path);
case ERROR_INVALID_NAME:
case ERROR_DIRECTORY:
case ERROR_FILENAME_EXCED_RANGE:
case ERROR_BAD_PATHNAME:
throw PathSyntaxException(path);
case ERROR_FILE_READ_ONLY:
throw FileReadOnlyException(path);
case ERROR_CANNOT_MAKE:
throw CreateFileException(path);
case ERROR_DIR_NOT_EMPTY:
throw FileException("directory not empty", path);
default:
throw FileException(path);
}
}
Foundation_END

View File

@@ -0,0 +1,361 @@
//
// File_WIN32U.cpp
//
// $Id: //poco/1.1.0/Foundation/src/File_WIN32U.cpp#2 $
//
// Library: Foundation
// Package: Filesystem
// Module: File
//
// 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 "Foundation/File_WIN32U.h"
#include "Foundation/Exception.h"
#include "Foundation/UnicodeConverter.h"
#include <windows.h>
Foundation_BEGIN
class FileHandle
{
public:
FileHandle(const std::string& path, const std::wstring& upath, DWORD access, DWORD share, DWORD disp)
{
_h = CreateFileW(upath.c_str(), access, share, 0, disp, 0, 0);
if (!_h) FileImpl::handleError(path);
}
~FileHandle()
{
if (_h) CloseHandle(_h);
}
HANDLE get() const
{
return _h;
}
private:
HANDLE _h;
};
FileImpl::FileImpl()
{
}
FileImpl::FileImpl(const std::string& path): _path(path)
{
std::string::size_type n = _path.size();
if (n > 0 && (_path[n - 1] == '\\' || _path[n - 1] == '/'))
_path.resize(n - 1);
UnicodeConverter::toUTF16(_path, _upath);
}
FileImpl::~FileImpl()
{
}
void FileImpl::swapImpl(FileImpl& file)
{
std::swap(_path, file._path);
std::swap(_upath, file._upath);
}
void FileImpl::setPathImpl(const std::string& path)
{
_path = path;
UnicodeConverter::toUTF16(_path, _upath);
}
bool FileImpl::existsImpl() const
{
poco_assert (!_path.empty());
DWORD attr = GetFileAttributesW(_upath.c_str());
if (attr == 0xFFFFFFFF)
{
switch (GetLastError())
{
case ERROR_FILE_NOT_FOUND:
case ERROR_PATH_NOT_FOUND:
case ERROR_NOT_READY:
case ERROR_INVALID_DRIVE:
return false;
default:
handleError(_path);
}
}
return true;
}
bool FileImpl::canReadImpl() const
{
poco_assert (!_path.empty());
DWORD attr = GetFileAttributesW(_upath.c_str());
if (attr == 0xFFFFFFFF)
{
switch (GetLastError())
{
case ERROR_ACCESS_DENIED:
return false;
default:
handleError(_path);
}
}
return true;
}
bool FileImpl::canWriteImpl() const
{
poco_assert (!_path.empty());
DWORD attr = GetFileAttributesW(_upath.c_str());
if (attr == 0xFFFFFFFF)
handleError(_path);
return (attr & FILE_ATTRIBUTE_READONLY) == 0;
}
bool FileImpl::isFileImpl() const
{
poco_assert (!_path.empty());
DWORD attr = GetFileAttributesW(_upath.c_str());
if (attr == 0xFFFFFFFF)
handleError(_path);
return (attr & FILE_ATTRIBUTE_DIRECTORY) == 0;
}
bool FileImpl::isDirectoryImpl() const
{
poco_assert (!_path.empty());
DWORD attr = GetFileAttributesW(_upath.c_str());
if (attr == 0xFFFFFFFF)
handleError(_path);
return (attr & FILE_ATTRIBUTE_DIRECTORY) != 0;
}
Timestamp FileImpl::createdImpl() const
{
poco_assert (!_path.empty());
WIN32_FILE_ATTRIBUTE_DATA fad;
if (GetFileAttributesExW(_upath.c_str(), GetFileExInfoStandard, &fad) == 0)
handleError(_path);
return Timestamp::fromFileTimeNP(fad.ftCreationTime.dwLowDateTime, fad.ftCreationTime.dwHighDateTime);
}
Timestamp FileImpl::getLastModifiedImpl() const
{
poco_assert (!_path.empty());
WIN32_FILE_ATTRIBUTE_DATA fad;
if (GetFileAttributesExW(_upath.c_str(), GetFileExInfoStandard, &fad) == 0)
handleError(_path);
return Timestamp::fromFileTimeNP(fad.ftLastWriteTime.dwLowDateTime, fad.ftLastWriteTime.dwHighDateTime);
}
void FileImpl::setLastModifiedImpl(const Timestamp& ts)
{
poco_assert (!_path.empty());
UInt32 low;
UInt32 high;
ts.toFileTimeNP(low, high);
FILETIME ft;
ft.dwLowDateTime = low;
ft.dwHighDateTime = high;
FileHandle fh(_path, _upath, FILE_ALL_ACCESS, FILE_SHARE_WRITE, OPEN_EXISTING);
if (SetFileTime(fh.get(), 0, &ft, &ft) == 0)
handleError(_path);
}
FileImpl::FileSizeImpl FileImpl::getSizeImpl() const
{
poco_assert (!_path.empty());
WIN32_FILE_ATTRIBUTE_DATA fad;
if (GetFileAttributesExW(_upath.c_str(), GetFileExInfoStandard, &fad) == 0)
handleError(_path);
LARGE_INTEGER li;
li.LowPart = fad.nFileSizeLow;
li.HighPart = fad.nFileSizeHigh;
return li.QuadPart;
}
void FileImpl::setSizeImpl(FileSizeImpl size)
{
poco_assert (!_path.empty());
FileHandle fh(_path, _upath, GENERIC_WRITE, FILE_SHARE_WRITE, OPEN_EXISTING);
LARGE_INTEGER li;
li.QuadPart = size;
if (SetFilePointer(fh.get(), li.LowPart, &li.HighPart, FILE_BEGIN) == -1)
handleError(_path);
if (SetEndOfFile(fh.get()) == 0)
handleError(_path);
}
void FileImpl::setWriteableImpl(bool flag)
{
poco_assert (!_path.empty());
DWORD attr = GetFileAttributesW(_upath.c_str());
if (attr == -1)
handleError(_path);
if (flag)
attr &= ~FILE_ATTRIBUTE_READONLY;
else
attr |= FILE_ATTRIBUTE_READONLY;
if (SetFileAttributesW(_upath.c_str(), attr) == 0)
handleError(_path);
}
void FileImpl::copyToImpl(const std::string& path) const
{
poco_assert (!_path.empty());
std::wstring upath;
UnicodeConverter::toUTF16(path, upath);
if (CopyFileW(_upath.c_str(), upath.c_str(), FALSE) == 0)
handleError(_path);
}
void FileImpl::renameToImpl(const std::string& path)
{
poco_assert (!_path.empty());
std::wstring upath;
UnicodeConverter::toUTF16(path, upath);
if (MoveFileW(_upath.c_str(), upath.c_str()) == 0)
handleError(_path);
}
void FileImpl::removeImpl()
{
poco_assert (!_path.empty());
if (isDirectoryImpl())
{
if (RemoveDirectoryW(_upath.c_str()) == 0)
handleError(_path);
}
else
{
if (DeleteFileW(_upath.c_str()) == 0)
handleError(_path);
}
}
bool FileImpl::createFileImpl()
{
poco_assert (!_path.empty());
HANDLE hFile = CreateFileW(_upath.c_str(), GENERIC_WRITE, 0, 0, CREATE_NEW, 0, 0);
if (hFile)
{
CloseHandle(hFile);
return true;
}
else if (GetLastError() == ERROR_ALREADY_EXISTS)
return false;
else
handleError(_path);
return false;
}
bool FileImpl::createDirectoryImpl()
{
poco_assert (!_path.empty());
if (existsImpl() && isDirectoryImpl())
return false;
if (CreateDirectoryW(_upath.c_str(), 0) == 0)
handleError(_path);
return true;
}
void FileImpl::handleError(const std::string& path)
{
switch (GetLastError())
{
case ERROR_FILE_NOT_FOUND:
throw FileNotFoundException(path);
case ERROR_PATH_NOT_FOUND:
case ERROR_BAD_NETPATH:
case ERROR_CANT_RESOLVE_FILENAME:
case ERROR_INVALID_DRIVE:
throw PathNotFoundException(path);
case ERROR_ACCESS_DENIED:
throw FileAccessDeniedException(path);
case ERROR_ALREADY_EXISTS:
case ERROR_FILE_EXISTS:
throw FileExistsException(path);
case ERROR_INVALID_NAME:
case ERROR_DIRECTORY:
case ERROR_FILENAME_EXCED_RANGE:
case ERROR_BAD_PATHNAME:
throw PathSyntaxException(path);
case ERROR_FILE_READ_ONLY:
throw FileReadOnlyException(path);
case ERROR_CANNOT_MAKE:
throw CreateFileException(path);
case ERROR_DIR_NOT_EMPTY:
throw FileException("directory not empty", path);
default:
throw FileException(path);
}
}
Foundation_END

View File

@@ -0,0 +1,66 @@
//
// Formatter.cpp
//
// $Id: //poco/1.1.0/Foundation/src/Formatter.cpp#2 $
//
// Library: Foundation
// Package: Logging
// Module: Formatter
//
// 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 "Foundation/Formatter.h"
#include "Foundation/Exception.h"
Foundation_BEGIN
Formatter::Formatter()
{
}
Formatter::~Formatter()
{
}
void Formatter::setProperty(const std::string& name, const std::string& value)
{
throw PropertyNotSupportedException();
}
std::string Formatter::getProperty(const std::string& name) const
{
throw PropertyNotSupportedException();
}
Foundation_END

View File

@@ -0,0 +1,148 @@
//
// FormattingChannel.cpp
//
// $Id: //poco/1.1.0/Foundation/src/FormattingChannel.cpp#2 $
//
// Library: Foundation
// Package: Logging
// Module: Formatter
//
// 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 "Foundation/FormattingChannel.h"
#include "Foundation/Formatter.h"
#include "Foundation/Message.h"
#include "Foundation/LoggingRegistry.h"
Foundation_BEGIN
FormattingChannel::FormattingChannel():
_pFormatter(0),
_pChannel(0)
{
}
FormattingChannel::FormattingChannel(Formatter* pFormatter):
_pFormatter(pFormatter),
_pChannel(0)
{
if (_pFormatter) _pFormatter->duplicate();
}
FormattingChannel::FormattingChannel(Formatter* pFormatter, Channel* pChannel):
_pFormatter(pFormatter),
_pChannel(pChannel)
{
if (_pFormatter) _pFormatter->duplicate();
if (_pChannel) _pChannel->duplicate();
}
FormattingChannel::~FormattingChannel()
{
if (_pChannel) _pChannel->release();
if (_pFormatter) _pFormatter->release();
}
void FormattingChannel::setFormatter(Formatter* pFormatter)
{
if (_pFormatter) _pFormatter->release();
_pFormatter = pFormatter;
if (_pFormatter) _pFormatter->duplicate();
}
Formatter* FormattingChannel::getFormatter() const
{
return _pFormatter;
}
void FormattingChannel::setChannel(Channel* pChannel)
{
if (_pChannel) _pChannel->release();
_pChannel = pChannel;
if (_pChannel) _pChannel->duplicate();
}
Channel* FormattingChannel::getChannel() const
{
return _pChannel;
}
void FormattingChannel::log(const Message& msg)
{
if (_pChannel)
{
if (_pFormatter)
{
std::string text;
_pFormatter->format(msg, text);
_pChannel->log(Message(msg, text));
}
else
{
_pChannel->log(msg);
}
}
};
void FormattingChannel::setProperty(const std::string& name, const std::string& value)
{
if (name == "channel")
setChannel(LoggingRegistry::defaultRegistry().channelForName(value));
else if (name == "formatter")
setFormatter(LoggingRegistry::defaultRegistry().formatterForName(value));
else
Channel::setProperty(name, value);
}
void FormattingChannel::open()
{
if (_pChannel)
_pChannel->open();
}
void FormattingChannel::close()
{
if (_pChannel)
_pChannel->close();
}
Foundation_END

242
Foundation/src/Glob.cpp Normal file
View File

@@ -0,0 +1,242 @@
//
// Glob.cpp
//
// $Id: //poco/1.1.0/Foundation/src/Glob.cpp#2 $
//
// Library: Foundation
// Package: Filesystem
// Module: Glob
//
// 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 "Foundation/Glob.h"
#include "Foundation/Path.h"
#include "Foundation/Exception.h"
#include "Foundation/DirectoryIterator.h"
#include "Foundation/File.h"
Foundation_BEGIN
Glob::Glob(const std::string& pattern, int options):
_pattern(pattern),
_options(options)
{
poco_assert (!_pattern.empty());
}
Glob::~Glob()
{
}
bool Glob::match(const std::string& subject)
{
std::string::const_iterator itp = _pattern.begin();
std::string::const_iterator endp = _pattern.end();
std::string::const_iterator its = subject.begin();
std::string::const_iterator ends = subject.end();
if ((_options & GLOB_DOT_SPECIAL) && its != ends && *its == '.' && (*itp == '?' || *itp == '*'))
return false;
else
return match(itp, endp, its, ends);
}
void Glob::glob(const std::string& pathPattern, std::set<std::string>& files, int options)
{
glob(Path(Path::expand(pathPattern), Path::PATH_GUESS), files, options);
}
void Glob::glob(const char* pathPattern, std::set<std::string>& files, int options)
{
glob(Path(Path::expand(pathPattern), Path::PATH_GUESS), files, options);
}
void Glob::glob(const Path& pathPattern, std::set<std::string>& files, int options)
{
Path pattern(pathPattern);
pattern.makeDirectory(); // to simplify pattern handling later on
Path base(pattern);
Path absBase(base);
absBase.makeAbsolute();
while (base.depth() > 0 && base[base.depth() - 1] != "..")
{
base.popDirectory();
absBase.popDirectory();
}
if (pathPattern.isDirectory()) options |= GLOB_DIRS_ONLY;
collect(pattern, absBase, base, pathPattern[base.depth()], files, options);
}
bool Glob::match(std::string::const_iterator& itp, const std::string::const_iterator& endp, std::string::const_iterator& its, const std::string::const_iterator& ends)
{
while (itp != endp)
{
if (its == ends)
{
while (itp != endp && *itp == '*') ++itp;
break;
}
switch (*itp)
{
case '?':
++itp; ++its;
break;
case '*':
if (++itp != endp)
{
while (its != ends && !matchAfterAsterisk(itp, endp, its, ends)) ++its;
return its != ends;
}
return true;
case '[':
if (++itp != endp)
{
bool invert = *itp == '!';
if (invert) ++itp;
if (itp != endp)
{
bool mtch = matchSet(itp, endp, *its++);
if (invert && mtch || !invert && !mtch) return false;
break;
}
}
throw SyntaxException("bad range syntax in glob pattern");
case '\\':
if (++itp == endp) throw SyntaxException("backslash must be followed by character in glob pattern");
// fallthrough
default:
if (*itp != *its) return false;
++itp; ++its;
}
}
return itp == endp && its == ends;
}
bool Glob::matchAfterAsterisk(std::string::const_iterator itp, const std::string::const_iterator& endp, std::string::const_iterator its, const std::string::const_iterator& ends)
{
return match(itp, endp, its, ends);
}
bool Glob::matchSet(std::string::const_iterator& itp, const std::string::const_iterator& endp, char c)
{
while (itp != endp)
{
switch (*itp)
{
case ']':
++itp;
return false;
case '\\':
if (++itp == endp) throw SyntaxException("backslash must be followed by character in glob pattern");
}
char first = *itp;
char last = first;
if (++itp != endp && *itp == '-')
{
if (++itp != endp)
last = *itp++;
else
throw SyntaxException("bad range syntax in glob pattern");
}
if (first <= c && c <= last)
{
while (itp != endp)
{
switch (*itp)
{
case ']':
++itp;
return true;
case '\\':
if (++itp == endp) break;
default:
++itp;
}
}
throw SyntaxException("range must be terminated by closing bracket in glob pattern");
}
}
return false;
}
void Glob::collect(const Path& pathPattern, const Path& base, const Path& current, const std::string& pattern, std::set<std::string>& files, int options)
{
try
{
std::string pp = pathPattern.toString();
std::string basep = base.toString();
std::string curp = current.toString();
Glob g(pattern, options);
DirectoryIterator it(base);
DirectoryIterator end;
while (it != end)
{
const std::string& name = it.name();
if (g.match(name))
{
Path p(current);
if (p.depth() < pathPattern.depth() - 1)
{
p.pushDirectory(name);
collect(pathPattern, it.path(), p, pathPattern[p.depth()], files, options);
}
else
{
p.setFileName(name);
if (File(p).isDirectory())
{
p.makeDirectory();
files.insert(p.toString());
}
else if (!(options & GLOB_DIRS_ONLY))
{
files.insert(p.toString());
}
}
}
++it;
}
}
catch (Exception&)
{
}
}
Foundation_END

View File

@@ -0,0 +1,115 @@
//
// HexBinaryDecoder.cpp
//
// $Id: //poco/1.1.0/Foundation/src/HexBinaryDecoder.cpp#2 $
//
// Library: Foundation
// Package: Streams
// Module: HexBinary
//
// 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 "Foundation/HexBinaryDecoder.h"
#include "Foundation/Exception.h"
Foundation_BEGIN
HexBinaryDecoderBuf::HexBinaryDecoderBuf(std::istream& istr): _istr(istr)
{
}
HexBinaryDecoderBuf::~HexBinaryDecoderBuf()
{
}
int HexBinaryDecoderBuf::readFromDevice()
{
int c;
int n;
if ((n = readOne()) == -1) return -1;
if (n >= '0' && n <= '9')
c = n - '0';
else if (n >= 'A' && n <= 'F')
c = n - 'A' + 10;
else if (n >= 'a' && n <= 'f')
c = n - 'a' + 10;
else throw DataFormatException();
c <<= 4;
if ((n = readOne()) == -1) return -1;
if (n >= '0' && n <= '9')
c |= n - '0';
else if (n >= 'A' && n <= 'F')
c |= n - 'A' + 10;
else if (n >= 'a' && n <= 'f')
c |= n - 'a' + 10;
else throw DataFormatException();
return c;
}
int HexBinaryDecoderBuf::readOne()
{
int ch = _istr.get();
while (ch == ' ' || ch == '\r' || ch == '\t' || ch == '\n')
ch = _istr.get();
return ch;
}
HexBinaryDecoderIOS::HexBinaryDecoderIOS(std::istream& istr): _buf(istr)
{
poco_ios_init(&_buf);
}
HexBinaryDecoderIOS::~HexBinaryDecoderIOS()
{
}
HexBinaryDecoderBuf* HexBinaryDecoderIOS::rdbuf()
{
return &_buf;
}
HexBinaryDecoder::HexBinaryDecoder(std::istream& istr): HexBinaryDecoderIOS(istr), std::istream(&_buf)
{
}
HexBinaryDecoder::~HexBinaryDecoder()
{
}
Foundation_END

View File

@@ -0,0 +1,140 @@
//
// HexBinaryEncoder.cpp
//
// $Id: //poco/1.1.0/Foundation/src/HexBinaryEncoder.cpp#2 $
//
// Library: Foundation
// Package: Streams
// Module: HexBinary
//
// 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 "Foundation/HexBinaryEncoder.h"
Foundation_BEGIN
HexBinaryEncoderBuf::HexBinaryEncoderBuf(std::ostream& ostr):
_pos(0),
_lineLength(72),
_uppercase(0),
_ostr(ostr)
{
}
HexBinaryEncoderBuf::~HexBinaryEncoderBuf()
{
try
{
close();
}
catch (...)
{
}
}
void HexBinaryEncoderBuf::setLineLength(int lineLength)
{
poco_assert (lineLength > 0);
_lineLength = lineLength;
}
int HexBinaryEncoderBuf::getLineLength() const
{
return _lineLength;
}
void HexBinaryEncoderBuf::setUppercase(bool flag)
{
_uppercase = flag ? 16 : 0;
}
int HexBinaryEncoderBuf::writeToDevice(char c)
{
static const char digits[] = "0123456789abcdef0123456789ABCDEF";
_ostr.put(digits[_uppercase + ((c >> 4) & 0xF)]);
++_pos;
_ostr.put(digits[_uppercase + (c & 0xF)]);
if (++_pos >= _lineLength)
{
_ostr << std::endl;
_pos = 0;
}
return _ostr ? charToInt(c) : -1;
}
int HexBinaryEncoderBuf::close()
{
sync();
_ostr.flush();
return _ostr ? 0 : -1;
}
HexBinaryEncoderIOS::HexBinaryEncoderIOS(std::ostream& ostr): _buf(ostr)
{
poco_ios_init(&_buf);
}
HexBinaryEncoderIOS::~HexBinaryEncoderIOS()
{
}
int HexBinaryEncoderIOS::close()
{
return _buf.close();
}
HexBinaryEncoderBuf* HexBinaryEncoderIOS::rdbuf()
{
return &_buf;
}
HexBinaryEncoder::HexBinaryEncoder(std::ostream& ostr): HexBinaryEncoderIOS(ostr), std::ostream(&_buf)
{
}
HexBinaryEncoder::~HexBinaryEncoder()
{
}
Foundation_END

View File

@@ -0,0 +1,258 @@
//
// InflatingStream.cpp
//
// $Id: //poco/1.1.0/Foundation/src/InflatingStream.cpp#2 $
//
// Library: Foundation
// Package: Streams
// Module: ZLibStream
//
// 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 "Foundation/InflatingStream.h"
#include "Foundation/Exception.h"
Foundation_BEGIN
InflatingStreamBuf::InflatingStreamBuf(std::istream& istr, StreamType type):
BufferedStreamBuf(STREAM_BUFFER_SIZE, std::ios::in),
_pIstr(&istr),
_pOstr(0),
_eof(false)
{
_zstr.zalloc = Z_NULL;
_zstr.zfree = Z_NULL;
_zstr.opaque = Z_NULL;
_zstr.next_in = 0;
_zstr.avail_in = 0;
_zstr.next_out = 0;
_zstr.avail_out = 0;
int rc = inflateInit2(&_zstr, 15 + (type == STREAM_GZIP ? 16 : 0));
if (rc != Z_OK) throw IOException(zError(rc));
_buffer = new char[INFLATE_BUFFER_SIZE];
}
InflatingStreamBuf::InflatingStreamBuf(std::ostream& ostr, StreamType type):
BufferedStreamBuf(STREAM_BUFFER_SIZE, std::ios::out),
_pIstr(0),
_pOstr(&ostr),
_eof(false)
{
_zstr.zalloc = Z_NULL;
_zstr.zfree = Z_NULL;
_zstr.opaque = Z_NULL;
_zstr.next_in = 0;
_zstr.avail_in = 0;
_zstr.next_out = 0;
_zstr.avail_out = 0;
int rc = inflateInit2(&_zstr, 15 + (type == STREAM_GZIP ? 16 : 0));
if (rc != Z_OK) throw IOException(zError(rc));
_buffer = new char[INFLATE_BUFFER_SIZE];
}
InflatingStreamBuf::~InflatingStreamBuf()
{
try
{
close();
}
catch (...)
{
}
delete [] _buffer;
}
int InflatingStreamBuf::close()
{
sync();
if (_pIstr || _pOstr)
{
int rc = inflateEnd(&_zstr);
if (rc != Z_OK) throw IOException(zError(rc));
_pIstr = 0;
_pOstr = 0;
}
return 0;
}
int InflatingStreamBuf::readFromDevice(char* buffer, std::streamsize length)
{
if (_eof || !_pIstr) return 0;
if (!_zstr.next_in)
{
int n = 0;
if (_pIstr->good())
{
_pIstr->read(_buffer, INFLATE_BUFFER_SIZE);
n = _pIstr->gcount();
}
if (n == 0) return 0;
_zstr.next_in = (unsigned char*) _buffer;
_zstr.avail_in = n;
_zstr.next_out = (unsigned char*) buffer;
_zstr.avail_out = length;
}
else if (_zstr.avail_out == 0)
{
_zstr.next_out = (unsigned char*) buffer;
_zstr.avail_out = length;
}
for (;;)
{
int rc = inflate(&_zstr, Z_NO_FLUSH);
if (rc == Z_STREAM_END)
{
_eof = true;
return length - _zstr.avail_out;
}
if (rc != Z_OK) throw IOException(zError(rc));
if (_zstr.avail_out == 0)
return length;
if (_zstr.avail_in == 0)
{
int n = 0;
if (_pIstr->good())
{
_pIstr->read(_buffer, INFLATE_BUFFER_SIZE);
n = _pIstr->gcount();
}
if (n > 0)
{
_zstr.next_in = (unsigned char*) _buffer;
_zstr.avail_in = n;
}
}
}
}
int InflatingStreamBuf::writeToDevice(const char* buffer, std::streamsize length)
{
if (length == 0 || !_pOstr) return 0;
_zstr.next_in = (unsigned char*) buffer;
_zstr.avail_in = length;
_zstr.next_out = (unsigned char*) _buffer;
_zstr.avail_out = INFLATE_BUFFER_SIZE;
for (;;)
{
int rc = inflate(&_zstr, Z_NO_FLUSH);
if (rc == Z_STREAM_END)
{
_pOstr->write(_buffer, INFLATE_BUFFER_SIZE - _zstr.avail_out);
if (!_pOstr->good()) throw IOException(zError(rc));
break;
}
if (rc != Z_OK) throw IOException(zError(rc));
if (_zstr.avail_out == 0)
{
_pOstr->write(_buffer, INFLATE_BUFFER_SIZE);
if (!_pOstr->good()) throw IOException(zError(rc));
_zstr.next_out = (unsigned char*) _buffer;
_zstr.avail_out = INFLATE_BUFFER_SIZE;
}
if (_zstr.avail_in == 0)
{
_pOstr->write(_buffer, INFLATE_BUFFER_SIZE - _zstr.avail_out);
if (!_pOstr->good()) throw IOException(zError(rc));
_zstr.next_out = (unsigned char*) _buffer;
_zstr.avail_out = INFLATE_BUFFER_SIZE;
break;
}
}
return length;
}
InflatingIOS::InflatingIOS(std::ostream& ostr, InflatingStreamBuf::StreamType type):
_buf(ostr, type)
{
poco_ios_init(&_buf);
}
InflatingIOS::InflatingIOS(std::istream& istr, InflatingStreamBuf::StreamType type):
_buf(istr, type)
{
poco_ios_init(&_buf);
}
InflatingIOS::~InflatingIOS()
{
}
InflatingStreamBuf* InflatingIOS::rdbuf()
{
return &_buf;
}
InflatingOutputStream::InflatingOutputStream(std::ostream& ostr, InflatingStreamBuf::StreamType type):
InflatingIOS(ostr, type),
std::ostream(&_buf)
{
}
InflatingOutputStream::~InflatingOutputStream()
{
}
int InflatingOutputStream::close()
{
return _buf.close();
}
InflatingInputStream::InflatingInputStream(std::istream& istr, InflatingStreamBuf::StreamType type):
InflatingIOS(istr, type),
std::istream(&_buf)
{
}
InflatingInputStream::~InflatingInputStream()
{
}
Foundation_END

View File

@@ -0,0 +1,97 @@
//
// Latin1Encoding.cpp
//
// $Id: //poco/1.1.0/Foundation/src/Latin1Encoding.cpp#2 $
//
// Library: Foundation
// Package: Text
// Module: Latin1Encoding
//
// 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 "Foundation/Latin1Encoding.h"
Foundation_BEGIN
const TextEncoding::CharacterMap Latin1Encoding::_charMap =
{
/* 00 */ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
/* 10 */ 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
/* 20 */ 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f,
/* 30 */ 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f,
/* 40 */ 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f,
/* 50 */ 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f,
/* 60 */ 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f,
/* 70 */ 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f,
/* 80 */ 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f,
/* 90 */ 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f,
/* a0 */ 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf,
/* b0 */ 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf,
/* c0 */ 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf,
/* d0 */ 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf,
/* e0 */ 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef,
/* f0 */ 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff,
};
Latin1Encoding::Latin1Encoding()
{
}
Latin1Encoding::~Latin1Encoding()
{
}
const TextEncoding::CharacterMap& Latin1Encoding::characterMap() const
{
return _charMap;
}
int Latin1Encoding::convert(const unsigned char* bytes) const
{
return *bytes;
}
int Latin1Encoding::convert(int ch, unsigned char* bytes, int length) const
{
if (ch >= 0 && ch <= 255)
{
*bytes = (unsigned char) ch;
return 1;
}
else return 0;
}
Foundation_END

View File

@@ -0,0 +1,108 @@
//
// Latin9Encoding.cpp
//
// $Id: //poco/1.1.0/Foundation/src/Latin9Encoding.cpp#2 $
//
// Library: Foundation
// Package: Text
// Module: Latin9Encoding
//
// 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 "Foundation/Latin9Encoding.h"
Foundation_BEGIN
const TextEncoding::CharacterMap Latin9Encoding::_charMap =
{
/* 00 */ 0x0000, 0x0001, 0x0002, 0x0003, 0x0004, 0x0005, 0x0006, 0x0007, 0x0008, 0x0009, 0x000a, 0x000b, 0x000c, 0x000d, 0x000e, 0x000f,
/* 10 */ 0x0010, 0x0011, 0x0012, 0x0013, 0x0014, 0x0015, 0x0016, 0x0017, 0x0018, 0x0019, 0x001a, 0x001b, 0x001c, 0x001d, 0x001e, 0x001f,
/* 20 */ 0x0020, 0x0021, 0x0022, 0x0023, 0x0024, 0x0025, 0x0026, 0x0027, 0x0028, 0x0029, 0x002a, 0x002b, 0x002c, 0x002d, 0x002e, 0x002f,
/* 30 */ 0x0030, 0x0031, 0x0032, 0x0033, 0x0034, 0x0035, 0x0036, 0x0037, 0x0038, 0x0039, 0x003a, 0x003b, 0x003c, 0x003d, 0x003e, 0x003f,
/* 40 */ 0x0040, 0x0041, 0x0042, 0x0043, 0x0044, 0x0045, 0x0046, 0x0047, 0x0048, 0x0049, 0x004a, 0x004b, 0x004c, 0x004d, 0x004e, 0x004f,
/* 50 */ 0x0050, 0x0051, 0x0052, 0x0053, 0x0054, 0x0055, 0x0056, 0x0057, 0x0058, 0x0059, 0x005a, 0x005b, 0x005c, 0x005d, 0x005e, 0x005f,
/* 60 */ 0x0060, 0x0061, 0x0062, 0x0063, 0x0064, 0x0065, 0x0066, 0x0067, 0x0068, 0x0069, 0x006a, 0x006b, 0x006c, 0x006d, 0x006e, 0x006f,
/* 70 */ 0x0070, 0x0071, 0x0072, 0x0073, 0x0074, 0x0075, 0x0076, 0x0077, 0x0078, 0x0079, 0x007a, 0x007b, 0x007c, 0x007d, 0x007e, 0x007f,
/* 80 */ 0x0080, 0x0081, 0x0082, 0x0083, 0x0084, 0x0085, 0x0086, 0x0087, 0x0088, 0x0089, 0x008a, 0x008b, 0x008c, 0x008d, 0x008e, 0x008f,
/* 90 */ 0x0090, 0x0091, 0x0092, 0x0093, 0x0094, 0x0095, 0x0096, 0x0097, 0x0098, 0x0099, 0x009a, 0x009b, 0x009c, 0x009d, 0x009e, 0x009f,
/* a0 */ 0x00a0, 0x00a1, 0x00a2, 0x00a3, 0x20ac, 0x00a5, 0x0160, 0x00a7, 0x0161, 0x00a9, 0x00aa, 0x00ab, 0x00ac, 0x00ad, 0x00ae, 0x00af,
/* b0 */ 0x00b0, 0x00b1, 0x00b2, 0x00b3, 0x017d, 0x00b5, 0x00b6, 0x00b7, 0x017e, 0x00b9, 0x00ba, 0x00bb, 0x0152, 0x0153, 0x0178, 0x00bf,
/* c0 */ 0x00c0, 0x00c1, 0x00c2, 0x00c3, 0x00c4, 0x00c5, 0x00c6, 0x00c7, 0x00c8, 0x00c9, 0x00ca, 0x00cb, 0x00cc, 0x00cd, 0x00ce, 0x00cf,
/* d0 */ 0x00d0, 0x00d1, 0x00d2, 0x00d3, 0x00d4, 0x00d5, 0x00d6, 0x00d7, 0x00d8, 0x00d9, 0x00da, 0x00db, 0x00dc, 0x00dd, 0x00de, 0x00df,
/* e0 */ 0x00e0, 0x00e1, 0x00e2, 0x00e3, 0x00e4, 0x00e5, 0x00e6, 0x00e7, 0x00e8, 0x00e9, 0x00ea, 0x00eb, 0x00ec, 0x00ed, 0x00ee, 0x00ef,
/* f0 */ 0x00f0, 0x00f1, 0x00f2, 0x00f3, 0x00f4, 0x00f5, 0x00f6, 0x00f7, 0x00f8, 0x00f9, 0x00fa, 0x00fb, 0x00fc, 0x00fd, 0x00fe, 0x00ff,
};
Latin9Encoding::Latin9Encoding()
{
}
Latin9Encoding::~Latin9Encoding()
{
}
const TextEncoding::CharacterMap& Latin9Encoding::characterMap() const
{
return _charMap;
}
int Latin9Encoding::convert(const unsigned char* bytes) const
{
return *bytes;
}
int Latin9Encoding::convert(int ch, unsigned char* bytes, int length) const
{
if (ch >= 0 && ch <= 255)
{
*bytes = ch;
return 1;
}
else switch (ch)
{
case 0x0152: *bytes = 0xbc; return 1;
case 0x0153: *bytes = 0xbd; return 1;
case 0x0160: *bytes = 0xa6; return 1;
case 0x0161: *bytes = 0xa8; return 1;
case 0x017d: *bytes = 0xb4; return 1;
case 0x017e: *bytes = 0xb8; return 1;
case 0x0178: *bytes = 0xbe; return 1;
case 0x20ac: *bytes = 0xa4; return 1;
default: return 0;
}
}
Foundation_END

View File

@@ -0,0 +1,204 @@
//
// LineEndingConverter.cpp
//
// $Id: //poco/1.1.0/Foundation/src/LineEndingConverter.cpp#2 $
//
// Library: Foundation
// Package: Streams
// Module: LineEndingConverter
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Foundation/LineEndingConverter.h"
Foundation_BEGIN
#if defined(_WIN32)
#define POCO_DEFAULT_NEWLINE_CHARS "\r\n"
#else
#define POCO_DEFAULT_NEWLINE_CHARS "\n"
#endif
const std::string LineEnding::NEWLINE_DEFAULT(POCO_DEFAULT_NEWLINE_CHARS);
const std::string LineEnding::NEWLINE_CR("\r");
const std::string LineEnding::NEWLINE_CRLF("\r\n");
const std::string LineEnding::NEWLINE_LF("\n");
LineEndingConverterStreamBuf::LineEndingConverterStreamBuf(std::istream& istr):
_pIstr(&istr),
_pOstr(0),
_newLine(LineEnding::NEWLINE_DEFAULT),
_lastChar(0)
{
_it = _newLine.end();
}
LineEndingConverterStreamBuf::LineEndingConverterStreamBuf(std::ostream& ostr):
_pIstr(0),
_pOstr(&ostr),
_newLine(LineEnding::NEWLINE_DEFAULT),
_lastChar(0)
{
_it = _newLine.end();
}
LineEndingConverterStreamBuf::~LineEndingConverterStreamBuf()
{
}
void LineEndingConverterStreamBuf::setNewLine(const std::string& newLineCharacters)
{
_newLine = newLineCharacters;
_it = _newLine.end();
}
const std::string& LineEndingConverterStreamBuf::getNewLine() const
{
return _newLine;
}
int LineEndingConverterStreamBuf::readFromDevice()
{
poco_assert_dbg (_pIstr);
while (_it == _newLine.end())
{
int c = _pIstr->get();
if (c == '\r')
{
if (_pIstr->peek() == '\n') _pIstr->get();
_it = _newLine.begin();
}
else if (c == '\n')
{
_it = _newLine.begin();
}
else return c;
}
return *_it++;
}
int LineEndingConverterStreamBuf::writeToDevice(char c)
{
poco_assert_dbg (_pOstr);
if (c == '\r' || c == '\n' && _lastChar != '\r')
_pOstr->write(_newLine.data(), (std::streamsize) _newLine.length());
if (c != '\n' && c != '\r')
_pOstr->put(c);
_lastChar = c;
return charToInt(c);
}
LineEndingConverterIOS::LineEndingConverterIOS(std::istream& istr): _buf(istr)
{
poco_ios_init(&_buf);
}
LineEndingConverterIOS::LineEndingConverterIOS(std::ostream& ostr): _buf(ostr)
{
poco_ios_init(&_buf);
}
LineEndingConverterIOS::~LineEndingConverterIOS()
{
}
void LineEndingConverterIOS::setNewLine(const std::string& newLineCharacters)
{
_buf.setNewLine(newLineCharacters);
}
const std::string& LineEndingConverterIOS::getNewLine() const
{
return _buf.getNewLine();
}
LineEndingConverterStreamBuf* LineEndingConverterIOS::rdbuf()
{
return &_buf;
}
InputLineEndingConverter::InputLineEndingConverter(std::istream& istr):
LineEndingConverterIOS(istr),
std::istream(&_buf)
{
}
InputLineEndingConverter::InputLineEndingConverter(std::istream& istr, const std::string& newLineCharacters):
LineEndingConverterIOS(istr),
std::istream(&_buf)
{
setNewLine(newLineCharacters);
}
InputLineEndingConverter::~InputLineEndingConverter()
{
}
OutputLineEndingConverter::OutputLineEndingConverter(std::ostream& ostr):
LineEndingConverterIOS(ostr),
std::ostream(&_buf)
{
}
OutputLineEndingConverter::OutputLineEndingConverter(std::ostream& ostr, const std::string& newLineCharacters):
LineEndingConverterIOS(ostr),
std::ostream(&_buf)
{
setNewLine(newLineCharacters);
}
OutputLineEndingConverter::~OutputLineEndingConverter()
{
}
Foundation_END

View File

@@ -0,0 +1,255 @@
//
// LocalDateTime.cpp
//
// $Id: //poco/1.1.0/Foundation/src/LocalDateTime.cpp#2 $
//
// Library: Foundation
// Package: DateTime
// Module: LocalDateTime
//
// 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 "Foundation/LocalDateTime.h"
#include "Foundation/Timezone.h"
#include "Foundation/Timespan.h"
#include <algorithm>
Foundation_BEGIN
LocalDateTime::LocalDateTime():
_tzd(Timezone::tzd())
{
_dateTime += Timespan(((Timestamp::TimeDiff) _tzd)*Timespan::SECONDS);
}
LocalDateTime::LocalDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int microsecond):
_dateTime(year, month, day, hour, minute, second, millisecond, microsecond),
_tzd(Timezone::tzd())
{
}
LocalDateTime::LocalDateTime(int tzd, int year, int month, int day, int hour, int minute, int second, int millisecond, int microsecond):
_dateTime(year, month, day, hour, minute, second, millisecond, microsecond),
_tzd(tzd)
{
}
LocalDateTime::LocalDateTime(double julianDay):
_dateTime(julianDay),
_tzd(Timezone::tzd())
{
_dateTime += Timespan(((Timestamp::TimeDiff) _tzd)*Timespan::SECONDS);
}
LocalDateTime::LocalDateTime(int tzd, double julianDay):
_dateTime(julianDay),
_tzd(tzd)
{
_dateTime += Timespan(((Timestamp::TimeDiff) _tzd)*Timespan::SECONDS);
}
LocalDateTime::LocalDateTime(const DateTime& dateTime):
_dateTime(dateTime),
_tzd(Timezone::tzd())
{
_dateTime += Timespan(((Timestamp::TimeDiff) _tzd)*Timespan::SECONDS);
}
LocalDateTime::LocalDateTime(int tzd, const DateTime& dateTime):
_dateTime(dateTime),
_tzd(tzd)
{
_dateTime += Timespan(((Timestamp::TimeDiff) _tzd)*Timespan::SECONDS);
}
LocalDateTime::LocalDateTime(const LocalDateTime& dateTime):
_dateTime(dateTime._dateTime),
_tzd(dateTime._tzd)
{
}
LocalDateTime::LocalDateTime(Timestamp::UtcTimeVal utcTime, Timestamp::TimeDiff diff, int tzd):
_dateTime(utcTime, diff),
_tzd(tzd)
{
}
LocalDateTime::~LocalDateTime()
{
}
LocalDateTime& LocalDateTime::operator = (const LocalDateTime& dateTime)
{
if (&dateTime != this)
{
_dateTime = dateTime._dateTime;
_tzd = dateTime._tzd;
}
return *this;
}
LocalDateTime& LocalDateTime::operator = (const Timestamp& timestamp)
{
if (timestamp != this->timestamp())
_dateTime = timestamp;
return *this;
}
LocalDateTime& LocalDateTime::operator = (double julianDay)
{
_tzd = Timezone::tzd();
_dateTime = julianDay;
_dateTime += Timespan(((Timestamp::TimeDiff) _tzd)*Timespan::SECONDS);
return *this;
}
LocalDateTime& LocalDateTime::assign(int year, int month, int day, int hour, int minute, int second, int millisecond, int microseconds)
{
_dateTime.assign(year, month, day, hour, minute, second, millisecond, microseconds);
_tzd = Timezone::tzd();
return *this;
}
LocalDateTime& LocalDateTime::assign(int tzd, int year, int month, int day, int hour, int minute, int second, int millisecond, int microseconds)
{
_dateTime.assign(year, month, day, hour, minute, second, millisecond, microseconds);
_tzd = tzd;
return *this;
}
LocalDateTime& LocalDateTime::assign(int tzd, double julianDay)
{
_tzd = tzd;
_dateTime = julianDay;
_dateTime += Timespan(((Timestamp::TimeDiff) _tzd)*Timespan::SECONDS);
return *this;
}
void LocalDateTime::swap(LocalDateTime& dateTime)
{
_dateTime.swap(dateTime._dateTime);
std::swap(_tzd, dateTime._tzd);
}
DateTime LocalDateTime::utc() const
{
return DateTime(_dateTime.utcTime(), -((Timestamp::TimeDiff) _tzd)*Timespan::SECONDS);
}
bool LocalDateTime::operator == (const LocalDateTime& dateTime) const
{
Timestamp::UtcTimeVal t1 = utcTime();
Timestamp::UtcTimeVal t2 = dateTime.utcTime();
return utcTime() == dateTime.utcTime();
}
bool LocalDateTime::operator != (const LocalDateTime& dateTime) const
{
return utcTime() != dateTime.utcTime();
}
bool LocalDateTime::operator < (const LocalDateTime& dateTime) const
{
return utcTime() < dateTime.utcTime();
}
bool LocalDateTime::operator <= (const LocalDateTime& dateTime) const
{
return utcTime() <= dateTime.utcTime();
}
bool LocalDateTime::operator > (const LocalDateTime& dateTime) const
{
return utcTime() > dateTime.utcTime();
}
bool LocalDateTime::operator >= (const LocalDateTime& dateTime) const
{
return utcTime() >= dateTime.utcTime();
}
LocalDateTime LocalDateTime::operator + (const Timespan& span) const
{
return LocalDateTime(_dateTime.utcTime(), span.totalMicroseconds(), _tzd);
}
LocalDateTime LocalDateTime::operator - (const Timespan& span) const
{
return LocalDateTime(_dateTime.utcTime(), -span.totalMicroseconds(), _tzd);
}
Timespan LocalDateTime::operator - (const LocalDateTime& dateTime) const
{
return Timespan((utcTime() - dateTime.utcTime())/10);
}
LocalDateTime& LocalDateTime::operator += (const Timespan& span)
{
_dateTime += span;
return *this;
}
LocalDateTime& LocalDateTime::operator -= (const Timespan& span)
{
_dateTime -= span;
return *this;
}
Foundation_END

View File

@@ -0,0 +1,62 @@
//
// LogFile.cpp
//
// $Id: //poco/1.1.0/Foundation/src/LogFile.cpp#2 $
//
// Library: Foundation
// Package: Logging
// Module: LogFile
//
// 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 "Foundation/LogFile.h"
#if defined(POCO_OS_FAMILY_WINDOWS)
#include "LogFile_WIN32.cpp"
#elif defined(POCO_OS_FAMILY_VMS)
#include "LogFile_VMS.cpp"
#else
#include "LogFile_STD.cpp"
#endif
Foundation_BEGIN
LogFile::LogFile(const std::string& path): LogFileImpl(path)
{
}
LogFile::~LogFile()
{
}
Foundation_END

View File

@@ -0,0 +1,86 @@
//
// LogFile_STD.cpp
//
// $Id: //poco/1.1.0/Foundation/src/LogFile_STD.cpp#2 $
//
// Library: Foundation
// Package: Logging
// Module: LogFile
//
// 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 "Foundation/LogFile_STD.h"
#include "Foundation/File.h"
#include "Foundation/Exception.h"
Foundation_BEGIN
LogFileImpl::LogFileImpl(const std::string& path): _path(path)
{
_str.open(path.c_str(), std::ios::ate);
if (!_str.good()) throw OpenFileException(path);
if (sizeImpl() == 0)
_creationDate = File(path).getLastModified();
else
_creationDate = File(path).created();
}
LogFileImpl::~LogFileImpl()
{
}
void LogFileImpl::writeImpl(const std::string& text)
{
_str << text << std::endl;
if (!_str.good()) throw WriteFileException(_path);
}
UInt64 LogFileImpl::sizeImpl() const
{
return (UInt64) _str.tellp();
}
Timestamp LogFileImpl::creationDateImpl() const
{
return _creationDate;
}
const std::string& LogFileImpl::pathImpl() const
{
return _path;
}
Foundation_END

View File

@@ -0,0 +1,91 @@
//
// LogFile_VMS.cpp
//
// $Id: //poco/1.1.0/Foundation/src/LogFile_VMS.cpp#2 $
//
// Library: Foundation
// Package: Logging
// Module: LogFile
//
// 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 "Foundation/LogFile_VMS.h"
#include "Foundation/File.h"
#include "Foundation/Exception.h"
Foundation_BEGIN
LogFileImpl::LogFileImpl(const std::string& path): _path(path)
{
_file = fopen(path.c_str(), "a", "ctx=rec,bin", "shr=get", "fop=dfw", "alq=500", "deq=500");
if (!_file) throw OpenFileException(path);
if (size() == 0)
_creationDate = File(path).getLastModified();
else
_creationDate = File(path).created();
}
LogFileImpl::~LogFileImpl()
{
fclose(_file);
}
void LogFileImpl::writeImpl(const std::string& text)
{
int rc = fputs(text.c_str(), _file);
if (rc == EOF) throw WriteFileException(_path);
rc = fputc('\n', _file);
if (rc == EOF) throw WriteFileException(_path);
rc = fflush(_file);
if (rc == EOF) throw WriteFileException(_path);
}
UInt64 LogFileImpl::sizeImpl() const
{
return (UInt64) ftell(_file);
}
Timestamp LogFileImpl::creationDateImpl() const
{
return _creationDate;
}
const std::string& LogFileImpl::pathImpl() const
{
return _path;
}
Foundation_END

View File

@@ -0,0 +1,109 @@
//
// LogFile_WIN32.cpp
//
// $Id: //poco/1.1.0/Foundation/src/LogFile_WIN32.cpp#2 $
//
// Library: Foundation
// Package: Logging
// Module: LogFile
//
// 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 "Foundation/LogFile_WIN32.h"
#include "Foundation/File.h"
#include "Foundation/Exception.h"
Foundation_BEGIN
LogFileImpl::LogFileImpl(const std::string& path): _path(path)
{
_hFile = CreateFile(path.c_str(), GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (_hFile == INVALID_HANDLE_VALUE) throw OpenFileException(path);
SetFilePointer(_hFile, 0, 0, FILE_END);
// There seems to be a strange "optimization" in the Windows NTFS
// filesystem that causes it to reuse directory entries of deleted
// files. Example:
// 1. create a file named "test.dat"
// note the file's creation date
// 2. delete the file "test.dat"
// 3. wait a few seconds
// 4. create a file named "test.dat"
// the new file will have the same creation
// date as the old one.
// We work around this bug by taking the file's
// modification date as a reference when the
// file is empty.
if (sizeImpl() == 0)
_creationDate = File(path).getLastModified();
else
_creationDate = File(path).created();
}
LogFileImpl::~LogFileImpl()
{
CloseHandle(_hFile);
}
void LogFileImpl::writeImpl(const std::string& text)
{
DWORD bytesWritten;
BOOL res = WriteFile(_hFile, text.data(), (DWORD) text.size(), &bytesWritten, NULL);
if (!res) throw WriteFileException(_path);
res = WriteFile(_hFile, "\r\n", 2, &bytesWritten, NULL);
if (!res) throw WriteFileException(_path);
res = FlushFileBuffers(_hFile);
if (!res) throw WriteFileException(_path);
}
UInt64 LogFileImpl::sizeImpl() const
{
LARGE_INTEGER li;
li.HighPart = 0;
li.LowPart = SetFilePointer(_hFile, 0, &li.HighPart, FILE_CURRENT);
return li.QuadPart;
}
Timestamp LogFileImpl::creationDateImpl() const
{
return _creationDate;
}
const std::string& LogFileImpl::pathImpl() const
{
return _path;
}
Foundation_END

416
Foundation/src/Logger.cpp Normal file
View File

@@ -0,0 +1,416 @@
//
// Logger.cpp
//
// $Id: //poco/1.1.0/Foundation/src/Logger.cpp#2 $
//
// Library: Foundation
// Package: Logging
// Module: Logger
//
// 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 "Foundation/Logger.h"
#include "Foundation/Formatter.h"
#include "Foundation/LoggingRegistry.h"
#include "Foundation/Exception.h"
#include "Foundation/NumberFormatter.h"
Foundation_BEGIN
Logger::LoggerMap* Logger::_pLoggerMap = 0;
Mutex Logger::_mapMtx;
Logger::Logger(const std::string& name, Channel* pChannel, int level): _name(name), _pChannel(pChannel), _level(level)
{
if (pChannel) pChannel->duplicate();
}
Logger::~Logger()
{
if (_pChannel) _pChannel->release();
}
void Logger::setChannel(Channel* pChannel)
{
if (_pChannel) _pChannel->release();
_pChannel = pChannel;
if (_pChannel) _pChannel->duplicate();
}
Channel* Logger::getChannel() const
{
return _pChannel;
}
void Logger::setLevel(int level)
{
_level = level;
}
void Logger::setLevel(const std::string& level)
{
if (level == "fatal")
setLevel(Message::PRIO_FATAL);
else if (level == "critical")
setLevel(Message::PRIO_CRITICAL);
else if (level == "error")
setLevel(Message::PRIO_ERROR);
else if (level == "warning")
setLevel(Message::PRIO_WARNING);
else if (level == "notice")
setLevel(Message::PRIO_NOTICE);
else if (level == "information")
setLevel(Message::PRIO_INFORMATION);
else if (level == "debug")
setLevel(Message::PRIO_DEBUG);
else if (level == "trace")
setLevel(Message::PRIO_TRACE);
else
throw InvalidArgumentException("Not a valid log level", level);
}
void Logger::setProperty(const std::string& name, const std::string& value)
{
if (name == "channel")
setChannel(LoggingRegistry::defaultRegistry().channelForName(value));
else if (name == "level")
setLevel(value);
else
Channel::setProperty(name, value);
}
void Logger::log(const Message& msg)
{
if (_level >= msg.getPriority() && _pChannel)
{
_pChannel->log(msg);
}
}
void Logger::log(const Exception& exc)
{
error(exc.displayText());
}
void Logger::dump(const std::string& msg, const void* buffer, int length, Message::Priority prio)
{
if (_level >= prio && _pChannel)
{
std::string text(msg);
formatDump(text, buffer, length);
_pChannel->log(Message(_name, text, prio));
}
}
void Logger::setLevel(const std::string& name, int level)
{
Mutex::ScopedLock lock(_mapMtx);
if (_pLoggerMap)
{
std::string::size_type len = name.length();
for (LoggerMap::iterator it = _pLoggerMap->begin(); it != _pLoggerMap->end(); ++it)
{
if (len == 0 || it->first.compare(0, len, name) == 0 && (it->first.length() == len || it->first[len] == '.'))
it->second->setLevel(level);
}
}
}
void Logger::setChannel(const std::string& name, Channel* pChannel)
{
Mutex::ScopedLock lock(_mapMtx);
if (_pLoggerMap)
{
std::string::size_type len = name.length();
for (LoggerMap::iterator it = _pLoggerMap->begin(); it != _pLoggerMap->end(); ++it)
{
if (len == 0 || it->first.compare(0, len, name) == 0 && (it->first.length() == len || it->first[len] == '.'))
it->second->setChannel(pChannel);
}
}
}
std::string Logger::format(const std::string& fmt, const std::string& arg)
{
std::string args[] =
{
arg
};
return format(fmt, 1, args);
}
std::string Logger::format(const std::string& fmt, const std::string& arg0, const std::string& arg1)
{
std::string args[] =
{
arg0,
arg1
};
return format(fmt, 2, args);
}
std::string Logger::format(const std::string& fmt, const std::string& arg0, const std::string& arg1, const std::string& arg2)
{
std::string args[] =
{
arg0,
arg1,
arg2
};
return format(fmt, 3, args);
}
std::string Logger::format(const std::string& fmt, const std::string& arg0, const std::string& arg1, const std::string& arg2, const std::string& arg3)
{
std::string args[] =
{
arg0,
arg1,
arg2,
arg3
};
return format(fmt, 4, args);
}
std::string Logger::format(const std::string& fmt, int argc, std::string argv[])
{
std::string result;
std::string::const_iterator it = fmt.begin();
while (it != fmt.end())
{
if (*it == '$')
{
++it;
if (*it == '$')
{
result += '$';
}
else if (*it >= '0' && *it <= '9')
{
int i = *it - '0';
if (i < argc)
result += argv[i];
}
else
{
result += '$';
result += *it;
}
}
else result += *it;
++it;
}
return result;
}
void Logger::formatDump(std::string& message, const void* buffer, int length)
{
const int BYTES_PER_LINE = 16;
message.reserve(message.size() + length*6);
if (!message.empty()) message.append("\n");
unsigned char* base = (unsigned char*) buffer;
int addr = 0;
while (addr < length)
{
if (addr > 0) message.append("\n");
message.append(NumberFormatter::formatHex(addr, 4));
message.append(" ");
int offset = 0;
while (addr + offset < length && offset < BYTES_PER_LINE)
{
message.append(NumberFormatter::formatHex(base[addr + offset], 2));
message.append(offset == 7 ? " " : " ");
++offset;
}
if (offset < 7) message.append(" ");
while (offset < BYTES_PER_LINE) { message.append(" "); ++offset; }
message.append(" ");
offset = 0;
while (addr + offset < length && offset < BYTES_PER_LINE)
{
unsigned char c = base[addr + offset];
message += (c >= 32 && c < 127) ? (char) c : '.';
++offset;
}
addr += BYTES_PER_LINE;
}
}
Logger& Logger::get(const std::string& name)
{
Mutex::ScopedLock lock(_mapMtx);
Logger* pLogger = has(name);
if (!pLogger)
{
Logger& par = parent(name);
pLogger = new Logger(name, par.getChannel(), par.getLevel());
add(pLogger);
}
return *pLogger;
}
Logger& Logger::create(const std::string& name, Channel* pChannel, int level)
{
Mutex::ScopedLock lock(_mapMtx);
if (has(name)) throw ExistsException();
Logger* pLogger = new Logger(name, pChannel, level);
add(pLogger);
return *pLogger;
}
Logger& Logger::root()
{
Mutex::ScopedLock lock(_mapMtx);
Logger* pRoot = has("");
if (!pRoot)
{
pRoot = new Logger("", 0, Message::PRIO_INFORMATION);
add(pRoot);
}
return *pRoot;
}
Logger* Logger::has(const std::string& name)
{
Mutex::ScopedLock lock(_mapMtx);
if (_pLoggerMap)
{
LoggerMap::iterator it = _pLoggerMap->find(name);
if (it != _pLoggerMap->end())
return it->second;
}
return 0;
}
void Logger::shutdown()
{
Mutex::ScopedLock lock(_mapMtx);
if (_pLoggerMap)
{
for (LoggerMap::iterator it = _pLoggerMap->begin(); it != _pLoggerMap->end(); ++it)
{
it->second->release();
}
delete _pLoggerMap;
_pLoggerMap = 0;
}
}
void Logger::destroy(const std::string& name)
{
Mutex::ScopedLock lock(_mapMtx);
if (_pLoggerMap)
{
LoggerMap::iterator it = _pLoggerMap->find(name);
if (it != _pLoggerMap->end())
{
it->second->release();
_pLoggerMap->erase(it);
}
}
}
Logger& Logger::parent(const std::string& name)
{
std::string::size_type pos = name.rfind('.');
if (pos != std::string::npos)
{
std::string pname = name.substr(0, pos);
Logger* pParent = has(pname);
if (pParent)
return *pParent;
else
return parent(pname);
}
else
{
return root();
}
}
class AutoLoggerShutdown
{
public:
AutoLoggerShutdown()
{
}
~AutoLoggerShutdown()
{
Logger::shutdown();
}
};
void Logger::add(Logger* pLogger)
{
static AutoLoggerShutdown als;
if (!_pLoggerMap)
_pLoggerMap = new LoggerMap;
_pLoggerMap->insert(LoggerMap::value_type(pLogger->name(), pLogger));
}
Foundation_END

View File

@@ -0,0 +1,125 @@
//
// LoggingFactory.cpp
//
// $Id: //poco/1.1.0/Foundation/src/LoggingFactory.cpp#2 $
//
// Library: Foundation
// Package: Logging
// Module: LoggingFactory
//
// 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 "Foundation/LoggingFactory.h"
#include "Foundation/SingletonHolder.h"
#include "Foundation/AsyncChannel.h"
#include "Foundation/ConsoleChannel.h"
#include "Foundation/FileChannel.h"
#include "Foundation/FormattingChannel.h"
#include "Foundation/SplitterChannel.h"
#include "Foundation/NullChannel.h"
#if defined(POCO_OS_FAMILY_UNIX)
#include "Foundation/SyslogChannel.h"
#endif
#if defined(POCO_OS_FAMILY_VMS)
#include "Foundation/OpcomChannel.h"
#endif
#if defined(POCO_OS_FAMILY_WINDOWS)
#include "Foundation/EventLogChannel.h"
#endif
#include "Foundation/PatternFormatter.h"
Foundation_BEGIN
LoggingFactory::LoggingFactory()
{
registerBuiltins();
}
LoggingFactory::~LoggingFactory()
{
}
void LoggingFactory::registerChannelClass(const std::string& className, ChannelInstantiator* pFactory)
{
_channelFactory.registerClass(className, pFactory);
}
void LoggingFactory::registerFormatterClass(const std::string& className, FormatterFactory* pFactory)
{
_formatterFactory.registerClass(className, pFactory);
}
Channel* LoggingFactory::createChannel(const std::string& className) const
{
return _channelFactory.createInstance(className);
}
Formatter* LoggingFactory::createFormatter(const std::string& className) const
{
return _formatterFactory.createInstance(className);
}
LoggingFactory& LoggingFactory::defaultFactory()
{
static SingletonHolder<LoggingFactory> sh;
return *sh.get();
}
void LoggingFactory::registerBuiltins()
{
_channelFactory.registerClass("AsyncChannel", new Instantiator<AsyncChannel, Channel>);
_channelFactory.registerClass("ConsoleChannel", new Instantiator<ConsoleChannel, Channel>);
_channelFactory.registerClass("FileChannel", new Instantiator<FileChannel, Channel>);
_channelFactory.registerClass("FormattingChannel", new Instantiator<FormattingChannel, Channel>);
_channelFactory.registerClass("SplitterChannel", new Instantiator<SplitterChannel, Channel>);
_channelFactory.registerClass("NullChannel", new Instantiator<NullChannel, Channel>);
#if defined(POCO_OS_FAMILY_UNIX)
_channelFactory.registerClass("SyslogChannel", new Instantiator<SyslogChannel, Channel>);
#endif
#if defined(POCO_OS_FAMILY_VMS)
_channelFactory.registerClass("OpcomChannel", new Instantiator<OpcomChannel, Channel>);
#endif
#if defined(POCO_OS_FAMILY_WINDOWS)
_channelFactory.registerClass("EventLogChannel", new Instantiator<EventLogChannel, Channel>);
#endif
_formatterFactory.registerClass("PatternFormatter", new Instantiator<PatternFormatter, Formatter>);
}
Foundation_END

View File

@@ -0,0 +1,134 @@
//
// LoggingRegistry.cpp
//
// $Id: //poco/1.1.0/Foundation/src/LoggingRegistry.cpp#2 $
//
// Library: Foundation
// Package: Logging
// Module: LoggingRegistry
//
// 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 "Foundation/LoggingRegistry.h"
#include "Foundation/SingletonHolder.h"
Foundation_BEGIN
LoggingRegistry::LoggingRegistry()
{
}
LoggingRegistry::~LoggingRegistry()
{
}
Channel* LoggingRegistry::channelForName(const std::string& name) const
{
FastMutex::ScopedLock lock(_mutex);
ChannelMap::const_iterator it = _channelMap.find(name);
if (it != _channelMap.end())
return const_cast<Channel*>(it->second.get());
else
throw NotFoundException(name);
}
Formatter* LoggingRegistry::formatterForName(const std::string& name) const
{
FastMutex::ScopedLock lock(_mutex);
FormatterMap::const_iterator it = _formatterMap.find(name);
if (it != _formatterMap.end())
return const_cast<Formatter*>(it->second.get());
else
throw NotFoundException(name);
}
void LoggingRegistry::registerChannel(const std::string& name, Channel* pChannel)
{
FastMutex::ScopedLock lock(_mutex);
_channelMap[name] = ChannelPtr(pChannel, true);
}
void LoggingRegistry::registerFormatter(const std::string& name, Formatter* pFormatter)
{
FastMutex::ScopedLock lock(_mutex);
_formatterMap[name] = FormatterPtr(pFormatter, true);
}
void LoggingRegistry::unregisterChannel(const std::string& name)
{
FastMutex::ScopedLock lock(_mutex);
ChannelMap::iterator it = _channelMap.find(name);
if (it != _channelMap.end())
_channelMap.erase(it);
else
throw NotFoundException(name);
}
void LoggingRegistry::unregisterFormatter(const std::string& name)
{
FastMutex::ScopedLock lock(_mutex);
FormatterMap::iterator it = _formatterMap.find(name);
if (it != _formatterMap.end())
_formatterMap.erase(it);
else
throw NotFoundException(name);
}
void LoggingRegistry::clear()
{
FastMutex::ScopedLock lock(_mutex);
_channelMap.clear();
_formatterMap.clear();
}
LoggingRegistry& LoggingRegistry::defaultRegistry()
{
static SingletonHolder<LoggingRegistry> sh;
return *sh.get();
}
Foundation_END

View File

@@ -0,0 +1,216 @@
//
// MD2Engine.cpp
//
// $Id: //poco/1.1.0/Foundation/src/MD2Engine.cpp#2 $
//
// Library: Foundation
// Package: Crypt
// Module: MD2Engine
//
// 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.
//
//
// MD2 (RFC 1319) algorithm:
// Copyright (C) 1990-2, RSA Data Security, Inc. Created 1990. All
// rights reserved.
//
// License to copy and use this software is granted for
// non-commercial Internet Privacy-Enhanced Mail provided that it is
// identified as the "RSA Data Security, Inc. MD2 Message Digest
// Algorithm" in all material mentioning or referencing this software
// or this function.
//
// RSA Data Security, Inc. makes no representations concerning either
// the merchantability of this software or the suitability of this
// software for any particular purpose. It is provided "as is"
// without express or implied warranty of any kind.
//
// These notices must be retained in any copies of any part of this
// documentation and/or software.
//
#include "Foundation/MD2Engine.h"
#include <string.h>
Foundation_BEGIN
MD2Engine::MD2Engine()
{
_digest.reserve(16);
reset();
}
MD2Engine::~MD2Engine()
{
reset();
}
void MD2Engine::updateImpl(const void* input_, unsigned inputLen)
{
const unsigned char* input = (const unsigned char*) input_;
unsigned int i, index, partLen;
/* Update number of bytes mod 16 */
index = _context.count;
_context.count = (index + inputLen) & 0xf;
partLen = 16 - index;
/* Transform as many times as possible. */
if (inputLen >= partLen)
{
memcpy(&_context.buffer[index], input, partLen);
transform(_context.state, _context.checksum, _context.buffer);
for (i = partLen; i + 15 < inputLen; i += 16)
transform(_context.state, _context.checksum, &input[i]);
index = 0;
}
else i = 0;
/* Buffer remaining input */
memcpy(&_context.buffer[index], &input[i], inputLen-i);
}
unsigned MD2Engine::digestLength() const
{
return DIGEST_SIZE;
}
void MD2Engine::reset()
{
memset(&_context, 0, sizeof(_context));
}
const DigestEngine::Digest& MD2Engine::digest()
{
static const unsigned char* PADDING[] =
{
(unsigned char*) "",
(unsigned char*) "\001",
(unsigned char*) "\002\002",
(unsigned char*) "\003\003\003",
(unsigned char*) "\004\004\004\004",
(unsigned char*) "\005\005\005\005\005",
(unsigned char*) "\006\006\006\006\006\006",
(unsigned char*) "\007\007\007\007\007\007\007",
(unsigned char*) "\010\010\010\010\010\010\010\010",
(unsigned char*) "\011\011\011\011\011\011\011\011\011",
(unsigned char*) "\012\012\012\012\012\012\012\012\012\012",
(unsigned char*) "\013\013\013\013\013\013\013\013\013\013\013",
(unsigned char*) "\014\014\014\014\014\014\014\014\014\014\014\014",
(unsigned char*) "\015\015\015\015\015\015\015\015\015\015\015\015\015",
(unsigned char *) "\016\016\016\016\016\016\016\016\016\016\016\016\016\016",
(unsigned char *) "\017\017\017\017\017\017\017\017\017\017\017\017\017\017\017",
(unsigned char *) "\020\020\020\020\020\020\020\020\020\020\020\020\020\020\020\020"
};
unsigned int index, padLen;
/* Pad out to multiple of 16. */
index = _context.count;
padLen = 16 - index;
update((const char*) PADDING[padLen], padLen);
/* Extend with checksum */
update((const char*) _context.checksum, 16);
/* Store state in digest */
_digest.clear();
_digest.insert(_digest.begin(), _context.state, _context.state + 16);
/* Zeroize sensitive information. */
memset(&_context, 0, sizeof(_context));
reset();
return _digest;
}
void MD2Engine::transform(unsigned char state[16], unsigned char checksum[16], const unsigned char block[16])
{
// Permutation of 0..255 constructed from the digits of pi. It gives a
// "random" nonlinear byte substitution operation.
static const unsigned char PI_SUBST[256] =
{
41, 46, 67, 201, 162, 216, 124, 1, 61, 54, 84, 161, 236, 240, 6,
19, 98, 167, 5, 243, 192, 199, 115, 140, 152, 147, 43, 217, 188,
76, 130, 202, 30, 155, 87, 60, 253, 212, 224, 22, 103, 66, 111, 24,
138, 23, 229, 18, 190, 78, 196, 214, 218, 158, 222, 73, 160, 251,
245, 142, 187, 47, 238, 122, 169, 104, 121, 145, 21, 178, 7, 63,
148, 194, 16, 137, 11, 34, 95, 33, 128, 127, 93, 154, 90, 144, 50,
39, 53, 62, 204, 231, 191, 247, 151, 3, 255, 25, 48, 179, 72, 165,
181, 209, 215, 94, 146, 42, 172, 86, 170, 198, 79, 184, 56, 210,
150, 164, 125, 182, 118, 252, 107, 226, 156, 116, 4, 241, 69, 157,
112, 89, 100, 113, 135, 32, 134, 91, 207, 101, 230, 45, 168, 2, 27,
96, 37, 173, 174, 176, 185, 246, 28, 70, 97, 105, 52, 64, 126, 15,
85, 71, 163, 35, 221, 81, 175, 58, 195, 92, 249, 206, 186, 197,
234, 38, 44, 83, 13, 110, 133, 40, 132, 9, 211, 223, 205, 244, 65,
129, 77, 82, 106, 220, 55, 200, 108, 193, 171, 250, 36, 225, 123,
8, 12, 189, 177, 74, 120, 136, 149, 139, 227, 99, 232, 109, 233,
203, 213, 254, 59, 0, 29, 57, 242, 239, 183, 14, 102, 88, 208, 228,
166, 119, 114, 248, 235, 117, 75, 10, 49, 68, 80, 180, 143, 237,
31, 26, 219, 153, 141, 51, 159, 17, 131, 20
};
unsigned int i, j, t;
unsigned char x[48];
/* Form encryption block from state, block, state ^ block. */
memcpy(x, state, 16);
memcpy(x+16, block, 16);
for (i = 0; i < 16; i++)
x[i+32] = state[i] ^ block[i];
/* Encrypt block (18 rounds). */
t = 0;
for (i = 0; i < 18; i++)
{
for (j = 0; j < 48; j++)
t = x[j] ^= PI_SUBST[t];
t = (t + i) & 0xff;
}
/* Save new state */
memcpy(state, x, 16);
/* Update checksum. */
t = checksum[15];
for (i = 0; i < 16; i++)
t = checksum[i] ^= PI_SUBST[block[i] ^ t];
/* Zeroize sensitive information. */
memset(x, 0, sizeof(x));
}
Foundation_END

View File

@@ -0,0 +1,300 @@
//
// MD4Engine.cpp
//
// $Id: //poco/1.1.0/Foundation/src/MD4Engine.cpp#2 $
//
// Library: Foundation
// Package: Crypt
// Module: MD4Engine
//
// 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.
//
//
// MD4 (RFC 1320) algorithm:
// Copyright (C) 1991-2, RSA Data Security, Inc. Created 1991. All
// rights reserved.
//
// License to copy and use this software is granted provided that it
// is identified as the "RSA Data Security, Inc. MD4 Message-Digest
// Algorithm" in all material mentioning or referencing this software
// or this function.
//
// License is also granted to make and use derivative works provided
// that such works are identified as "derived from the RSA Data
// Security, Inc. MD4 Message-Digest Algorithm" in all material
// mentioning or referencing the derived work.
//
// RSA Data Security, Inc. makes no representations concerning either
// the merchantability of this software or the suitability of this
// software for any particular purpose. It is provided "as is"
// without express or implied warranty of any kind.
//
// These notices must be retained in any copies of any part of this
// documentation and/or software.
//
#include "Foundation/MD4Engine.h"
#include <string.h>
Foundation_BEGIN
MD4Engine::MD4Engine()
{
_digest.reserve(16);
reset();
}
MD4Engine::~MD4Engine()
{
reset();
}
void MD4Engine::updateImpl(const void* input_, unsigned inputLen)
{
const unsigned char* input = (const unsigned char*) input_;
unsigned int i, index, partLen;
/* Compute number of bytes mod 64 */
index = (unsigned int)((_context.count[0] >> 3) & 0x3F);
/* Update number of bits */
if ((_context.count[0] += ((UInt32) inputLen << 3)) < ((UInt32) inputLen << 3))
_context.count[1]++;
_context.count[1] += ((UInt32) inputLen >> 29);
partLen = 64 - index;
/* Transform as many times as possible. */
if (inputLen >= partLen)
{
memcpy(&_context.buffer[index], input, partLen);
transform(_context.state, _context.buffer);
for (i = partLen; i + 63 < inputLen; i += 64)
transform(_context.state, &input[i]);
index = 0;
}
else i = 0;
/* Buffer remaining input */
memcpy(&_context.buffer[index], &input[i], inputLen-i);
}
unsigned MD4Engine::digestLength() const
{
return DIGEST_SIZE;
}
void MD4Engine::reset()
{
memset(&_context, 0, sizeof(_context));
_context.count[0] = _context.count[1] = 0;
_context.state[0] = 0x67452301;
_context.state[1] = 0xefcdab89;
_context.state[2] = 0x98badcfe;
_context.state[3] = 0x10325476;
}
const DigestEngine::Digest& MD4Engine::digest()
{
static const unsigned char PADDING[64] =
{
0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
};
unsigned char bits[8];
unsigned int index, padLen;
/* Save number of bits */
encode(bits, _context.count, 8);
/* Pad out to 56 mod 64. */
index = (unsigned int)((_context.count[0] >> 3) & 0x3f);
padLen = (index < 56) ? (56 - index) : (120 - index);
update(PADDING, padLen);
/* Append length (before padding) */
update(bits, 8);
/* Store state in digest */
unsigned char digest[16];
encode(digest, _context.state, 16);
_digest.clear();
_digest.insert(_digest.begin(), digest, digest + sizeof(digest));
/* Zeroize sensitive information. */
memset(&_context, 0, sizeof (_context));
reset();
return _digest;
}
/* Constants for MD4Transform routine. */
#define S11 3
#define S12 7
#define S13 11
#define S14 19
#define S21 3
#define S22 5
#define S23 9
#define S24 13
#define S31 3
#define S32 9
#define S33 11
#define S34 15
/* F, G and H are basic MD4 functions. */
#define F(x, y, z) (((x) & (y)) | ((~x) & (z)))
#define G(x, y, z) (((x) & (y)) | ((x) & (z)) | ((y) & (z)))
#define H(x, y, z) ((x) ^ (y) ^ (z))
/* ROTATE_LEFT rotates x left n bits. */
#define ROTATE_LEFT(x, n) (((x) << (n)) | ((x) >> (32-(n))))
/* FF, GG and HH are transformations for rounds 1, 2 and 3 */
/* Rotation is separate from addition to prevent recomputation */
#define FF(a, b, c, d, x, s) { \
(a) += F ((b), (c), (d)) + (x); \
(a) = ROTATE_LEFT ((a), (s)); \
}
#define GG(a, b, c, d, x, s) { \
(a) += G ((b), (c), (d)) + (x) + (UInt32)0x5a827999; \
(a) = ROTATE_LEFT ((a), (s)); \
}
#define HH(a, b, c, d, x, s) { \
(a) += H ((b), (c), (d)) + (x) + (UInt32)0x6ed9eba1; \
(a) = ROTATE_LEFT ((a), (s)); \
}
void MD4Engine::transform (UInt32 state[4], const unsigned char block[64])
{
UInt32 a = state[0], b = state[1], c = state[2], d = state[3], x[16];
decode(x, block, 64);
/* Round 1 */
FF (a, b, c, d, x[ 0], S11); /* 1 */
FF (d, a, b, c, x[ 1], S12); /* 2 */
FF (c, d, a, b, x[ 2], S13); /* 3 */
FF (b, c, d, a, x[ 3], S14); /* 4 */
FF (a, b, c, d, x[ 4], S11); /* 5 */
FF (d, a, b, c, x[ 5], S12); /* 6 */
FF (c, d, a, b, x[ 6], S13); /* 7 */
FF (b, c, d, a, x[ 7], S14); /* 8 */
FF (a, b, c, d, x[ 8], S11); /* 9 */
FF (d, a, b, c, x[ 9], S12); /* 10 */
FF (c, d, a, b, x[10], S13); /* 11 */
FF (b, c, d, a, x[11], S14); /* 12 */
FF (a, b, c, d, x[12], S11); /* 13 */
FF (d, a, b, c, x[13], S12); /* 14 */
FF (c, d, a, b, x[14], S13); /* 15 */
FF (b, c, d, a, x[15], S14); /* 16 */
/* Round 2 */
GG (a, b, c, d, x[ 0], S21); /* 17 */
GG (d, a, b, c, x[ 4], S22); /* 18 */
GG (c, d, a, b, x[ 8], S23); /* 19 */
GG (b, c, d, a, x[12], S24); /* 20 */
GG (a, b, c, d, x[ 1], S21); /* 21 */
GG (d, a, b, c, x[ 5], S22); /* 22 */
GG (c, d, a, b, x[ 9], S23); /* 23 */
GG (b, c, d, a, x[13], S24); /* 24 */
GG (a, b, c, d, x[ 2], S21); /* 25 */
GG (d, a, b, c, x[ 6], S22); /* 26 */
GG (c, d, a, b, x[10], S23); /* 27 */
GG (b, c, d, a, x[14], S24); /* 28 */
GG (a, b, c, d, x[ 3], S21); /* 29 */
GG (d, a, b, c, x[ 7], S22); /* 30 */
GG (c, d, a, b, x[11], S23); /* 31 */
GG (b, c, d, a, x[15], S24); /* 32 */
/* Round 3 */
HH (a, b, c, d, x[ 0], S31); /* 33 */
HH (d, a, b, c, x[ 8], S32); /* 34 */
HH (c, d, a, b, x[ 4], S33); /* 35 */
HH (b, c, d, a, x[12], S34); /* 36 */
HH (a, b, c, d, x[ 2], S31); /* 37 */
HH (d, a, b, c, x[10], S32); /* 38 */
HH (c, d, a, b, x[ 6], S33); /* 39 */
HH (b, c, d, a, x[14], S34); /* 40 */
HH (a, b, c, d, x[ 1], S31); /* 41 */
HH (d, a, b, c, x[ 9], S32); /* 42 */
HH (c, d, a, b, x[ 5], S33); /* 43 */
HH (b, c, d, a, x[13], S34); /* 44 */
HH (a, b, c, d, x[ 3], S31); /* 45 */
HH (d, a, b, c, x[11], S32); /* 46 */
HH (c, d, a, b, x[ 7], S33); /* 47 */
HH (b, c, d, a, x[15], S34); /* 48 */
state[0] += a;
state[1] += b;
state[2] += c;
state[3] += d;
/* Zeroize sensitive information. */
memset(x, 0, sizeof(x));
}
void MD4Engine::encode(unsigned char* output, const UInt32* input, unsigned int len)
{
unsigned int i, j;
for (i = 0, j = 0; j < len; i++, j += 4)
{
output[j] = (unsigned char)(input[i] & 0xff);
output[j+1] = (unsigned char)((input[i] >> 8) & 0xff);
output[j+2] = (unsigned char)((input[i] >> 16) & 0xff);
output[j+3] = (unsigned char)((input[i] >> 24) & 0xff);
}
}
void MD4Engine::decode(UInt32* output, const unsigned char* input, unsigned int len)
{
unsigned int i, j;
for (i = 0, j = 0; j < len; i++, j += 4)
output[i] = ((UInt32)input[j]) | (((UInt32)input[j+1]) << 8) |
(((UInt32)input[j+2]) << 16) | (((UInt32)input[j+3]) << 24);
}
Foundation_END

View File

@@ -0,0 +1,331 @@
//
// MD5Engine.cpp
//
// $Id: //poco/1.1.0/Foundation/src/MD5Engine.cpp#2 $
//
// Library: Foundation
// Package: Crypt
// Module: MD5Engine
//
// 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.
//
//
// MD5 (RFC 1321) algorithm:
// Copyright (C) 1991-2, RSA Data Security, Inc. Created 1991. All
// rights reserved.
//
// License to copy and use this software is granted provided that it
// is identified as the "RSA Data Security, Inc. MD5 Message-Digest
// Algorithm" in all material mentioning or referencing this software
// or this function.
//
// License is also granted to make and use derivative works provided
// that such works are identified as "derived from the RSA Data
// Security, Inc. MD5 Message-Digest Algorithm" in all material
// mentioning or referencing the derived work.
//
// RSA Data Security, Inc. makes no representations concerning either
// the merchantability of this software or the suitability of this
// software for any particular purpose. It is provided "as is"
// without express or implied warranty of any kind.
//
// These notices must be retained in any copies of any part of this
// documentation and/or software.
//
#include "Foundation/MD5Engine.h"
#include <string.h>
Foundation_BEGIN
MD5Engine::MD5Engine()
{
_digest.reserve(16);
reset();
}
MD5Engine::~MD5Engine()
{
reset();
}
void MD5Engine::updateImpl(const void* input_, unsigned inputLen)
{
const unsigned char* input = (const unsigned char*) input_;
unsigned int i, index, partLen;
/* Compute number of bytes mod 64 */
index = (unsigned int)((_context.count[0] >> 3) & 0x3F);
/* Update number of bits */
if ((_context.count[0] += ((UInt32) inputLen << 3)) < ((UInt32) inputLen << 3))
_context.count[1]++;
_context.count[1] += ((UInt32) inputLen >> 29);
partLen = 64 - index;
/* Transform as many times as possible. */
if (inputLen >= partLen)
{
memcpy(&_context.buffer[index], input, partLen);
transform(_context.state, _context.buffer);
for (i = partLen; i + 63 < inputLen; i += 64)
transform(_context.state, &input[i]);
index = 0;
}
else i = 0;
/* Buffer remaining input */
memcpy(&_context.buffer[index], &input[i],inputLen-i);
}
unsigned MD5Engine::digestLength() const
{
return DIGEST_SIZE;
}
void MD5Engine::reset()
{
memset(&_context, 0, sizeof(_context));
_context.count[0] = _context.count[1] = 0;
_context.state[0] = 0x67452301;
_context.state[1] = 0xefcdab89;
_context.state[2] = 0x98badcfe;
_context.state[3] = 0x10325476;
}
const DigestEngine::Digest& MD5Engine::digest()
{
static const unsigned char PADDING[64] =
{
0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
};
unsigned char bits[8];
unsigned int index, padLen;
/* Save number of bits */
encode(bits, _context.count, 8);
/* Pad out to 56 mod 64. */
index = (unsigned int)((_context.count[0] >> 3) & 0x3f);
padLen = (index < 56) ? (56 - index) : (120 - index);
update(PADDING, padLen);
/* Append length (before padding) */
update(bits, 8);
/* Store state in digest */
unsigned char digest[16];
encode(digest, _context.state, 16);
_digest.clear();
_digest.insert(_digest.begin(), digest, digest + sizeof(digest));
/* Zeroize sensitive information. */
memset(&_context, 0, sizeof (_context));
reset();
return _digest;
}
/* Constants for MD5Transform routine. */
#define S11 7
#define S12 12
#define S13 17
#define S14 22
#define S21 5
#define S22 9
#define S23 14
#define S24 20
#define S31 4
#define S32 11
#define S33 16
#define S34 23
#define S41 6
#define S42 10
#define S43 15
#define S44 21
/* F, G, H and I are basic MD5 functions. */
#define F(x, y, z) (((x) & (y)) | ((~x) & (z)))
#define G(x, y, z) (((x) & (z)) | ((y) & (~z)))
#define H(x, y, z) ((x) ^ (y) ^ (z))
#define I(x, y, z) ((y) ^ ((x) | (~z)))
/* ROTATE_LEFT rotates x left n bits. */
#define ROTATE_LEFT(x, n) (((x) << (n)) | ((x) >> (32-(n))))
/* FF, GG, HH, and II transformations for rounds 1, 2, 3, and 4.
Rotation is separate from addition to prevent recomputation. */
#define FF(a, b, c, d, x, s, ac) { \
(a) += F ((b), (c), (d)) + (x) + (UInt32)(ac); \
(a) = ROTATE_LEFT ((a), (s)); \
(a) += (b); \
}
#define GG(a, b, c, d, x, s, ac) { \
(a) += G ((b), (c), (d)) + (x) + (UInt32)(ac); \
(a) = ROTATE_LEFT ((a), (s)); \
(a) += (b); \
}
#define HH(a, b, c, d, x, s, ac) { \
(a) += H ((b), (c), (d)) + (x) + (UInt32)(ac); \
(a) = ROTATE_LEFT ((a), (s)); \
(a) += (b); \
}
#define II(a, b, c, d, x, s, ac) { \
(a) += I ((b), (c), (d)) + (x) + (UInt32)(ac); \
(a) = ROTATE_LEFT ((a), (s)); \
(a) += (b); \
}
void MD5Engine::transform (UInt32 state[4], const unsigned char block[64])
{
UInt32 a = state[0], b = state[1], c = state[2], d = state[3], x[16];
decode(x, block, 64);
/* Round 1 */
FF (a, b, c, d, x[ 0], S11, 0xd76aa478); /* 1 */
FF (d, a, b, c, x[ 1], S12, 0xe8c7b756); /* 2 */
FF (c, d, a, b, x[ 2], S13, 0x242070db); /* 3 */
FF (b, c, d, a, x[ 3], S14, 0xc1bdceee); /* 4 */
FF (a, b, c, d, x[ 4], S11, 0xf57c0faf); /* 5 */
FF (d, a, b, c, x[ 5], S12, 0x4787c62a); /* 6 */
FF (c, d, a, b, x[ 6], S13, 0xa8304613); /* 7 */
FF (b, c, d, a, x[ 7], S14, 0xfd469501); /* 8 */
FF (a, b, c, d, x[ 8], S11, 0x698098d8); /* 9 */
FF (d, a, b, c, x[ 9], S12, 0x8b44f7af); /* 10 */
FF (c, d, a, b, x[10], S13, 0xffff5bb1); /* 11 */
FF (b, c, d, a, x[11], S14, 0x895cd7be); /* 12 */
FF (a, b, c, d, x[12], S11, 0x6b901122); /* 13 */
FF (d, a, b, c, x[13], S12, 0xfd987193); /* 14 */
FF (c, d, a, b, x[14], S13, 0xa679438e); /* 15 */
FF (b, c, d, a, x[15], S14, 0x49b40821); /* 16 */
/* Round 2 */
GG (a, b, c, d, x[ 1], S21, 0xf61e2562); /* 17 */
GG (d, a, b, c, x[ 6], S22, 0xc040b340); /* 18 */
GG (c, d, a, b, x[11], S23, 0x265e5a51); /* 19 */
GG (b, c, d, a, x[ 0], S24, 0xe9b6c7aa); /* 20 */
GG (a, b, c, d, x[ 5], S21, 0xd62f105d); /* 21 */
GG (d, a, b, c, x[10], S22, 0x2441453); /* 22 */
GG (c, d, a, b, x[15], S23, 0xd8a1e681); /* 23 */
GG (b, c, d, a, x[ 4], S24, 0xe7d3fbc8); /* 24 */
GG (a, b, c, d, x[ 9], S21, 0x21e1cde6); /* 25 */
GG (d, a, b, c, x[14], S22, 0xc33707d6); /* 26 */
GG (c, d, a, b, x[ 3], S23, 0xf4d50d87); /* 27 */
GG (b, c, d, a, x[ 8], S24, 0x455a14ed); /* 28 */
GG (a, b, c, d, x[13], S21, 0xa9e3e905); /* 29 */
GG (d, a, b, c, x[ 2], S22, 0xfcefa3f8); /* 30 */
GG (c, d, a, b, x[ 7], S23, 0x676f02d9); /* 31 */
GG (b, c, d, a, x[12], S24, 0x8d2a4c8a); /* 32 */
/* Round 3 */
HH (a, b, c, d, x[ 5], S31, 0xfffa3942); /* 33 */
HH (d, a, b, c, x[ 8], S32, 0x8771f681); /* 34 */
HH (c, d, a, b, x[11], S33, 0x6d9d6122); /* 35 */
HH (b, c, d, a, x[14], S34, 0xfde5380c); /* 36 */
HH (a, b, c, d, x[ 1], S31, 0xa4beea44); /* 37 */
HH (d, a, b, c, x[ 4], S32, 0x4bdecfa9); /* 38 */
HH (c, d, a, b, x[ 7], S33, 0xf6bb4b60); /* 39 */
HH (b, c, d, a, x[10], S34, 0xbebfbc70); /* 40 */
HH (a, b, c, d, x[13], S31, 0x289b7ec6); /* 41 */
HH (d, a, b, c, x[ 0], S32, 0xeaa127fa); /* 42 */
HH (c, d, a, b, x[ 3], S33, 0xd4ef3085); /* 43 */
HH (b, c, d, a, x[ 6], S34, 0x4881d05); /* 44 */
HH (a, b, c, d, x[ 9], S31, 0xd9d4d039); /* 45 */
HH (d, a, b, c, x[12], S32, 0xe6db99e5); /* 46 */
HH (c, d, a, b, x[15], S33, 0x1fa27cf8); /* 47 */
HH (b, c, d, a, x[ 2], S34, 0xc4ac5665); /* 48 */
/* Round 4 */
II (a, b, c, d, x[ 0], S41, 0xf4292244); /* 49 */
II (d, a, b, c, x[ 7], S42, 0x432aff97); /* 50 */
II (c, d, a, b, x[14], S43, 0xab9423a7); /* 51 */
II (b, c, d, a, x[ 5], S44, 0xfc93a039); /* 52 */
II (a, b, c, d, x[12], S41, 0x655b59c3); /* 53 */
II (d, a, b, c, x[ 3], S42, 0x8f0ccc92); /* 54 */
II (c, d, a, b, x[10], S43, 0xffeff47d); /* 55 */
II (b, c, d, a, x[ 1], S44, 0x85845dd1); /* 56 */
II (a, b, c, d, x[ 8], S41, 0x6fa87e4f); /* 57 */
II (d, a, b, c, x[15], S42, 0xfe2ce6e0); /* 58 */
II (c, d, a, b, x[ 6], S43, 0xa3014314); /* 59 */
II (b, c, d, a, x[13], S44, 0x4e0811a1); /* 60 */
II (a, b, c, d, x[ 4], S41, 0xf7537e82); /* 61 */
II (d, a, b, c, x[11], S42, 0xbd3af235); /* 62 */
II (c, d, a, b, x[ 2], S43, 0x2ad7d2bb); /* 63 */
II (b, c, d, a, x[ 9], S44, 0xeb86d391); /* 64 */
state[0] += a;
state[1] += b;
state[2] += c;
state[3] += d;
/* Zeroize sensitive information. */
memset(x, 0, sizeof(x));
}
void MD5Engine::encode(unsigned char* output, const UInt32* input, unsigned int len)
{
unsigned int i, j;
for (i = 0, j = 0; j < len; i++, j += 4)
{
output[j] = (unsigned char)(input[i] & 0xff);
output[j+1] = (unsigned char)((input[i] >> 8) & 0xff);
output[j+2] = (unsigned char)((input[i] >> 16) & 0xff);
output[j+3] = (unsigned char)((input[i] >> 24) & 0xff);
}
}
void MD5Engine::decode(UInt32* output, const unsigned char* input, unsigned int len)
{
unsigned int i, j;
for (i = 0, j = 0; j < len; i++, j += 4)
output[i] = ((UInt32)input[j]) | (((UInt32)input[j+1]) << 8) |
(((UInt32)input[j+2]) << 16) | (((UInt32)input[j+3]) << 24);
}
Foundation_END

BIN
Foundation/src/MSG00001.bin Normal file

Binary file not shown.

View File

@@ -0,0 +1,53 @@
//
// Manifest.cpp
//
// $Id: //poco/1.1.0/Foundation/src/Manifest.cpp#2 $
//
// Library: Foundation
// Package: SharedLibrary
// Module: ClassLoader
//
// 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 "Foundation/Manifest.h"
Foundation_BEGIN
ManifestBase::ManifestBase()
{
}
ManifestBase::~ManifestBase()
{
}
Foundation_END

View File

@@ -0,0 +1,103 @@
//
// MemoryPool.cpp
//
// $Id: //poco/1.1.0/Foundation/src/MemoryPool.cpp#2 $
//
// Library: Foundation
// Package: Core
// Module: MemoryPool
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Foundation/MemoryPool.h"
#include "Foundation/Exception.h"
Foundation_BEGIN
MemoryPool::MemoryPool(size_t blockSize, int preAlloc, int maxAlloc):
_blockSize(blockSize),
_maxAlloc(maxAlloc),
_allocated(preAlloc)
{
poco_assert (maxAlloc == 0 || maxAlloc >= preAlloc);
int r = BLOCK_RESERVE;
if (preAlloc > r)
r = preAlloc;
if (maxAlloc > 0 && maxAlloc < r)
r = maxAlloc;
_blocks.reserve(r);
for (int i = 0; i < preAlloc; ++i)
{
_blocks.push_back(new char[_blockSize]);
}
}
MemoryPool::~MemoryPool()
{
for (BlockVec::iterator it = _blocks.begin(); it != _blocks.end(); ++it)
{
delete [] *it;
}
}
void* MemoryPool::get()
{
FastMutex::ScopedLock lock(_mutex);
if (_blocks.empty())
{
if (_maxAlloc == 0 || _allocated < _maxAlloc)
{
++_allocated;
return new char[_blockSize];
}
else throw OutOfMemoryException("MemoryPool exhausted");
}
else
{
char* ptr = _blocks.back();
_blocks.pop_back();
return ptr;
}
}
void MemoryPool::release(void* ptr)
{
FastMutex::ScopedLock lock(_mutex);
_blocks.push_back(reinterpret_cast<char*>(ptr));
}
Foundation_END

202
Foundation/src/Message.cpp Normal file
View File

@@ -0,0 +1,202 @@
//
// Message.cpp
//
// $Id: //poco/1.1.0/Foundation/src/Message.cpp#2 $
//
// Library: Foundation
// Package: Logging
// Module: Message
//
// 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 "Foundation/Message.h"
#include "Foundation/Exception.h"
#include "Foundation/Process.h"
#include "Foundation/Thread.h"
Foundation_BEGIN
Message::Message():
_prio(PRIO_FATAL),
_pMap(0),
_tid(0),
_pid(0)
{
init();
}
Message::Message(const std::string& source, const std::string& text, Priority prio):
_source(source),
_text(text),
_prio(prio),
_pMap(0),
_tid(0),
_pid(0)
{
init();
}
Message::Message(const Message& msg)
{
_source = msg._source;
_text = msg._text;
_prio = msg._prio;
_time = msg._time;
_thread = msg._thread;
_tid = msg._tid;
_pid = msg._pid;
if (msg._pMap)
_pMap = new StringMap(*msg._pMap);
else
_pMap = 0;
}
Message::Message(const Message& msg, const std::string& text)
{
_source = msg._source;
_text = text;
_prio = msg._prio;
_time = msg._time;
_thread = msg._thread;
_tid = msg._tid;
_pid = msg._pid;
if (msg._pMap)
_pMap = new StringMap(*msg._pMap);
else
_pMap = 0;
}
Message::~Message()
{
delete _pMap;
}
void Message::init()
{
_pid = Process::id();
Thread* pThread = Thread::current();
if (pThread)
{
_tid = pThread->id();
_thread = pThread->name();
}
}
Message& Message::operator = (const Message& msg)
{
if (this == &msg) return *this;
_source = msg._source;
_text = msg._text;
_prio = msg._prio;
_time = msg._time;
_thread = msg._thread;
_pid = msg._pid;
if (msg._pMap)
_pMap = new StringMap(*msg._pMap);
else
_pMap = 0;
return *this;
}
void Message::setSource(const std::string& src)
{
_source = src;
}
void Message::setText(const std::string& text)
{
_text = text;
}
void Message::setPriority(Priority prio)
{
_prio = prio;
}
void Message::setTime(const Timestamp& t)
{
_time = t;
}
const Timestamp& Message::getTime() const
{
return _time;
}
void Message::setThread(const std::string& thread)
{
_thread = thread;
}
void Message::setTid(long tid)
{
_tid = tid;
}
void Message::setPid(long pid)
{
_pid = pid;
}
const std::string& Message::operator [] (const std::string& param) const
{
if (_pMap)
return (*_pMap)[param];
else
throw NotFoundException();
}
std::string& Message::operator [] (const std::string& param)
{
if (!_pMap)
_pMap = new StringMap;
return (*_pMap)[param];
}
Foundation_END

70
Foundation/src/Mutex.cpp Normal file
View File

@@ -0,0 +1,70 @@
//
// Mutex.cpp
//
// $Id: //poco/1.1.0/Foundation/src/Mutex.cpp#2 $
//
// Library: Foundation
// Package: Threading
// Module: Mutex
//
// 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 "Foundation/Mutex.h"
#if defined(POCO_OS_FAMILY_WINDOWS)
#include "Mutex_WIN32.cpp"
#else
#include "Mutex_POSIX.cpp"
#endif
Foundation_BEGIN
Mutex::Mutex()
{
}
Mutex::~Mutex()
{
}
FastMutex::FastMutex()
{
}
FastMutex::~FastMutex()
{
}
Foundation_END

View File

@@ -0,0 +1,95 @@
//
// Mutex_POSIX.cpp
//
// $Id: //poco/1.1.0/Foundation/src/Mutex_POSIX.cpp#2 $
//
// Library: Foundation
// Package: Threading
// Module: Mutex
//
// 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 "Foundation/Mutex_POSIX.h"
Foundation_BEGIN
MutexImpl::MutexImpl()
{
pthread_mutexattr_t attr;
pthread_mutexattr_init(&attr);
#if defined(PTHREAD_MUTEX_RECURSIVE_NP)
pthread_mutexattr_settype_np(&attr, PTHREAD_MUTEX_RECURSIVE_NP);
#else
pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
#endif
if (pthread_mutex_init(&_mutex, &attr))
{
pthread_mutexattr_destroy(&attr);
throw SystemException("cannot create mutex");
}
pthread_mutexattr_destroy(&attr);
}
MutexImpl::MutexImpl(bool fast)
{
pthread_mutexattr_t attr;
pthread_mutexattr_init(&attr);
#if defined(PTHREAD_MUTEX_RECURSIVE_NP)
pthread_mutexattr_settype_np(&attr, fast ? PTHREAD_MUTEX_NORMAL_NP : PTHREAD_MUTEX_RECURSIVE_NP);
#else
pthread_mutexattr_settype(&attr, fast ? PTHREAD_MUTEX_NORMAL : PTHREAD_MUTEX_RECURSIVE);
#endif
if (pthread_mutex_init(&_mutex, &attr))
{
pthread_mutexattr_destroy(&attr);
throw SystemException("cannot create mutex");
}
pthread_mutexattr_destroy(&attr);
}
MutexImpl::~MutexImpl()
{
pthread_mutex_destroy(&_mutex);
}
FastMutexImpl::FastMutexImpl(): MutexImpl(true)
{
}
FastMutexImpl::~FastMutexImpl()
{
}
Foundation_END

View File

@@ -0,0 +1,56 @@
//
// Mutex_WIN32.cpp
//
// $Id: //poco/1.1.0/Foundation/src/Mutex_WIN32.cpp#2 $
//
// Library: Foundation
// Package: Threading
// Module: Mutex
//
// 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 "Foundation/Mutex_WIN32.h"
Foundation_BEGIN
MutexImpl::MutexImpl()
{
if (!InitializeCriticalSectionAndSpinCount(&_cs, 4000))
throw SystemException("cannot create mutex");
}
MutexImpl::~MutexImpl()
{
DeleteCriticalSection(&_cs);
}
Foundation_END

View File

@@ -0,0 +1,65 @@
//
// NamedEvent.cpp
//
// $Id: //poco/1.1.0/Foundation/src/NamedEvent.cpp#2 $
//
// Library: Foundation
// Package: Processes
// Module: NamedEvent
//
// 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 "Foundation/NamedEvent.h"
#if defined(POCO_OS_FAMILY_WINDOWS) && defined(POCO_WIN32_UTF8)
#include "NamedEvent_WIN32U.cpp"
#elif defined(POCO_OS_FAMILY_WINDOWS)
#include "NamedEvent_WIN32.cpp"
#elif defined(POCO_OS_FAMILY_UNIX)
#include "NamedEvent_UNIX.cpp"
#else
#include "NamedEvent_VMS.cpp"
#endif
Foundation_BEGIN
NamedEvent::NamedEvent(const std::string& name):
NamedEventImpl(name)
{
}
NamedEvent::~NamedEvent()
{
}
Foundation_END

View File

@@ -0,0 +1,159 @@
//
// NamedEvent_UNIX.cpp
//
// $Id: //poco/1.1.0/Foundation/src/NamedEvent_UNIX.cpp#2 $
//
// Library: Foundation
// Package: Processes
// Module: NamedEvent
//
// 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 "Foundation/NamedEvent_UNIX.h"
#include "Foundation/Exception.h"
#include <fcntl.h>
#include <sys/stat.h>
#if defined(sun) || defined(__APPLE__) || defined(__osf__) || defined(__QNX__)
#include <semaphore.h>
#else
#include <unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <errno.h>
#endif
Foundation_BEGIN
#if defined(linux) || defined(__CYGWIN__)
union semun
{
int val;
struct semid_ds* buf;
unsigned short int* array;
struct seminfo* __buf;
};
#elif defined(hpux)
union semun
{
int val;
struct semid_ds* buf;
ushort* array;
};
#endif
NamedEventImpl::NamedEventImpl(const std::string& name):
_name(name)
{
std::string fileName = getFileName();
#if defined(sun) || defined(__APPLE__) || defined(__osf__) || defined(__QNX__)
_sem = sem_open(fileName.c_str(), O_CREAT, S_IRWXU | S_IRWXG | S_IRWXO, 0);
if ((long) _sem == (long) SEM_FAILED)
throw SystemException("cannot create named event (sem_open() failed)", _name);
#else
int fd = open(fileName.c_str(), O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
if (fd != -1)
close(fd);
else
throw SystemException("cannot create named event (lockfile)", _name);
key_t key = ftok(fileName.c_str(), 0);
if (key == -1)
throw SystemException("cannot create named event (ftok() failed)", _name);
_semid = semget(key, 1, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH | IPC_CREAT | IPC_EXCL);
if (_semid >= 0)
{
union semun arg;
arg.val = 0;
semctl(_semid, 0, SETVAL, arg);
}
else if (errno == EEXIST)
{
_semid = semget(key, 1, 0);
}
else throw SystemException("cannot create named event (semget() failed)", _name);
#endif // defined(sun) || defined(__APPLE__) || defined(__osf__) || defined(__QNX__)
}
NamedEventImpl::~NamedEventImpl()
{
#if defined(sun) || defined(__APPLE__) || defined(__osf__) || defined(__QNX__)
sem_close(_sem);
#endif
}
void NamedEventImpl::setImpl()
{
#if defined(sun) || defined(__APPLE__) || defined(__osf__) || defined(__QNX__)
if (sem_post(_sem) != 0)
throw SystemException("cannot set named event", _name);
#else
struct sembuf op;
op.sem_num = 0;
op.sem_op = 1;
op.sem_flg = SEM_UNDO;
if (semop(_semid, &op, 1) != 0)
throw SystemException("cannot set named event", _name);
#endif
}
void NamedEventImpl::waitImpl()
{
#if defined(sun) || defined(__APPLE__) || defined(__osf__) || defined(__QNX__)
if (sem_wait(_sem) != 0)
throw SystemException("cannot wait for named event", _name);
#else
struct sembuf op;
op.sem_num = 0;
op.sem_op = -1;
op.sem_flg = SEM_UNDO;
if (semop(_semid, &op, 1) != 0)
throw SystemException("cannot wait for named event", _name);
#endif
}
std::string NamedEventImpl::getFileName()
{
#if defined(sun) || defined(__APPLE__) || defined(__QNX__)
std::string fn = "/";
#else
std::string fn = "/tmp/";
#endif
fn.append(_name);
fn.append(".event");
return fn;
}
Foundation_END

View File

@@ -0,0 +1,85 @@
//
// NamedEvent_VMS.cpp
//
// $Id: //poco/1.1.0/Foundation/src/NamedEvent_VMS.cpp#2 $
//
// Library: Foundation
// Package: Processes
// Module: NamedEvent
//
// 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 "Foundation/NamedEvent_VMS.h"
#include <lib$routines.h>
#include <starlet.h>
#include <descrip.h>
#include <iodef.h>
Foundation_BEGIN
NamedEventImpl::NamedEventImpl(const std::string& name):
_name(name)
{
struct dsc$descriptor_s mbxDesc;
mbxDesc.dsc$w_length = _name.length();
mbxDesc.dsc$b_dtype = DSC$K_DTYPE_T;
mbxDesc.dsc$b_class = DSC$K_CLASS_S;
mbxDesc.dsc$a_pointer = _name.c_str();
if (sys$crembx(0, &_mbxChan, 0, 0, 0, 0, &mbxDesc, 0, 0) != 1)
throw SystemException("cannot create named event", _name);
}
NamedEventImpl::~NamedEventImpl()
{
sys$dassgn(_mbxChan);
}
void NamedEventImpl::setImpl()
{
char buffer = 0xFF;
if (sys$qio(0, _mbxChan, IO$_WRITEVBLK, 0, 0, 0, &buffer, sizeof(buffer), 0, 0, 0, 0) != 1)
throw SystemException("cannot set named event", _name);
}
void NamedEventImpl::waitImpl()
{
char buffer = 0;
while (buffer == 0)
{
if (sys$qiow(0, _mbxChan, IO$_READVBLK, 0, 0, 0, &buffer, sizeof(buffer), 0, 0, 0, 0) != 1)
throw SystemException("cannot wait for named event", _name);
}
}
Foundation_END

View File

@@ -0,0 +1,78 @@
//
// NamedEvent_WIN32.cpp
//
// $Id: //poco/1.1.0/Foundation/src/NamedEvent_WIN32.cpp#2 $
//
// Library: Foundation
// Package: Processes
// Module: NamedEvent
//
// 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 "Foundation/NamedEvent_WIN32.h"
#include "Foundation/Exception.h"
Foundation_BEGIN
NamedEventImpl::NamedEventImpl(const std::string& name):
_name(name)
{
_event = CreateEvent(NULL, FALSE, FALSE, _name.c_str());
if (!_event)
throw SystemException("cannot create named event", _name);
}
NamedEventImpl::~NamedEventImpl()
{
CloseHandle(_event);
}
void NamedEventImpl::setImpl()
{
if (!SetEvent(_event))
throw SystemException("cannot signal named event", _name);
}
void NamedEventImpl::waitImpl()
{
switch (WaitForSingleObject(_event, INFINITE))
{
case WAIT_OBJECT_0:
return;
default:
throw SystemException("wait for named event failed", _name);
}
}
Foundation_END

View File

@@ -0,0 +1,80 @@
//
// NamedEvent_WIN32.cpp
//
// $Id: //poco/1.1.0/Foundation/src/NamedEvent_WIN32U.cpp#2 $
//
// Library: Foundation
// Package: Processes
// Module: NamedEvent
//
// 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 "Foundation/NamedEvent_WIN32U.h"
#include "Foundation/Exception.h"
#include "Foundation/UnicodeConverter.h"
Foundation_BEGIN
NamedEventImpl::NamedEventImpl(const std::string& name):
_name(name)
{
UnicodeConverter::toUTF16(_name, _uname);
_event = CreateEventW(NULL, FALSE, FALSE, _uname.c_str());
if (!_event)
throw SystemException("cannot create named event", _name);
}
NamedEventImpl::~NamedEventImpl()
{
CloseHandle(_event);
}
void NamedEventImpl::setImpl()
{
if (!SetEvent(_event))
throw SystemException("cannot signal named event", _name);
}
void NamedEventImpl::waitImpl()
{
switch (WaitForSingleObject(_event, INFINITE))
{
case WAIT_OBJECT_0:
return;
default:
throw SystemException("wait for named event failed", _name);
}
}
Foundation_END

View File

@@ -0,0 +1,65 @@
//
// NamedMutex.cpp
//
// $Id: //poco/1.1.0/Foundation/src/NamedMutex.cpp#2 $
//
// Library: Foundation
// Package: Processes
// Module: NamedMutex
//
// 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 "Foundation/NamedMutex.h"
#if defined(POCO_OS_FAMILY_WINDOWS) && defined(POCO_WIN32_UTF8)
#include "NamedMutex_WIN32U.cpp"
#elif defined(POCO_OS_FAMILY_WINDOWS)
#include "NamedMutex_WIN32.cpp"
#elif defined(POCO_OS_FAMILY_UNIX)
#include "NamedMutex_UNIX.cpp"
#else
#include "NamedMutex_VMS.cpp"
#endif
Foundation_BEGIN
NamedMutex::NamedMutex(const std::string& name):
NamedMutexImpl(name)
{
}
NamedMutex::~NamedMutex()
{
}
Foundation_END

View File

@@ -0,0 +1,173 @@
//
// NamedMutex_UNIX.cpp
//
// $Id: //poco/1.1.0/Foundation/src/NamedMutex_UNIX.cpp#2 $
//
// Library: Foundation
// Package: Processes
// Module: NamedMutex
//
// 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 "Foundation/NamedMutex_UNIX.h"
#include "Foundation/Exception.h"
#include <fcntl.h>
#include <sys/stat.h>
#if defined(sun) || defined(__APPLE__) || defined(__osf__)
#include <semaphore.h>
#else
#include <unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <errno.h>
#endif
Foundation_BEGIN
#if defined(linux) || defined(__CYGWIN__)
union semun
{
int val;
struct semid_ds* buf;
unsigned short int* array;
struct seminfo* __buf;
};
#elif defined(hpux)
union semun
{
int val;
struct semid_ds* buf;
ushort* array;
};
#endif
NamedMutexImpl::NamedMutexImpl(const std::string& name):
_name(name)
{
std::string fileName = getFileName();
#if defined(sun) || defined(__APPLE__) || defined(__osf__) || defined(__QNX__)
_sem = sem_open(fileName.c_str(), O_CREAT, S_IRWXU | S_IRWXG | S_IRWXO, 1);
if ((long) _sem == (long) SEM_FAILED)
throw SystemException("cannot create named mutex (sem_open() failed)", _name);
#else
int fd = open(fileName.c_str(), O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
if (fd != -1)
close(fd);
else
throw SystemException("cannot create named mutex (lockfile)", _name);
key_t key = ftok(fileName.c_str(), 0);
if (key == -1)
throw SystemException("cannot create named mutex (ftok() failed)", _name);
_semid = semget(key, 1, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH | IPC_CREAT | IPC_EXCL);
if (_semid >= 0)
{
union semun arg;
arg.val = 1;
semctl(_semid, 0, SETVAL, arg);
}
else if (errno == EEXIST)
{
_semid = semget(key, 1, 0);
}
else throw SystemException("cannot create named mutex (semget() failed)", _name);
#endif // defined(sun) || defined(__APPLE__) || defined(__osf__) || defined(__QNX__)
}
NamedMutexImpl::~NamedMutexImpl()
{
#if defined(sun) || defined(__APPLE__) || defined(__osf__) || defined(__QNX__)
sem_close(_sem);
#endif
}
void NamedMutexImpl::lockImpl()
{
#if defined(sun) || defined(__APPLE__) || defined(__osf__) || defined(__QNX__)
if (sem_wait(_sem) != 0)
throw SystemException("cannot lock named mutex", _name);
#else
struct sembuf op;
op.sem_num = 0;
op.sem_op = -1;
op.sem_flg = SEM_UNDO;
if (semop(_semid, &op, 1) != 0)
throw SystemException("cannot lock named mutex", _name);
#endif
}
bool NamedMutexImpl::tryLockImpl()
{
#if defined(sun) || defined(__APPLE__) || defined(__osf__) || defined(__QNX__)
return sem_trywait(_sem) == 0;
#else
struct sembuf op;
op.sem_num = 0;
op.sem_op = -1;
op.sem_flg = SEM_UNDO | IPC_NOWAIT;
return semop(_semid, &op, 1) == 0;
#endif
}
void NamedMutexImpl::unlockImpl()
{
#if defined(sun) || defined(__APPLE__) || defined(__osf__) || defined(__QNX__)
if (sem_post(_sem) != 0)
throw SystemException("cannot unlock named mutex", _name);
#else
struct sembuf op;
op.sem_num = 0;
op.sem_op = 1;
op.sem_flg = SEM_UNDO;
if (semop(_semid, &op, 1) != 0)
throw SystemException("cannot unlock named mutex", _name);
#endif
}
std::string NamedMutexImpl::getFileName()
{
#if defined(sun) || defined(__APPLE__) || defined(__QNX__)
std::string fn = "/";
#else
std::string fn = "/tmp/";
#endif
fn.append(_name);
fn.append(".mutex");
return fn;
}
Foundation_END

View File

@@ -0,0 +1,87 @@
//
// NamedMutex_VMS.cpp
//
// $Id: //poco/1.1.0/Foundation/src/NamedMutex_VMS.cpp#2 $
//
// Library: Foundation
// Package: Processes
// Module: NamedMutex
//
// 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 "Foundation/NamedMutex_VMS.h"
#include <starlet.h>
#include <iodef.h>
Foundation_BEGIN
NamedMutexImpl::NamedMutexImpl(const std::string& name):
_name(name)
{
_nameDesc.dsc$w_length = _name.length();
_nameDesc.dsc$b_dtype = DSC$K_DTYPE_T;
_nameDesc.dsc$b_class = DSC$K_CLASS_S;
_nameDesc.dsc$a_pointer = _name.data();
int status = sys$enqw(0, LCK$K_NLMODE, (struct _lksb*) &_lksb, 0, &_nameDesc, 0, 0, 0, 0, 0, 0);
if (status != 1)
throw SystemException("cannot create named mutex", _name);
}
NamedMutexImpl::~NamedMutexImpl()
{
sys$deq(m_lksb[1], 0, 0, 0);
}
void NamedMutexImpl::lockImpl()
{
int status = sys$enqw(0, LCK$K_EXMODE, (struct _lksb*) &_lksb, LCK$M_CONVERT, &_nameDesc, 0, 0, 0, 0, 0, 0);
if (status != 1)
throw SystemException("cannot lock named mutex", _name);
}
bool NamedMutexImpl::tryLockImpl()
{
int status = sys$enqw(0, LCK$K_EXMODE, (struct _lksb*) &_lksb, LCK$M_CONVERT | LCK$M_NOQUEUE, &_nameDesc, 0, 0, 0, 0, 0, 0);
return status == 1;
}
void NamedMutexImpl::unlockImpl()
{
int status = sys$enqw(0, LCK$K_NLMODE, (struct _lksb*) &_lksb, LCK$M_CONVERT, &_nameDesc, 0, 0, 0, 0, 0, 0);
if (status != 1)
throw SystemException("cannot unlock named mutex", _name);
}
Foundation_END

View File

@@ -0,0 +1,95 @@
//
// NamedMutex_WIN32.cpp
//
// $Id: //poco/1.1.0/Foundation/src/NamedMutex_WIN32.cpp#2 $
//
// Library: Foundation
// Package: Processes
// Module: NamedMutex
//
// 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 "Foundation/NamedMutex_WIN32.h"
#include "Foundation/Exception.h"
Foundation_BEGIN
NamedMutexImpl::NamedMutexImpl(const std::string& name):
_name(name)
{
_mutex = CreateMutex(NULL, FALSE, _name.c_str());
if (!_mutex)
throw SystemException("cannot create named mutex", _name);
}
NamedMutexImpl::~NamedMutexImpl()
{
CloseHandle(_mutex);
}
void NamedMutexImpl::lockImpl()
{
switch (WaitForSingleObject(_mutex, INFINITE))
{
case WAIT_OBJECT_0:
return;
case WAIT_ABANDONED:
throw SystemException("cannot lock named mutex (abadoned)", _name);
default:
throw SystemException("cannot lock named mutex", _name);
}
}
bool NamedMutexImpl::tryLockImpl()
{
switch (WaitForSingleObject(_mutex, 0))
{
case WAIT_OBJECT_0:
return true;
case WAIT_TIMEOUT:
return false;
case WAIT_ABANDONED:
throw SystemException("cannot lock named mutex (abadoned)", _name);
default:
throw SystemException("cannot lock named mutex", _name);
}
}
void NamedMutexImpl::unlockImpl()
{
ReleaseMutex(_mutex);
}
Foundation_END

View File

@@ -0,0 +1,97 @@
//
// NamedMutex_WIN32.cpp
//
// $Id: //poco/1.1.0/Foundation/src/NamedMutex_WIN32U.cpp#2 $
//
// Library: Foundation
// Package: Processes
// Module: NamedMutex
//
// 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 "Foundation/NamedMutex_WIN32U.h"
#include "Foundation/Exception.h"
#include "Foundation/UnicodeConverter.h"
Foundation_BEGIN
NamedMutexImpl::NamedMutexImpl(const std::string& name):
_name(name)
{
UnicodeConverter::toUTF16(_name, _uname);
_mutex = CreateMutexW(NULL, FALSE, _uname.c_str());
if (!_mutex)
throw SystemException("cannot create named mutex", _name);
}
NamedMutexImpl::~NamedMutexImpl()
{
CloseHandle(_mutex);
}
void NamedMutexImpl::lockImpl()
{
switch (WaitForSingleObject(_mutex, INFINITE))
{
case WAIT_OBJECT_0:
return;
case WAIT_ABANDONED:
throw SystemException("cannot lock named mutex (abadoned)", _name);
default:
throw SystemException("cannot lock named mutex", _name);
}
}
bool NamedMutexImpl::tryLockImpl()
{
switch (WaitForSingleObject(_mutex, 0))
{
case WAIT_OBJECT_0:
return true;
case WAIT_TIMEOUT:
return false;
case WAIT_ABANDONED:
throw SystemException("cannot lock named mutex (abadoned)", _name);
default:
throw SystemException("cannot lock named mutex", _name);
}
}
void NamedMutexImpl::unlockImpl()
{
ReleaseMutex(_mutex);
}
Foundation_END

View File

@@ -0,0 +1,146 @@
//
// NestedDiagnosticContext.cpp
//
// $Id: //poco/1.1.0/Foundation/src/NestedDiagnosticContext.cpp#2 $
//
// Library: Foundation
// Package: Core
// Module: NestedDiagnosticContext
//
// 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 "Foundation/NestedDiagnosticContext.h"
#include "Foundation/SingletonHolder.h"
#include "Foundation/ThreadLocal.h"
Foundation_BEGIN
NestedDiagnosticContext::NestedDiagnosticContext()
{
}
NestedDiagnosticContext::NestedDiagnosticContext(const NestedDiagnosticContext& ctx)
{
_stack = ctx._stack;
}
NestedDiagnosticContext::~NestedDiagnosticContext()
{
}
NestedDiagnosticContext& NestedDiagnosticContext::operator = (const NestedDiagnosticContext& ctx)
{
if (&ctx != this)
_stack = ctx._stack;
return *this;
}
void NestedDiagnosticContext::push(const std::string& info)
{
Context ctx;
ctx.info = info;
ctx.line = -1;
ctx.file = 0;
_stack.push_back(ctx);
}
void NestedDiagnosticContext::push(const std::string& info, int line, const char* filename)
{
Context ctx;
ctx.info = info;
ctx.line = line;
ctx.file = filename;
_stack.push_back(ctx);
}
void NestedDiagnosticContext::pop()
{
if (!_stack.empty())
_stack.pop_back();
}
int NestedDiagnosticContext::depth() const
{
return int(_stack.size());
}
std::string NestedDiagnosticContext::toString() const
{
std::string result;
for (Stack::const_iterator it = _stack.begin(); it != _stack.end(); ++it)
{
if (!result.empty())
result.append(":");
result.append(it->info);
}
return result;
}
void NestedDiagnosticContext::dump(std::ostream& ostr) const
{
dump(ostr, "\n");
}
void NestedDiagnosticContext::dump(std::ostream& ostr, const std::string& delimiter) const
{
for (Stack::const_iterator it = _stack.begin(); it != _stack.end(); ++it)
{
ostr << it->info;
if (it->file)
ostr << " (in \"" << it->file << "\", line " << it->line << ")";
ostr << delimiter;
}
}
void NestedDiagnosticContext::clear()
{
_stack.clear();
}
NestedDiagnosticContext& NestedDiagnosticContext::current()
{
static ThreadLocal<NestedDiagnosticContext> ndc;
return ndc.get();
}
Foundation_END

View File

@@ -0,0 +1,60 @@
//
// Notification.cpp
//
// $Id: //poco/1.1.0/Foundation/src/Notification.cpp#2 $
//
// Library: Foundation
// Package: Notifications
// Module: Notification
//
// 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 "Foundation/Notification.h"
#include <typeinfo>
Foundation_BEGIN
Notification::Notification()
{
}
Notification::~Notification()
{
}
std::string Notification::name() const
{
return typeid(*this).name();
}
Foundation_END

View File

@@ -0,0 +1,119 @@
//
// NotificationCenter.cpp
//
// $Id: //poco/1.1.0/Foundation/src/NotificationCenter.cpp#2 $
//
// Library: Foundation
// Package: Notifications
// Module: NotificationCenter
//
// 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 "Foundation/NotificationCenter.h"
#include "Foundation/Notification.h"
#include "Foundation/Observer.h"
#include "Foundation/AutoPtr.h"
#include "Foundation/SingletonHolder.h"
Foundation_BEGIN
NotificationCenter::NotificationCenter()
{
}
NotificationCenter::~NotificationCenter()
{
for (ObserverList::iterator it = _observers.begin(); it != _observers.end(); ++it)
{
delete *it;
}
}
void NotificationCenter::addObserver(const AbstractObserver& observer)
{
Mutex::ScopedLock lock(_mutex);
_observers.push_front(observer.clone());
}
void NotificationCenter::removeObserver(const AbstractObserver& observer)
{
Mutex::ScopedLock lock(_mutex);
for (ObserverList::iterator it = _observers.begin(); it != _observers.end(); ++it)
{
if (*it && observer.equals(**it))
{
delete *it;
*it = 0;
return;
}
}
}
void NotificationCenter::postNotification(Notification* pNotification)
{
poco_check_ptr (pNotification);
Mutex::ScopedLock lock(_mutex);
AutoPtr<Notification> pNf = pNotification;
ObserverList::iterator it = _observers.begin();
while (it != _observers.end())
{
ObserverList::iterator cur = it++;
if (*cur)
{
(*cur)->notify(pNotification);
}
else
{
_observers.erase(cur);
}
}
}
bool NotificationCenter::hasObservers() const
{
Mutex::ScopedLock lock(_mutex);
return !_observers.empty();
}
NotificationCenter& NotificationCenter::defaultCenter()
{
static SingletonHolder<NotificationCenter> sh;
return *sh.get();
}
Foundation_END

View File

@@ -0,0 +1,227 @@
//
// NotificationQueue.cpp
//
// $Id: //poco/1.1.0/Foundation/src/NotificationQueue.cpp#2 $
//
// Library: Foundation
// Package: Notifications
// Module: NotificationQueue
//
// 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 "Foundation/NotificationQueue.h"
#include "Foundation/NotificationCenter.h"
#include "Foundation/Notification.h"
#include "Foundation/SingletonHolder.h"
Foundation_BEGIN
NotificationQueue::NotificationQueue()
{
}
NotificationQueue::~NotificationQueue()
{
clear();
}
void NotificationQueue::enqueueNotification(Notification* pNotification)
{
poco_check_ptr (pNotification);
FastMutex::ScopedLock lock(_mutex);
if (_waitQueue.empty())
{
_nfQueue.push_back(pNotification);
}
else
{
WaitInfo* pWI = _waitQueue.front();
_waitQueue.pop_front();
pWI->pNf = pNotification;
pWI->nfAvailable.set();
}
}
void NotificationQueue::enqueueUrgentNotification(Notification* pNotification)
{
poco_check_ptr (pNotification);
FastMutex::ScopedLock lock(_mutex);
if (_waitQueue.empty())
{
_nfQueue.push_front(pNotification);
}
else
{
WaitInfo* pWI = _waitQueue.front();
_waitQueue.pop_front();
pWI->pNf = pNotification;
pWI->nfAvailable.set();
}
}
Notification* NotificationQueue::dequeueNotification()
{
FastMutex::ScopedLock lock(_mutex);
return dequeueOne();
}
Notification* NotificationQueue::waitDequeueNotification()
{
Notification* pNf = 0;
WaitInfo* pWI = 0;
{
FastMutex::ScopedLock lock(_mutex);
pNf = dequeueOne();
if (pNf) return pNf;
pWI = new WaitInfo;
pWI->pNf = 0;
_waitQueue.push_back(pWI);
}
pWI->nfAvailable.wait();
pNf = pWI->pNf;
delete pWI;
return pNf;
}
Notification* NotificationQueue::waitDequeueNotification(long milliseconds)
{
Notification* pNf = 0;
WaitInfo* pWI = 0;
{
FastMutex::ScopedLock lock(_mutex);
pNf = dequeueOne();
if (pNf) return pNf;
pWI = new WaitInfo;
pWI->pNf = 0;
_waitQueue.push_back(pWI);
}
if (pWI->nfAvailable.tryWait(milliseconds))
{
pNf = pWI->pNf;
}
else
{
FastMutex::ScopedLock lock(_mutex);
pNf = pWI->pNf;
for (WaitQueue::iterator it = _waitQueue.begin(); it != _waitQueue.end(); ++it)
{
if (*it == pWI)
{
_waitQueue.erase(it);
break;
}
}
}
delete pWI;
return pNf;
}
void NotificationQueue::dispatch(NotificationCenter& notificationCenter)
{
FastMutex::ScopedLock lock(_mutex);
Notification* pNf = dequeueOne();
while (pNf)
{
notificationCenter.postNotification(pNf);
pNf = dequeueOne();
}
}
void NotificationQueue::wakeUpAll()
{
FastMutex::ScopedLock lock(_mutex);
for (WaitQueue::iterator it = _waitQueue.begin(); it != _waitQueue.end(); ++it)
{
(*it)->nfAvailable.set();
}
_waitQueue.clear();
}
bool NotificationQueue::empty() const
{
FastMutex::ScopedLock lock(_mutex);
return _nfQueue.empty();
}
int NotificationQueue::size() const
{
FastMutex::ScopedLock lock(_mutex);
return int(_nfQueue.size());
}
void NotificationQueue::clear()
{
FastMutex::ScopedLock lock(_mutex);
for (NfQueue::iterator it = _nfQueue.begin(); it != _nfQueue.end(); ++it)
{
(*it)->release();
}
_nfQueue.clear();
}
bool NotificationQueue::hasIdleThreads() const
{
FastMutex::ScopedLock lock(_mutex);
return !_waitQueue.empty();
}
Notification* NotificationQueue::dequeueOne()
{
Notification* pNf = 0;
if (!_nfQueue.empty())
{
pNf = _nfQueue.front();
_nfQueue.pop_front();
}
return pNf;
}
NotificationQueue& NotificationQueue::defaultQueue()
{
static SingletonHolder<NotificationQueue> sh;
return *sh.get();
}
Foundation_END

View File

@@ -0,0 +1,63 @@
//
// NullChannel.cpp
//
// $Id: //poco/1.1.0/Foundation/src/NullChannel.cpp#2 $
//
// Library: Foundation
// Package: Logging
// Module: NullChannel
//
// 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 "Foundation/NullChannel.h"
Foundation_BEGIN
NullChannel::NullChannel()
{
}
NullChannel::~NullChannel()
{
}
void NullChannel::log(const Message&)
{
}
void NullChannel::setProperty(const std::string&, const std::string&)
{
}
Foundation_END

View File

@@ -0,0 +1,96 @@
//
// NullStream.cpp
//
// $Id: //poco/1.1.0/Foundation/src/NullStream.cpp#2 $
//
// Library: Foundation
// Package: Streams
// Module: NullStream
//
// 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 "Foundation/NullStream.h"
Foundation_BEGIN
NullStreamBuf::NullStreamBuf()
{
}
NullStreamBuf::~NullStreamBuf()
{
}
int NullStreamBuf::readFromDevice()
{
return -1;
}
int NullStreamBuf::writeToDevice(char c)
{
return charToInt(c);
}
NullIOS::NullIOS()
{
poco_ios_init(&_buf);
}
NullIOS::~NullIOS()
{
}
NullInputStream::NullInputStream(): std::istream(&_buf)
{
}
NullInputStream::~NullInputStream()
{
}
NullOutputStream::NullOutputStream(): std::ostream(&_buf)
{
}
NullOutputStream::~NullOutputStream()
{
}
Foundation_END

View File

@@ -0,0 +1,384 @@
//
// NumberFormatter.cpp
//
// $Id: //poco/1.1.0/Foundation/src/NumberFormatter.cpp#2 $
//
// Library: Foundation
// Package: Core
// Module: NumberFormatter
//
// 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 "Foundation/NumberFormatter.h"
#include <stdio.h>
#include <ctype.h>
#if defined(_MSC_VER)
#define I64_FMT "I64"
#elif defined(__APPLE__)
#define I64_FMT "q"
#else
#define I64_FMT "ll"
#endif
Foundation_BEGIN
std::string NumberFormatter::format(int value)
{
char buffer[64];
sprintf(buffer, "%d", value);
return std::string(buffer);
}
std::string NumberFormatter::format(int value, int width)
{
poco_assert (width > 0 && width < 64);
char buffer[64];
sprintf(buffer, "%*d", width, value);
return std::string(buffer);
}
std::string NumberFormatter::format0(int value, int width)
{
poco_assert (width > 0 && width < 64);
char buffer[64];
sprintf(buffer, "%0*d", width, value);
return std::string(buffer);
}
std::string NumberFormatter::formatHex(int value)
{
char buffer[64];
sprintf(buffer, "%X", value);
return std::string(buffer);
}
std::string NumberFormatter::formatHex(int value, int width)
{
poco_assert (width > 0 && width < 64);
char buffer[64];
sprintf(buffer, "%0*X", width, value);
return std::string(buffer);
}
std::string NumberFormatter::format(unsigned value)
{
char buffer[64];
sprintf(buffer, "%u", value);
return std::string(buffer);
}
std::string NumberFormatter::format(unsigned value, int width)
{
poco_assert (width > 0 && width < 64);
char buffer[64];
sprintf(buffer, "%*u", width, value);
return std::string(buffer);
}
std::string NumberFormatter::format0(unsigned int value, int width)
{
poco_assert (width > 0 && width < 64);
char buffer[64];
sprintf(buffer, "%0*u", width, value);
return std::string(buffer);
}
std::string NumberFormatter::formatHex(unsigned value)
{
char buffer[64];
sprintf(buffer, "%X", value);
return std::string(buffer);
}
std::string NumberFormatter::formatHex(unsigned value, int width)
{
poco_assert (width > 0 && width < 64);
char buffer[64];
sprintf(buffer, "%0*X", width, value);
return std::string(buffer);
}
std::string NumberFormatter::format(long value)
{
char buffer[64];
sprintf(buffer, "%ld", value);
return std::string(buffer);
}
std::string NumberFormatter::format(long value, int width)
{
poco_assert (width > 0 && width < 64);
char buffer[64];
sprintf(buffer, "%*ld", width, value);
return std::string(buffer);
}
std::string NumberFormatter::format0(long value, int width)
{
poco_assert (width > 0 && width < 64);
char buffer[64];
sprintf(buffer, "%0*ld", width, value);
return std::string(buffer);
}
std::string NumberFormatter::formatHex(long value)
{
char buffer[64];
sprintf(buffer, "%lX", value);
return std::string(buffer);
}
std::string NumberFormatter::formatHex(long value, int width)
{
poco_assert (width > 0 && width < 64);
char buffer[64];
sprintf(buffer, "%0*lX", width, value);
return std::string(buffer);
}
std::string NumberFormatter::format(unsigned long value)
{
char buffer[64];
sprintf(buffer, "%lu", value);
return std::string(buffer);
}
std::string NumberFormatter::format(unsigned long value, int width)
{
poco_assert (width > 0 && width < 64);
char buffer[64];
sprintf(buffer, "%*lu", width, value);
return std::string(buffer);
}
std::string NumberFormatter::format0(unsigned long value, int width)
{
poco_assert (width > 0 && width < 64);
char buffer[64];
sprintf(buffer, "%0*lu", width, value);
return std::string(buffer);
}
std::string NumberFormatter::formatHex(unsigned long value)
{
char buffer[64];
sprintf(buffer, "%lX", value);
return std::string(buffer);
}
std::string NumberFormatter::formatHex(unsigned long value, int width)
{
poco_assert (width > 0 && width < 64);
char buffer[64];
sprintf(buffer, "%0*lX", width, value);
return std::string(buffer);
}
#if defined(POCO_HAVE_INT64) && !defined(POCO_LONG_IS_64_BIT)
std::string NumberFormatter::format(Int64 value)
{
char buffer[64];
sprintf(buffer, "%"I64_FMT"d", value);
return std::string(buffer);
}
std::string NumberFormatter::format(Int64 value, int width)
{
poco_assert (width > 0 && width < 64);
char buffer[64];
sprintf(buffer, "%*"I64_FMT"d", width, value);
return std::string(buffer);
}
std::string NumberFormatter::format0(Int64 value, int width)
{
poco_assert (width > 0 && width < 64);
char buffer[64];
sprintf(buffer, "%0*"I64_FMT"d", width, value);
return std::string(buffer);
}
std::string NumberFormatter::formatHex(Int64 value)
{
char buffer[64];
sprintf(buffer, "%"I64_FMT"X", value);
return std::string(buffer);
}
std::string NumberFormatter::formatHex(Int64 value, int width)
{
poco_assert (width > 0 && width < 64);
char buffer[64];
sprintf(buffer, "%0*"I64_FMT"X", width, value);
return std::string(buffer);
}
std::string NumberFormatter::format(UInt64 value)
{
char buffer[64];
sprintf(buffer, "%"I64_FMT"u", value);
return std::string(buffer);
}
std::string NumberFormatter::format(UInt64 value, int width)
{
poco_assert (width > 0 && width < 64);
char buffer[64];
sprintf(buffer, "%*"I64_FMT"u", width, value);
return std::string(buffer);
}
std::string NumberFormatter::format0(UInt64 value, int width)
{
poco_assert (width > 0 && width < 64);
char buffer[64];
sprintf(buffer, "%0*"I64_FMT"u", width, value);
return std::string(buffer);
}
std::string NumberFormatter::formatHex(UInt64 value)
{
char buffer[64];
sprintf(buffer, "%"I64_FMT"X", value);
return std::string(buffer);
}
std::string NumberFormatter::formatHex(UInt64 value, int width)
{
poco_assert (width > 0 && width < 64);
char buffer[64];
sprintf(buffer, "%0*"I64_FMT"X", width, value);
return std::string(buffer);
}
#endif // defined(POCO_HAVE_INT64) && !defined(POCO_LONG_IS_64_BIT)
std::string NumberFormatter::format(float value)
{
char buffer[64];
sprintf(buffer, "%.*g", 10, (double) value);
return std::string(buffer);
}
std::string NumberFormatter::format(double value)
{
char buffer[64];
sprintf(buffer, "%.*g", 20, value);
return std::string(buffer);
}
std::string NumberFormatter::format(double value, int precision)
{
poco_assert (precision >= 0 && precision < 32);
char buffer[64];
sprintf(buffer, "%.*f", precision, value);
return std::string(buffer);
}
std::string NumberFormatter::format(double value, int width, int precision)
{
poco_assert (width > 0 && width < 64 && precision >= 0 && precision < width);
char buffer[64];
sprintf(buffer, "%*.*f", width, precision, value);
return std::string(buffer);
}
std::string NumberFormatter::format(const void* ptr)
{
char buffer[24];
#if defined(POCO_PTR_IS_64_BIT)
sprintf(buffer, "%016"I64_FMT"X", (UIntPtr) ptr);
#else
sprintf(buffer, "%08lX", (UIntPtr) ptr);
#endif
return std::string(buffer);
}
Foundation_END

View File

@@ -0,0 +1,173 @@
//
// NumberParser.cpp
//
// $Id: //poco/1.1.0/Foundation/src/NumberParser.cpp#2 $
//
// Library: Foundation
// Package: Core
// Module: NumberParser
//
// 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 "Foundation/NumberParser.h"
#include "Foundation/Exception.h"
#include <stdio.h>
#include <ctype.h>
#if defined(_MSC_VER)
#define I64_FMT "I64"
#elif defined(__APPLE__)
#define I64_FMT "q"
#else
#define I64_FMT "ll"
#endif
Foundation_BEGIN
int NumberParser::parse(const std::string& s)
{
int result;
if (tryParse(s, result))
return result;
else
throw SyntaxException("Not a valid integer", s);
}
bool NumberParser::tryParse(const std::string& s, int& value)
{
return sscanf(s.c_str(), "%d", &value) == 1;
}
unsigned NumberParser::parseUnsigned(const std::string& s)
{
unsigned result;
if (tryParseUnsigned(s, result))
return result;
else
throw SyntaxException("Not a valid unsigned integer", s);
}
bool NumberParser::tryParseUnsigned(const std::string& s, unsigned& value)
{
return sscanf(s.c_str(), "%u", &value) == 1;
}
unsigned NumberParser::parseHex(const std::string& s)
{
unsigned result;
if (tryParseHex(s, result))
return result;
else
throw SyntaxException("Not a valid hexadecimal integer", s);
}
bool NumberParser::tryParseHex(const std::string& s, unsigned& value)
{
return sscanf(s.c_str(), "%x", &value) == 1;
}
#if defined(POCO_HAVE_INT64)
Int64 NumberParser::parse64(const std::string& s)
{
Int64 result;
if (tryParse64(s, result))
return result;
else
throw SyntaxException("Not a valid integer", s);
}
bool NumberParser::tryParse64(const std::string& s, Int64& value)
{
return sscanf(s.c_str(), "%"I64_FMT"d", &value) == 1;
}
UInt64 NumberParser::parseUnsigned64(const std::string& s)
{
UInt64 result;
if (tryParseUnsigned64(s, result))
return result;
else
throw SyntaxException("Not a valid unsigned integer", s);
}
bool NumberParser::tryParseUnsigned64(const std::string& s, UInt64& value)
{
return sscanf(s.c_str(), "%"I64_FMT"u", &value) == 1;
}
UInt64 NumberParser::parseHex64(const std::string& s)
{
UInt64 result;
if (tryParseHex64(s, result))
return result;
else
throw SyntaxException("Not a valid hexadecimal integer", s);
}
bool NumberParser::tryParseHex64(const std::string& s, UInt64& value)
{
return sscanf(s.c_str(), "%"I64_FMT"x", &value) == 1;
}
#endif // defined(POCO_HAVE_INT64)
double NumberParser::parseFloat(const std::string& s)
{
double result;
if (tryParseFloat(s, result))
return result;
else
throw SyntaxException("Not a valid floating-point number", s);
}
bool NumberParser::tryParseFloat(const std::string& s, double& value)
{
return sscanf(s.c_str(), "%lf", &value) == 1;
}
Foundation_END

View File

@@ -0,0 +1,64 @@
//
// Observer.cpp
//
// $Id: //poco/1.1.0/Foundation/src/Observer.cpp#2 $
//
// Library: Foundation
// Package: Notifications
// Module: NotificationCenter
//
// 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 "Foundation/Observer.h"
Foundation_BEGIN
AbstractObserver::AbstractObserver()
{
}
AbstractObserver::AbstractObserver(const AbstractObserver& observer)
{
}
AbstractObserver::~AbstractObserver()
{
}
AbstractObserver& AbstractObserver::operator = (const AbstractObserver& observer)
{
return *this;
}
Foundation_END

View File

@@ -0,0 +1,199 @@
//
// OpcomChannel.cpp
//
// $Id: //poco/1.1.0/Foundation/src/OpcomChannel.cpp#2 $
//
// Library: Foundation
// Package: Logging
// Module: OpcomChannel
//
// 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 "Foundation/OpcomChannel.h"
#include "Foundation/Message.h"
#include <starlet.h>
#include <opcdef.h>
#include <descrip.h>
Foundation_BEGIN
const std::string OpcomChannel::PROP_TARGET = "target";
OpcomChannel::OpcomChannel(): _target(OPC$M_NM_CENTRL)
{
}
OpcomChannel::OpcomChannel(int target): _target(target)
{
}
OpcomChannel::~OpcomChannel()
{
}
void OpcomChannel::log(const Message& msg)
{
const std::string& text = msg.getText();
// set up OPC buffer
struct _opcdef buffer;
buffer.opc$b_ms_type = OPC$_RQ_RQST;
buffer.opc$b_ms_target = _target;
buffer.opc$l_ms_rqstid = 0;
int len = text.size();
// restrict message text to 128 chars
if (len > 128) len = 128;
// copy message text into buffer
memcpy(&buffer.opc$l_ms_text, text.data(), len);
// sys$sndopr only accepts 32-bit pointers
#pragma pointer_size save
#pragma pointer_size 32
// set up the descriptor
struct dsc$descriptor bufferDsc;
bufferDsc.dsc$w_length = len + 8;
bufferDsc.dsc$a_pointer = (char*) &buffer;
// call the system service
sys$sndopr(&bufferDsc, 0);
#pragma pointer_size restore
}
void OpcomChannel::setProperty(const std::string& name, const std::string& value)
{
if (name == PROP_TARGET)
{
if (value == "CARDS")
_target = OPC$M_NM_CARDS;
else if (value == "CENTRL")
_target = OPC$M_NM_CENTRL;
else if (value == "CLUSTER")
_target = OPC$M_NM_CLUSTER;
else if (value == "DEVICE")
_target = OPC$M_NM_DEVICE;
else if (value == "DISKS")
_target = OPC$M_NM_DISKS;
else if (value == "NTWORK")
_target = OPC$M_NM_NTWORK;
else if (value == "TAPES")
_target = OPC$M_NM_TAPES;
else if (value == "PRINT")
_target = OPC$M_NM_PRINT;
else if (value == "SECURITY")
_target = OPC$M_NM_SECURITY;
else if (value == "OPER1")
_target = OPC$M_NM_OPER1;
else if (value == "OPER2")
_target = OPC$M_NM_OPER2;
else if (value == "OPER3")
_target = OPC$M_NM_OPER3;
else if (value == "OPER4")
_target = OPC$M_NM_OPER4;
else if (value == "OPER5")
_target = OPC$M_NM_OPER5;
else if (value == "OPER6")
_target = OPC$M_NM_OPER6;
else if (value == "OPER7")
_target = OPC$M_NM_OPER7;
else if (value == "OPER8")
_target = OPC$M_NM_OPER8;
else if (value == "OPER9")
_target = OPC$M_NM_OPER9;
else if (value == "OPER10")
_target = OPC$M_NM_OPER10;
else if (value == "OPER11")
_target = OPC$M_NM_OPER11;
else if (value == "OPER12")
_target = OPC$M_NM_OPER12;
}
else
{
Channel::setProperty(name, value);
}
}
std::string OpcomChannel::getProperty(const std::string& name) const
{
if (name == PROP_TARGET)
{
if (_target == OPC$M_NM_CARDS)
return "CARDS";
else if (_target == OPC$M_NM_CENTRL)
return "CENTRL";
else if (_target == OPC$M_NM_CLUSTER)
return "CLUSTER";
else if (_target == OPC$M_NM_DEVICE)
return "DEVICE";
else if (_target == OPC$M_NM_DISKS)
return "DISKS";
else if (_target == OPC$M_NM_NTWORK)
return "NTWORK";
else if (_target == OPC$M_NM_TAPES)
return "TAPES";
else if (_target == OPC$M_NM_PRINT)
return "PRINT";
else if (_target == OPC$M_NM_SECURITY)
return "SECURITY";
else if (_target == OPC$M_NM_OPER1)
return "OPER1";
else if (_target == OPC$M_NM_OPER2)
return "OPER2";
else if (_target == OPC$M_NM_OPER3)
return "OPER3";
else if (_target == OPC$M_NM_OPER4)
return "OPER4";
else if (_target == OPC$M_NM_OPER5)
return "OPER5";
else if (_target == OPC$M_NM_OPER6)
return "OPER6";
else if (_target == OPC$M_NM_OPER7)
return "OPER7";
else if (_target == OPC$M_NM_OPER8)
return "OPER8";
else if (_target == OPC$M_NM_OPER9)
return "OPER9";
else if (_target == OPC$M_NM_OPER10)
return "OPER10";
else if (_target == OPC$M_NM_OPER11)
return "OPER11";
else if (_target == OPC$M_NM_OPER12)
return "OPER12";
}
return Channel::getProperty(name);
}
Foundation_END

987
Foundation/src/Path.cpp Normal file
View File

@@ -0,0 +1,987 @@
//
// Path.cpp
//
// $Id: //poco/1.1.0/Foundation/src/Path.cpp#2 $
//
// Library: Foundation
// Package: Filesystem
// Module: Path
//
// 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 "Foundation/Path.h"
#include "Foundation/File.h"
#include "Foundation/Exception.h"
#include "Foundation/StringTokenizer.h"
#include <algorithm>
#if defined(POCO_OS_FAMILY_VMS)
#include "Path_VMS.cpp"
#elif defined(POCO_OS_FAMILY_UNIX)
#include "Path_UNIX.cpp"
#elif defined(POCO_OS_FAMILY_WINDOWS) && defined(POCO_WIN32_UTF8)
#include "Path_WIN32U.cpp"
#elif defined(POCO_OS_FAMILY_WINDOWS)
#include "Path_WIN32.cpp"
#endif
Foundation_BEGIN
Path::Path(): _absolute(false)
{
}
Path::Path(bool absolute): _absolute(absolute)
{
}
Path::Path(const std::string& path)
{
assign(path);
}
Path::Path(const std::string& path, Style style)
{
assign(path, style);
}
Path::Path(const char* path)
{
poco_check_ptr(path);
assign(path);
}
Path::Path(const char* path, Style style)
{
poco_check_ptr(path);
assign(path, style);
}
Path::Path(const Path& path):
_node(path._node),
_device(path._device),
_name(path._name),
_version(path._version),
_dirs(path._dirs),
_absolute(path._absolute)
{
}
Path::Path(const Path& parent, const std::string& fileName):
_node(parent._node),
_device(parent._device),
_name(parent._name),
_version(parent._version),
_dirs(parent._dirs),
_absolute(parent._absolute)
{
makeDirectory();
_name = fileName;
}
Path::Path(const Path& parent, const Path& relative):
_node(parent._node),
_device(parent._device),
_name(parent._name),
_version(parent._version),
_dirs(parent._dirs),
_absolute(parent._absolute)
{
resolve(relative);
}
Path::~Path()
{
}
Path& Path::operator = (const Path& path)
{
return assign(path);
}
Path& Path::operator = (const std::string& path)
{
return assign(path);
}
Path& Path::operator = (const char* path)
{
poco_check_ptr(path);
return assign(path);
}
void Path::swap(Path& path)
{
std::swap(_node, path._node);
std::swap(_device, path._device);
std::swap(_name, path._name);
std::swap(_version, path._version);
std::swap(_dirs, path._dirs);
std::swap(_absolute, path._absolute);
}
Path& Path::assign(const Path& path)
{
if (&path != this)
{
_node = path._node;
_device = path._device;
_name = path._name;
_version = path._version;
_dirs = path._dirs;
_absolute = path._absolute;
}
return *this;
}
Path& Path::assign(const std::string& path)
{
#if defined(POCO_OS_FAMILY_VMS)
parseVMS(path);
#elif defined(POCO_OS_FAMILY_WINDOWS)
parseWindows(path);
#else
parseUnix(path);
#endif
return *this;
}
Path& Path::assign(const std::string& path, Style style)
{
switch (style)
{
case PATH_UNIX:
parseUnix(path);
break;
case PATH_WINDOWS:
parseWindows(path);
break;
case PATH_VMS:
parseVMS(path);
break;
case PATH_NATIVE:
assign(path);
break;
case PATH_GUESS:
parseGuess(path);
break;
default:
poco_bugcheck();
}
return *this;
}
Path& Path::assign(const char* path)
{
return assign(std::string(path));
}
std::string Path::toString() const
{
#if defined(POCO_OS_FAMILY_UNIX)
return buildUnix();
#elif defined(POCO_OS_FAMILY_WINDOWS)
return buildWindows();
#else
return buildVMS();
#endif
}
std::string Path::toString(Style style) const
{
switch (style)
{
case PATH_UNIX:
return buildUnix();
case PATH_WINDOWS:
return buildWindows();
case PATH_VMS:
return buildVMS();
case PATH_NATIVE:
case PATH_GUESS:
return toString();
default:
poco_bugcheck();
}
return std::string();
}
bool Path::tryParse(const std::string& path)
{
try
{
Path p;
p.parse(path);
assign(p);
return true;
}
catch (...)
{
return false;
}
}
bool Path::tryParse(const std::string& path, Style style)
{
try
{
Path p;
p.parse(path, style);
assign(p);
return true;
}
catch (...)
{
return false;
}
}
Path& Path::parseDirectory(const std::string& path)
{
assign(path);
return makeDirectory();
}
Path& Path::parseDirectory(const std::string& path, Style style)
{
assign(path, style);
return makeDirectory();
}
Path& Path::makeDirectory()
{
#if defined(POCO_OS_FAMILY_VMS)
pushDirectory(getBaseName());
#else
pushDirectory(_name);
#endif
_name.clear();
_version.clear();
return *this;
}
Path& Path::makeFile()
{
if (!_dirs.empty() && _name.empty())
{
_name = _dirs.back();
_dirs.pop_back();
#if defined(POCO_OS_FAMILY_VMS)
setExtension("DIR");
#endif
}
return *this;
}
Path& Path::makeAbsolute()
{
return makeAbsolute(current());
}
Path& Path::makeAbsolute(const Path& base)
{
if (!_absolute)
{
Path tmp = base;
tmp.makeDirectory();
for (StringVec::const_iterator it = _dirs.begin(); it != _dirs.end(); ++it)
{
tmp.pushDirectory(*it);
}
_node = tmp._node;
_device = tmp._device;
_dirs = tmp._dirs;
_absolute = base._absolute;
}
return *this;
}
Path Path::absolute() const
{
Path result(*this);
if (!result._absolute)
{
result.makeAbsolute();
}
return result;
}
Path Path::absolute(const Path& base) const
{
Path result(*this);
if (!result._absolute)
{
result.makeAbsolute(base);
}
return result;
}
Path Path::parent() const
{
Path p(*this);
return p.makeParent();
}
Path& Path::makeParent()
{
if (_name.empty())
{
if (_dirs.empty())
{
if (!_absolute)
_dirs.push_back("..");
}
else
{
if (_dirs.back() == "..")
_dirs.push_back("..");
else
_dirs.pop_back();
}
}
else
{
_name.clear();
_version.clear();
}
return *this;
}
Path& Path::append(const Path& path)
{
makeDirectory();
_dirs.insert(_dirs.end(), path._dirs.begin(), path._dirs.end());
_name = path._name;
_version = path._version;
return *this;
}
Path& Path::resolve(const Path& path)
{
if (path.isAbsolute())
{
assign(path);
}
else
{
for (int i = 0; i < path.depth(); ++i)
pushDirectory(path[i]);
_name = path._name;
}
return *this;
}
void Path::setNode(const std::string& node)
{
_node = node;
_absolute = _absolute || !node.empty();
}
void Path::setDevice(const std::string& device)
{
_device = device;
_absolute = _absolute || !device.empty();
}
const std::string& Path::directory(int n) const
{
poco_assert (0 <= n && n <= _dirs.size());
if (n < _dirs.size())
return _dirs[n];
else
return _name;
}
const std::string& Path::operator [] (int n) const
{
poco_assert (0 <= n && n <= _dirs.size());
if (n < _dirs.size())
return _dirs[n];
else
return _name;
}
void Path::pushDirectory(const std::string& dir)
{
if (!dir.empty() && dir != ".")
{
#if defined(POCO_OS_FAMILY_VMS)
if (dir == ".." || dir == "-")
{
if (!_dirs.empty() && _dirs.back() != ".." && _dirs.back() != "-")
_dirs.pop_back();
else if (!_absolute)
_dirs.push_back(dir);
}
else _dirs.push_back(dir);
#else
if (dir == "..")
{
if (!_dirs.empty() && _dirs.back() != "..")
_dirs.pop_back();
else if (!_absolute)
_dirs.push_back(dir);
}
else _dirs.push_back(dir);
#endif
}
}
void Path::popDirectory()
{
poco_assert (!_dirs.empty());
_dirs.pop_back();
}
void Path::setFileName(const std::string& name)
{
_name = name;
}
void Path::setBaseName(const std::string& name)
{
std::string ext = getExtension();
_name = name;
if (!ext.empty())
{
_name.append(".");
_name.append(ext);
}
}
std::string Path::getBaseName() const
{
std::string::size_type pos = _name.rfind('.');
if (pos != std::string::npos)
return _name.substr(0, pos);
else
return _name;
}
void Path::setExtension(const std::string& extension)
{
_name = getBaseName();
if (!extension.empty())
{
_name.append(".");
_name.append(extension);
}
}
std::string Path::getExtension() const
{
std::string::size_type pos = _name.rfind('.');
if (pos != std::string::npos)
return _name.substr(pos + 1);
else
return std::string();
}
void Path::clear()
{
_node.clear();
_device.clear();
_name.clear();
_dirs.clear();
_version.clear();
_absolute = false;
}
std::string Path::current()
{
return PathImpl::currentImpl();
}
std::string Path::home()
{
return PathImpl::homeImpl();
}
std::string Path::temp()
{
return PathImpl::tempImpl();
}
std::string Path::null()
{
return PathImpl::nullImpl();
}
std::string Path::expand(const std::string& path)
{
return PathImpl::expandImpl(path);
}
void Path::listRoots(std::vector<std::string>& roots)
{
PathImpl::listRootsImpl(roots);
}
bool Path::find(StringVec::const_iterator it, StringVec::const_iterator end, const std::string& name, Path& path)
{
while (it != end)
{
Path p(*it);
p.makeDirectory();
p.resolve(Path(name));
File f(p);
if (f.exists())
{
path = p;
return true;
}
++it;
}
return false;
}
bool Path::find(const std::string& pathList, const std::string& name, Path& path)
{
StringTokenizer st(pathList, std::string(1, pathSeparator()), StringTokenizer::TOK_IGNORE_EMPTY + StringTokenizer::TOK_TRIM);
return find(st.begin(), st.end(), name, path);
}
void Path::parseUnix(const std::string& path)
{
clear();
std::string::const_iterator it = path.begin();
std::string::const_iterator end = path.end();
if (it != end)
{
if (*it == '/')
{
_absolute = true; ++it;
}
else if (*it == '~')
{
++it;
if (it == end || *it == '/')
{
Path cwd(home());
_dirs = cwd._dirs;
_absolute = true;
}
else --it;
}
while (it != end)
{
std::string name;
while (it != end && *it != '/') name += *it++;
if (it != end)
{
if (_dirs.empty())
{
if (!name.empty() && *(name.rbegin()) == ':')
_device.assign(name, 0, name.length() - 1);
else
pushDirectory(name);
}
else pushDirectory(name);
}
else _name = name;
if (it != end) ++it;
}
}
}
void Path::parseWindows(const std::string& path)
{
clear();
std::string::const_iterator it = path.begin();
std::string::const_iterator end = path.end();
if (it != end)
{
if (*it == '\\' || *it == '/') { _absolute = true; ++it; }
if (_absolute && it != end && (*it == '\\' || *it == '/')) // UNC
{
++it;
while (it != end && *it != '\\' && *it != '/') _node += *it++;
if (it != end) ++it;
}
else if (it != end)
{
char d = *it++;
if (it != end && *it == ':') // drive letter
{
if (_absolute || !(d >= 'a' && d <= 'z' || d >= 'A' && d <= 'Z')) throw PathSyntaxException(path);
_absolute = true;
_device += d;
++it;
if (it == end || *it != '\\' && *it != '/') throw PathSyntaxException(path);
++it;
}
else --it;
}
while (it != end)
{
std::string name;
while (it != end && *it != '\\' && *it != '/') name += *it++;
if (it != end)
pushDirectory(name);
else
_name = name;
if (it != end) ++it;
}
}
if (!_node.empty() && _dirs.empty() && !_name.empty())
makeDirectory();
}
void Path::parseVMS(const std::string& path)
{
clear();
std::string::const_iterator it = path.begin();
std::string::const_iterator end = path.end();
if (it != end)
{
std::string name;
while (it != end && *it != ':' && *it != '[' && *it != ';') name += *it++;
if (it != end)
{
if (*it == ':')
{
++it;
if (it != end && *it == ':')
{
_node = name;
++it;
}
else _device = name;
_absolute = true;
name.clear();
}
if (it != end)
{
if (_device.empty() && *it != '[')
{
while (it != end && *it != ':' && *it != ';') name += *it++;
if (it != end)
{
if (*it == ':')
{
_device = name;
_absolute = true;
name.clear();
++it;
}
}
}
}
if (name.empty())
{
if (it != end && *it == '[')
{
++it;
if (it != end)
{
_absolute = true;
if (*it == '.')
{ _absolute = false; ++it; }
else if (*it == ']' || *it == '-')
_absolute = false;
while (it != end && *it != ']')
{
name.clear();
if (*it == '-')
name = "-";
else
while (it != end && *it != '.' && *it != ']') name += *it++;
if (!name.empty())
{
if (name == "-")
{
if (_dirs.empty() || _dirs.back() == "..")
_dirs.push_back("..");
else
_dirs.pop_back();
}
else _dirs.push_back(name);
}
if (it != end && *it != ']') ++it;
}
if (it == end) throw PathSyntaxException(path);
++it;
if (it != end && *it == '[')
{
if (!_absolute) throw PathSyntaxException(path);
++it;
if (it != end && *it == '.') throw PathSyntaxException(path);
int d = int(_dirs.size());
while (it != end && *it != ']')
{
name.clear();
if (*it == '-')
name = "-";
else
while (it != end && *it != '.' && *it != ']') name += *it++;
if (!name.empty())
{
if (name == "-")
{
if (_dirs.size() > d)
_dirs.pop_back();
}
else _dirs.push_back(name);
}
if (it != end && *it != ']') ++it;
}
if (it == end) throw PathSyntaxException(path);
++it;
}
}
_name.clear();
}
while (it != end && *it != ';') _name += *it++;
}
else _name = name;
if (it != end && *it == ';')
{
++it;
while (it != end) _version += *it++;
}
}
else _name = name;
}
}
void Path::parseGuess(const std::string& path)
{
bool hasBackslash = false;
bool hasSlash = false;
bool hasOpenBracket = false;
bool hasClosBracket = false;
bool isWindows = path.length() > 2 && path[1] == ':' && (path[2] == '/' || path[2] == '\\');
std::string::const_iterator end = path.end();
std::string::const_iterator semiIt = end;
if (!isWindows)
{
for (std::string::const_iterator it = path.begin(); it != end; ++it)
{
switch (*it)
{
case '\\': hasBackslash = true; break;
case '/': hasSlash = true; break;
case '[': hasOpenBracket = true;
case ']': hasClosBracket = hasOpenBracket;
case ';': semiIt = it; break;
}
}
}
if (hasBackslash || isWindows)
{
parseWindows(path);
}
else if (hasSlash)
{
parseUnix(path);
}
else
{
bool isVMS = hasClosBracket;
if (!isVMS && semiIt != end)
{
isVMS = true;
++semiIt;
while (semiIt != end)
{
if (*semiIt < '0' || *semiIt > '9')
{
isVMS = false; break;
}
++semiIt;
}
}
if (isVMS)
parseVMS(path);
else
parseUnix(path);
}
}
std::string Path::buildUnix() const
{
std::string result;
if (!_device.empty())
{
result.append("/");
result.append(_device);
result.append(":/");
}
else if (_absolute)
{
result.append("/");
}
for (StringVec::const_iterator it = _dirs.begin(); it != _dirs.end(); ++it)
{
result.append(*it);
result.append("/");
}
result.append(_name);
return result;
}
std::string Path::buildWindows() const
{
std::string result;
if (!_node.empty())
{
result.append("\\\\");
result.append(_node);
result.append("\\");
}
else if (!_device.empty())
{
result.append(_device);
result.append(":\\");
}
else if (_absolute)
{
result.append("\\");
}
for (StringVec::const_iterator it = _dirs.begin(); it != _dirs.end(); ++it)
{
result.append(*it);
result.append("\\");
}
result.append(_name);
return result;
}
std::string Path::buildVMS() const
{
std::string result;
if (!_node.empty())
{
result.append(_node);
result.append("::");
}
if (!_device.empty())
{
result.append(_device);
result.append(":");
}
if (!_dirs.empty())
{
result.append("[");
if (!_absolute && _dirs[0] != "..")
result.append(".");
for (StringVec::const_iterator it = _dirs.begin(); it != _dirs.end(); ++it)
{
if (it != _dirs.begin() && *it != "..")
result.append(".");
if (*it == "..")
result.append("-");
else
result.append(*it);
}
result.append("]");
}
result.append(_name);
if (!_version.empty())
{
result.append(";");
result.append(_version);
}
return result;
}
Foundation_END

View File

@@ -0,0 +1,162 @@
//
// Path_UNIX.cpp
//
// $Id: //poco/1.1.0/Foundation/src/Path_UNIX.cpp#2 $
//
// Library: Foundation
// Package: Filesystem
// Module: Path
//
// 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 "Foundation/Path_UNIX.h"
#include "Foundation/Exception.h"
#include "Foundation/Environment_UNIX.h"
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <pwd.h>
#include <ctype.h>
#include <limits.h>
#include <locale>
#ifndef PATH_MAX
#define PATH_MAX 1024 // fallback
#endif
Foundation_BEGIN
std::string PathImpl::currentImpl()
{
std::string path;
char cwd[PATH_MAX];
if (getcwd(cwd, sizeof(cwd)))
path = cwd;
else
throw SystemException("cannot get current directory");
std::string::size_type n = path.size();
if (n > 0 && path[n - 1] != '/') path.append("/");
return path;
}
std::string PathImpl::homeImpl()
{
std::string path;
struct passwd* pwd = getpwuid(getuid());
if (pwd)
path = pwd->pw_dir;
else
{
pwd = getpwuid(geteuid());
if (pwd)
path = pwd->pw_dir;
else
path = EnvironmentImpl::getImpl("HOME");
}
std::string::size_type n = path.size();
if (n > 0 && path[n - 1] != '/') path.append("/");
return path;
}
std::string PathImpl::tempImpl()
{
std::string path;
char* tmp = getenv("TMPDIR");
if (tmp)
{
path = tmp;
std::string::size_type n = path.size();
if (n > 0 && path[n - 1] != '/') path.append("/");
}
else
{
path = "/tmp/";
}
return path;
}
std::string PathImpl::nullImpl()
{
return "/dev/null";
}
std::string PathImpl::expandImpl(const std::string& path)
{
std::locale loc;
std::string result;
std::string::const_iterator it = path.begin();
std::string::const_iterator end = path.end();
if (it != end && *it == '~')
{
++it;
if (it != end && *it == '/')
{
result += homeImpl(); ++it;
}
else result += '~';
}
while (it != end)
{
if (*it == '$')
{
std::string var;
++it;
if (it != end && *it == '{')
{
++it;
while (it != end && *it != '}') var += *it++;
if (it != end) ++it;
}
else
{
while (it != end && (isalnum(*it, loc) || *it == '_')) var += *it++;
}
char* val = getenv(var.c_str());
if (val) result += val;
}
else result += *it++;
}
return result;
}
void PathImpl::listRootsImpl(std::vector<std::string>& roots)
{
roots.clear();
roots.push_back("/");
}
Foundation_END

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