code
stringlengths
1
2.01M
repo_name
stringlengths
3
62
path
stringlengths
1
267
language
stringclasses
231 values
license
stringclasses
13 values
size
int64
1
2.01M
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <log4cxx/logstring.h> #include <log4cxx/spi/configurator.h> #include <assert.h> #include <log4cxx/logger.h> using namespace log4cxx; using namespace log4cxx::spi; IMPLEMENT_LOG4CXX_OBJECT(Configurator) Configurator::Configurator() { }
001-log4cxx
trunk/src/main/cpp/configurator.cpp
C++
asf20
1,054
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <log4cxx/logstring.h> #include <log4cxx/rolling/filerenameaction.h> using namespace log4cxx; using namespace log4cxx::rolling; using namespace log4cxx::helpers; IMPLEMENT_LOG4CXX_OBJECT(FileRenameAction) FileRenameAction::FileRenameAction(const File& toRename, const File& renameTo, bool renameEmptyFile1) : source(toRename), destination(renameTo), renameEmptyFile(renameEmptyFile1) { } bool FileRenameAction::execute(log4cxx::helpers::Pool& pool1) const { return source.renameTo(destination, pool1); }
001-log4cxx
trunk/src/main/cpp/filerenameaction.cpp
C++
asf20
1,333
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <log4cxx/logstring.h> #include <log4cxx/stream.h> #include <log4cxx/helpers/transcoder.h> #if !defined(LOG4CXX) #define LOG4CXX 1 #endif #include <log4cxx/private/log4cxx_private.h> using namespace log4cxx; logstream_base::logstream_ios_base::logstream_ios_base(std::ios_base::fmtflags initval, int initsize) { #if LOG4CXX_MEMSET_IOS_BASE // // the destructor for std::ios_base in the MSVC STL // releases a pointer that was not initialized in the constructor. // memset(this, 0, sizeof(*this)); #endif flags(initval); precision(initsize); width(initsize); } logstream_base::logstream_base(const LoggerPtr& log, const LevelPtr& lvl) : initset((std::ios_base::fmtflags) -1, 1), initclear((std::ios_base::fmtflags) 0, 0), fillchar(0), fillset(false), logger(log), level(lvl), location() { enabled = logger->isEnabledFor(level); } logstream_base::~logstream_base() { } void logstream_base::insert(std::ios_base& (*manip)(std::ios_base&)) { get_stream_state(initclear, initset, fillchar, fillset); (*manip)(initset); (*manip)(initclear); refresh_stream_state(); } bool logstream_base::set_stream_state(std::ios_base& dest, int& dstchar) { std::ios_base::fmtflags setval = initset.flags(); std::ios_base::fmtflags clrval = initclear.flags(); std::ios_base::fmtflags mask = setval ^ (~clrval); dest.setf(clrval, mask); if (initset.precision() == initclear.precision()) { dest.precision(initset.precision()); } if (initset.width() == initclear.width()) { dest.width(initset.width()); } dstchar = fillchar; return fillset; } logstream_base& logstream_base::endmsg(logstream_base& stream) { stream.end_message(); return stream; } logstream_base& logstream_base::nop(logstream_base& stream) { return stream; } void logstream_base::end_message() { if (isEnabled()) { log(logger, level, location); } erase(); } int log4cxx::logstream_base::precision(int p) { get_stream_state(initclear, initset, fillchar, fillset); initset.precision(p); int oldVal = initclear.precision(p); refresh_stream_state(); return oldVal; } int log4cxx::logstream_base::precision() { get_stream_state(initclear, initset, fillchar, fillset); return initclear.precision(); } int log4cxx::logstream_base::width(int w) { get_stream_state(initclear, initset, fillchar, fillset); initset.width(w); int oldVal = initclear.width(w); refresh_stream_state(); return oldVal; } int log4cxx::logstream_base::width() { get_stream_state(initclear, initset, fillchar, fillset); return initclear.width(); } int log4cxx::logstream_base::fill(int newfill) { get_stream_state(initclear, initset, fillchar, fillset); int oldfill = fillchar; fillchar = newfill; fillset = true; refresh_stream_state(); return oldfill; } int logstream_base::fill() { get_stream_state(initclear, initset, fillchar, fillset); return fillchar; } std::ios_base::fmtflags logstream_base::flags(std::ios_base::fmtflags newflags) { get_stream_state(initclear, initset, fillchar, fillset); initset.flags(newflags); std::ios_base::fmtflags oldVal = initclear.flags(newflags); refresh_stream_state(); return oldVal; } std::ios_base::fmtflags logstream_base::setf(std::ios_base::fmtflags newflags, std::ios_base::fmtflags mask) { get_stream_state(initclear, initset, fillchar, fillset); initset.setf(newflags, mask); std::ios_base::fmtflags oldVal = initclear.setf(newflags, mask); refresh_stream_state(); return oldVal; } std::ios_base::fmtflags logstream_base::setf(std::ios_base::fmtflags newflags) { get_stream_state(initclear, initset, fillchar, fillset); initset.setf(newflags); std::ios_base::fmtflags oldVal = initclear.setf(newflags); refresh_stream_state(); return oldVal; } void logstream_base::setLevel(const ::log4cxx::LevelPtr& newlevel) { level = newlevel; bool oldLevel = enabled; enabled = logger->isEnabledFor(level); if (oldLevel != enabled) { erase(); } } bool logstream_base::isEnabledFor(const ::log4cxx::LevelPtr& level) const { return logger->isEnabledFor(level); } void logstream_base::setLocation(const log4cxx::spi::LocationInfo& newlocation) { if (LOG4CXX_UNLIKELY(enabled)) { location = newlocation; } } logstream::logstream(const log4cxx::LoggerPtr& logger, const log4cxx::LevelPtr& level) : logstream_base(logger, level), stream(0) { } logstream::logstream(const Ch* loggerName, const log4cxx::LevelPtr& level) : logstream_base(log4cxx::Logger::getLogger(loggerName), level), stream(0) { } logstream::logstream(const std::basic_string<Ch>& loggerName, const log4cxx::LevelPtr& level) : logstream_base(log4cxx::Logger::getLogger(loggerName), level), stream(0) { } logstream::~logstream() { delete stream; } logstream& logstream::operator<<(logstream_base& (*manip)(logstream_base&)) { (*manip)(*this); return *this; } logstream& logstream::operator<<(const LevelPtr& level) { setLevel(level); return *this; } logstream& logstream::operator<<(const log4cxx::spi::LocationInfo& newlocation) { setLocation(newlocation); return *this; } logstream& logstream::operator>>(const log4cxx::spi::LocationInfo& newlocation) { setLocation(newlocation); return *this; } logstream& logstream::operator<<(std::ios_base& (*manip)(std::ios_base&)) { logstream_base::insert(manip); return *this; } logstream::operator std::basic_ostream<char>&() { if (stream == 0) { stream = new std::basic_stringstream<Ch>(); refresh_stream_state(); } return *stream; } void logstream::log(LoggerPtr& logger, const LevelPtr& level, const log4cxx::spi::LocationInfo& location) { if (stream != 0) { std::basic_string<Ch> msg = stream->str(); if (!msg.empty()) { logger->log(level, msg, location); } } } void logstream::erase() { if (stream != 0) { std::basic_string<Ch> emptyStr; stream->str(emptyStr); } } void logstream::get_stream_state(std::ios_base& base, std::ios_base& mask, int& fill, bool& fillSet) const { if (stream != 0) { std::ios_base::fmtflags flags = stream->flags(); base.flags(flags); mask.flags(flags); int width = stream->width(); base.width(width); mask.width(width); int precision = stream->precision(); base.precision(precision); mask.precision(precision); fill = stream->fill(); fillSet = true; } } void logstream::refresh_stream_state() { if (stream != 0) { int fillchar; if(logstream_base::set_stream_state(*stream, fillchar)) { stream->fill(fillchar); } } } #if LOG4CXX_WCHAR_T_API wlogstream::wlogstream(const log4cxx::LoggerPtr& logger, const log4cxx::LevelPtr& level) : logstream_base(logger, level), stream(0) { } wlogstream::wlogstream(const Ch* loggerName, const log4cxx::LevelPtr& level) : logstream_base(log4cxx::Logger::getLogger(loggerName), level), stream(0) { } wlogstream::wlogstream(const std::basic_string<Ch>& loggerName, const log4cxx::LevelPtr& level) : logstream_base(log4cxx::Logger::getLogger(loggerName), level), stream(0) { } wlogstream::~wlogstream() { delete stream; } wlogstream& wlogstream::operator<<(logstream_base& (*manip)(logstream_base&)) { (*manip)(*this); return *this; } wlogstream& wlogstream::operator<<(const LevelPtr& level) { setLevel(level); return *this; } wlogstream& wlogstream::operator<<(const log4cxx::spi::LocationInfo& newlocation) { setLocation(newlocation); return *this; } wlogstream& wlogstream::operator>>(const log4cxx::spi::LocationInfo& newlocation) { setLocation(newlocation); return *this; } wlogstream& wlogstream::operator<<(std::ios_base& (*manip)(std::ios_base&)) { logstream_base::insert(manip); return *this; } wlogstream::operator std::basic_ostream<wchar_t>&() { if (stream == 0) { stream = new std::basic_stringstream<Ch>(); refresh_stream_state(); } return *stream; } void wlogstream::log(LoggerPtr& logger, const LevelPtr& level, const log4cxx::spi::LocationInfo& location) { if (stream != 0) { std::basic_string<Ch> msg = stream->str(); if (!msg.empty()) { logger->log(level, msg, location); } } } void wlogstream::erase() { if (stream != 0) { std::basic_string<Ch> emptyStr; stream->str(emptyStr); } } void wlogstream::get_stream_state(std::ios_base& base, std::ios_base& mask, int& fill, bool& fillSet) const { if (stream != 0) { std::ios_base::fmtflags flags = stream->flags(); base.flags(flags); mask.flags(flags); int width = stream->width(); base.width(width); mask.width(width); int precision = stream->precision(); base.precision(precision); mask.precision(precision); fill = stream->fill(); fillSet = true; } } void wlogstream::refresh_stream_state() { if (stream != 0) { int fillchar; if(logstream_base::set_stream_state(*stream, fillchar)) { stream->fill(fillchar); } } } #endif #if LOG4CXX_UNICHAR_API ulogstream::ulogstream(const Ch* loggerName, const log4cxx::LevelPtr& level) : logstream_base(log4cxx::Logger::getLogger(loggerName), level), stream(0) { } ulogstream::ulogstream(const std::basic_string<Ch>& loggerName, const log4cxx::LevelPtr& level) : logstream_base(log4cxx::Logger::getLogger(loggerName), level), stream(0) { } #endif #if LOG4CXX_CFSTRING_API ulogstream::ulogstream(const CFStringRef& loggerName, const log4cxx::LevelPtr& level) : logstream_base(log4cxx::Logger::getLogger(loggerName), level), stream(0) { } #endif #if LOG4CXX_UNICHAR_API || LOG4CXX_CFSTRING_API ulogstream::ulogstream(const log4cxx::LoggerPtr& logger, const log4cxx::LevelPtr& level) : logstream_base(logger, level), stream(0) { } ulogstream::~ulogstream() { delete stream; } ulogstream& ulogstream::operator<<(logstream_base& (*manip)(logstream_base&)) { (*manip)(*this); return *this; } ulogstream& ulogstream::operator<<(const LevelPtr& level) { setLevel(level); return *this; } ulogstream& ulogstream::operator<<(const log4cxx::spi::LocationInfo& newlocation) { setLocation(newlocation); return *this; } ulogstream& ulogstream::operator>>(const log4cxx::spi::LocationInfo& newlocation) { setLocation(newlocation); return *this; } ulogstream& ulogstream::operator<<(std::ios_base& (*manip)(std::ios_base&)) { logstream_base::insert(manip); return *this; } ulogstream::operator std::basic_ostream<UniChar>&() { if (stream == 0) { stream = new std::basic_stringstream<Ch>(); refresh_stream_state(); } return *stream; } void ulogstream::log(LoggerPtr& logger, const LevelPtr& level, const log4cxx::spi::LocationInfo& location) { if (stream != 0) { std::basic_string<Ch> msg = stream->str(); if (!msg.empty() && logger->isEnabledFor(level)) { LOG4CXX_DECODE_UNICHAR(lsmsg, msg); logger->forcedLogLS(level, lsmsg, location); } } } void ulogstream::erase() { if (stream != 0) { std::basic_string<Ch> emptyStr; stream->str(emptyStr); } } void ulogstream::get_stream_state(std::ios_base& base, std::ios_base& mask, int& fill, bool& fillSet) const { if (stream != 0) { std::ios_base::fmtflags flags = stream->flags(); base.flags(flags); mask.flags(flags); int width = stream->width(); base.width(width); mask.width(width); int precision = stream->precision(); base.precision(precision); mask.precision(precision); fill = stream->fill(); fillSet = true; } } void ulogstream::refresh_stream_state() { if (stream != 0) { int fillchar; if(logstream_base::set_stream_state(*stream, fillchar)) { stream->fill(fillchar); } } } #endif
001-log4cxx
trunk/src/main/cpp/logstream.cpp
C++
asf20
13,956
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <log4cxx/logstring.h> #include <log4cxx/helpers/socketoutputstream.h> #include <log4cxx/helpers/socket.h> #include <log4cxx/helpers/bytebuffer.h> using namespace log4cxx; using namespace log4cxx::helpers; IMPLEMENT_LOG4CXX_OBJECT(SocketOutputStream) SocketOutputStream::SocketOutputStream(const SocketPtr& socket1) : socket(socket1) { } SocketOutputStream::~SocketOutputStream() { } void SocketOutputStream::close(Pool& p) { flush(p); socket->close(); } void SocketOutputStream::flush(Pool& /* p */) { if (array.size() > 0) { ByteBuffer buf((char*) &array[0], array.size()); socket->write(buf); array.resize(0); } } void SocketOutputStream::write(ByteBuffer& buf, Pool& /* p */ ) { if (buf.remaining() > 0) { size_t sz = array.size(); array.resize(sz + buf.remaining()); memcpy(&array[sz], buf.current(), buf.remaining()); buf.position(buf.limit()); } }
001-log4cxx
trunk/src/main/cpp/socketoutputstream.cpp
C++
asf20
1,725
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #if defined(_MSC_VER) #pragma warning ( disable: 4231 4251 4275 4786 ) #endif #include <log4cxx/ndc.h> #include <log4cxx/helpers/transcoder.h> #include <log4cxx/helpers/threadspecificdata.h> using namespace log4cxx; using namespace log4cxx::helpers; NDC::NDC(const std::string& message) { push(message); } NDC::~NDC() { pop(); } LogString& NDC::getMessage(NDC::DiagnosticContext& ctx) { return ctx.first; } LogString& NDC::getFullMessage(NDC::DiagnosticContext& ctx) { return ctx.second; } void NDC::clear() { ThreadSpecificData* data = ThreadSpecificData::getCurrentData(); if (data != 0) { Stack& stack = data->getStack(); while(!stack.empty()) { stack.pop(); } data->recycle(); } } NDC::Stack* NDC::cloneStack() { ThreadSpecificData* data = ThreadSpecificData::getCurrentData(); if (data != 0) { Stack& stack = data->getStack(); if (!stack.empty()) { return new Stack(stack); } } return new Stack(); } void NDC::inherit(NDC::Stack * stack) { if (stack != NULL) { ThreadSpecificData::inherit(*stack); delete stack; } } bool NDC::get(LogString& dest) { ThreadSpecificData* data = ThreadSpecificData::getCurrentData(); if (data != 0) { Stack& stack = data->getStack(); if(!stack.empty()) { dest.append(getFullMessage(stack.top())); return true; } data->recycle(); } return false; } int NDC::getDepth() { int size = 0; ThreadSpecificData* data = ThreadSpecificData::getCurrentData(); if (data != 0) { size = data->getStack().size(); if (size == 0) { data->recycle(); } } return size; } LogString NDC::pop() { ThreadSpecificData* data = ThreadSpecificData::getCurrentData(); if (data != 0) { Stack& stack = data->getStack(); if(!stack.empty()) { LogString value(getMessage(stack.top())); stack.pop(); data->recycle(); return value; } data->recycle(); } return LogString(); } bool NDC::pop(std::string& dst) { bool retval = false; ThreadSpecificData* data = ThreadSpecificData::getCurrentData(); if (data != 0) { Stack& stack = data->getStack(); if(!stack.empty()) { Transcoder::encode(getMessage(stack.top()), dst); stack.pop(); retval = true; } data->recycle(); } return retval; } LogString NDC::peek() { ThreadSpecificData* data = ThreadSpecificData::getCurrentData(); if (data != 0) { Stack& stack = data->getStack(); if(!stack.empty()) { return getMessage(stack.top()); } data->recycle(); } return LogString(); } bool NDC::peek(std::string& dst) { ThreadSpecificData* data = ThreadSpecificData::getCurrentData(); if (data != 0) { Stack& stack = data->getStack(); if(!stack.empty()) { Transcoder::encode(getMessage(stack.top()), dst); return true; } data->recycle(); } return false; } void NDC::pushLS(const LogString& message) { ThreadSpecificData::push(message); } void NDC::push(const std::string& message) { LOG4CXX_DECODE_CHAR(msg, message); pushLS(msg); } void NDC::remove() { clear(); } bool NDC::empty() { bool empty = true; ThreadSpecificData* data = ThreadSpecificData::getCurrentData(); if (data != 0) { Stack& stack = data->getStack(); empty = stack.empty(); if (empty) { data->recycle(); } } return empty; } #if LOG4CXX_WCHAR_T_API NDC::NDC(const std::wstring& message) { push(message); } void NDC::push(const std::wstring& message) { LOG4CXX_DECODE_WCHAR(msg, message); pushLS(msg); } bool NDC::pop(std::wstring& dst) { ThreadSpecificData* data = ThreadSpecificData::getCurrentData(); if (data != 0) { Stack& stack = data->getStack(); if(!stack.empty()) { Transcoder::encode(getMessage(stack.top()), dst); stack.pop(); data->recycle(); return true; } data->recycle(); } return false; } bool NDC::peek(std::wstring& dst) { ThreadSpecificData* data = ThreadSpecificData::getCurrentData(); if (data != 0) { Stack& stack = data->getStack(); if(!stack.empty()) { Transcoder::encode(getMessage(stack.top()), dst); return true; } data->recycle(); } return false; } #endif #if LOG4CXX_UNICHAR_API NDC::NDC(const std::basic_string<UniChar>& message) { push(message); } void NDC::push(const std::basic_string<UniChar>& message) { LOG4CXX_DECODE_UNICHAR(msg, message); pushLS(msg); } bool NDC::pop(std::basic_string<UniChar>& dst) { ThreadSpecificData* data = ThreadSpecificData::getCurrentData(); if (data != 0) { Stack& stack = data->getStack(); if(!stack.empty()) { Transcoder::encode(stack.top().message, dst); stack.pop(); data->recycle(); return true; } data->recycle(); } return false; } bool NDC::peek(std::basic_string<UniChar>& dst) { ThreadSpecificData* data = ThreadSpecificData::getCurrentData(); if (data != 0) { Stack& stack = data->getStack(); if(!stack.empty()) { Transcoder::encode(stack.top().message, dst); return true; } data->recycle(); } return false; } #endif #if LOG4CXX_CFSTRING_API NDC::NDC(const CFStringRef& message) { push(message); } void NDC::push(const CFStringRef& message) { LOG4CXX_DECODE_CFSTRING(msg, message); pushLS(msg); } bool NDC::pop(CFStringRef& dst) { ThreadSpecificData* data = ThreadSpecificData::getCurrentData(); if (data != 0) { Stack& stack = data->getStack(); if(!stack.empty()) { dst = Transcoder::encode(stack.top().message); stack.pop(); data->recycle(); return true; } data->recycle(); } return false; } bool NDC::peek(CFStringRef& dst) { ThreadSpecificData* data = ThreadSpecificData::getCurrentData(); if (data != 0) { Stack& stack = data->getStack(); if(!stack.empty()) { dst = Transcoder::encode(stack.top().message); return true; } data->recycle(); } return false; } #endif
001-log4cxx
trunk/src/main/cpp/ndc.cpp
C++
asf20
7,610
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <log4cxx/logstring.h> #include <log4cxx/helpers/bytebuffer.h> #include <log4cxx/helpers/exception.h> #include <apr_pools.h> #include <log4cxx/helpers/pool.h> using namespace log4cxx; using namespace log4cxx::helpers; ByteBuffer::ByteBuffer(char* data1, size_t capacity) : base(data1), pos(0), lim(capacity), cap(capacity) { } ByteBuffer::~ByteBuffer() { } void ByteBuffer::clear() { lim = cap; pos = 0; } void ByteBuffer::flip() { lim = pos; pos = 0; } void ByteBuffer::position(size_t newPosition) { if (newPosition < lim) { pos = newPosition; } else { pos = lim; } } void ByteBuffer::limit(size_t newLimit) { if (newLimit > cap) { throw IllegalArgumentException(LOG4CXX_STR("newLimit")); } lim = newLimit; } bool ByteBuffer::put(char byte) { if (pos < lim) { base[pos++] = byte; return true; } return false; }
001-log4cxx
trunk/src/main/cpp/bytebuffer.cpp
C++
asf20
1,682
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <log4cxx/logstring.h> #include <log4cxx/helpers/bufferedwriter.h> #include <log4cxx/helpers/pool.h> using namespace log4cxx; using namespace log4cxx::helpers; IMPLEMENT_LOG4CXX_OBJECT(BufferedWriter) BufferedWriter::BufferedWriter(WriterPtr& out1) : out(out1), sz(1024) { } BufferedWriter::BufferedWriter(WriterPtr& out1, size_t sz1) : out(out1), sz(sz1) { } BufferedWriter::~BufferedWriter() { } void BufferedWriter::close(Pool& p) { flush(p); out->close(p); } void BufferedWriter::flush(Pool& p) { if (buf.length() > 0) { out->write(buf, p); buf.erase(buf.begin(), buf.end()); } } void BufferedWriter::write(const LogString& str, Pool& p) { if (buf.length() + str.length() > sz) { out->write(buf, p); buf.erase(buf.begin(), buf.end()); } if (str.length() > sz) { out->write(str, p); } else { buf.append(str); } }
001-log4cxx
trunk/src/main/cpp/bufferedwriter.cpp
C++
asf20
1,690
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <log4cxx/logstring.h> #include <log4cxx/simplelayout.h> #include <log4cxx/spi/loggingevent.h> #include <log4cxx/level.h> using namespace log4cxx; using namespace log4cxx::spi; IMPLEMENT_LOG4CXX_OBJECT(SimpleLayout) void SimpleLayout::format(LogString& output, const spi::LoggingEventPtr& event, log4cxx::helpers::Pool&) const { output.append(event->getLevel()->toString()); output.append(LOG4CXX_STR(" - ")); output.append(event->getRenderedMessage()); output.append(LOG4CXX_EOL); }
001-log4cxx
trunk/src/main/cpp/simplelayout.cpp
C++
asf20
1,338
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #if defined(_MSC_VER) #pragma warning ( disable: 4231 4251 4275 4786 ) #endif #include <log4cxx/logstring.h> #include <log4cxx/pattern/filelocationpatternconverter.h> #include <log4cxx/spi/loggingevent.h> #include <log4cxx/spi/location/locationinfo.h> using namespace log4cxx; using namespace log4cxx::pattern; using namespace log4cxx::spi; using namespace helpers; IMPLEMENT_LOG4CXX_OBJECT(FileLocationPatternConverter) FileLocationPatternConverter::FileLocationPatternConverter() : LoggingEventPatternConverter(LOG4CXX_STR("File Location"), LOG4CXX_STR("file")) { } PatternConverterPtr FileLocationPatternConverter::newInstance( const std::vector<LogString>& /* options */ ) { static PatternConverterPtr instance(new FileLocationPatternConverter()); return instance; } void FileLocationPatternConverter::format( const LoggingEventPtr& event, LogString& toAppendTo, Pool& /* p */ ) const { append(toAppendTo, event->getLocationInformation().getFileName()); }
001-log4cxx
trunk/src/main/cpp/filelocationpatternconverter.cpp
C++
asf20
1,810
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <log4cxx/logstring.h> #include <log4cxx/spi/rootlogger.h> #include <log4cxx/helpers/loglog.h> #include <log4cxx/level.h> #include <log4cxx/appender.h> using namespace log4cxx; using namespace log4cxx::spi; using namespace log4cxx::helpers; RootLogger::RootLogger(Pool& pool, const LevelPtr& level1) : Logger(pool, LOG4CXX_STR("root")) { setLevel(level1); } const LevelPtr& RootLogger::getEffectiveLevel() const { return level; } void RootLogger::setLevel(const LevelPtr& level1) { if(level1 == 0) { LogLog::error(LOG4CXX_STR("You have tried to set a null level to root.")); } else { this->level = level1; } }
001-log4cxx
trunk/src/main/cpp/rootlogger.cpp
C++
asf20
1,470
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <log4cxx/logstring.h> #include <log4cxx/helpers/outputstreamwriter.h> #include <log4cxx/helpers/exception.h> #include <log4cxx/helpers/charsetencoder.h> #include <log4cxx/helpers/bytebuffer.h> #include <log4cxx/helpers/stringhelper.h> using namespace log4cxx; using namespace log4cxx::helpers; IMPLEMENT_LOG4CXX_OBJECT(OutputStreamWriter) OutputStreamWriter::OutputStreamWriter(OutputStreamPtr& out1) : out(out1), enc(CharsetEncoder::getDefaultEncoder()) { if (out1 == 0) { throw NullPointerException(LOG4CXX_STR("out parameter may not be null.")); } } OutputStreamWriter::OutputStreamWriter(OutputStreamPtr& out1, CharsetEncoderPtr &enc1) : out(out1), enc(enc1) { if (out1 == 0) { throw NullPointerException(LOG4CXX_STR("out parameter may not be null.")); } if (enc1 == 0) { throw NullPointerException(LOG4CXX_STR("enc parameter may not be null.")); } } OutputStreamWriter::~OutputStreamWriter() { } void OutputStreamWriter::close(Pool& p) { out->close(p); } void OutputStreamWriter::flush(Pool& p) { out->flush(p); } void OutputStreamWriter::write(const LogString& str, Pool& p) { if (str.length() > 0) { enum { BUFSIZE = 1024 }; char rawbuf[BUFSIZE]; ByteBuffer buf(rawbuf, (size_t) BUFSIZE); enc->reset(); LogString::const_iterator iter = str.begin(); while(iter != str.end()) { CharsetEncoder::encode(enc, str, iter, buf); buf.flip(); out->write(buf, p); buf.clear(); } CharsetEncoder::encode(enc, str, iter, buf); enc->flush(buf); buf.flip(); out->write(buf, p); } }
001-log4cxx
trunk/src/main/cpp/outputstreamwriter.cpp
C++
asf20
2,425
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <log4cxx/logstring.h> #include <log4cxx/helpers/inputstream.h> using namespace log4cxx; using namespace log4cxx::helpers; IMPLEMENT_LOG4CXX_OBJECT(InputStream) InputStream::InputStream() { } InputStream::~InputStream() { }
001-log4cxx
trunk/src/main/cpp/inputstream.cpp
C++
asf20
1,040
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <log4cxx/logstring.h> #include <log4cxx/helpers/system.h> #include <log4cxx/helpers/transcoder.h> #include <log4cxx/helpers/pool.h> #include <apr_file_io.h> #include <apr_user.h> #include <apr_env.h> using namespace log4cxx; using namespace log4cxx::helpers; LogString System::getProperty(const LogString& lkey) { if (lkey.empty()) { throw IllegalArgumentException(LOG4CXX_STR("key is empty")); } LogString rv; if (lkey == LOG4CXX_STR("java.io.tmpdir")) { Pool p; const char* dir = NULL; apr_status_t stat = apr_temp_dir_get(&dir, p.getAPRPool()); if (stat == APR_SUCCESS) { Transcoder::decode(dir, rv); } return rv; } if (lkey == LOG4CXX_STR("user.dir")) { Pool p; char* dir = NULL; apr_status_t stat = apr_filepath_get(&dir, APR_FILEPATH_NATIVE, p.getAPRPool()); if (stat == APR_SUCCESS) { Transcoder::decode(dir, rv); } return rv; } #if APR_HAS_USER if (lkey == LOG4CXX_STR("user.home") || lkey == LOG4CXX_STR("user.name")) { Pool pool; apr_uid_t userid; apr_gid_t groupid; apr_pool_t* p = pool.getAPRPool(); apr_status_t stat = apr_uid_current(&userid, &groupid, p); if (stat == APR_SUCCESS) { char* username = NULL; stat = apr_uid_name_get(&username, userid, p); if (stat == APR_SUCCESS) { if (lkey == LOG4CXX_STR("user.name")) { Transcoder::decode(username, rv); } else { char* dirname = NULL; stat = apr_uid_homepath_get(&dirname, username, p); if (stat == APR_SUCCESS) { Transcoder::decode(dirname, rv); } } } } return rv; } #endif LOG4CXX_ENCODE_CHAR(key, lkey); Pool p; char* value = NULL; apr_status_t stat = apr_env_get(&value, key.c_str(), p.getAPRPool()); if (stat == APR_SUCCESS) { Transcoder::decode((const char*) value, rv); } return rv; }
001-log4cxx
trunk/src/main/cpp/system.cpp
C++
asf20
3,083
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <log4cxx/rolling/rollingpolicy.h> using namespace log4cxx::rolling; IMPLEMENT_LOG4CXX_OBJECT(RollingPolicy)
001-log4cxx
trunk/src/main/cpp/rollingpolicy.cpp
C++
asf20
927
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #if defined(_MSC_VER) #pragma warning ( disable: 4231 4251 4275 4786 ) #endif #include <log4cxx/logstring.h> #include <log4cxx/pattern/loggerpatternconverter.h> #include <log4cxx/spi/loggingevent.h> #include <log4cxx/spi/location/locationinfo.h> using namespace log4cxx; using namespace log4cxx::pattern; using namespace log4cxx::spi; using namespace log4cxx::helpers; IMPLEMENT_LOG4CXX_OBJECT(LoggerPatternConverter) LoggerPatternConverter::LoggerPatternConverter( const std::vector<LogString>& options) : NamePatternConverter(LOG4CXX_STR("Logger"), LOG4CXX_STR("logger"), options) { } PatternConverterPtr LoggerPatternConverter::newInstance( const std::vector<LogString>& options) { if (options.size() == 0) { static PatternConverterPtr def(new LoggerPatternConverter(options)); return def; } return new LoggerPatternConverter(options); } void LoggerPatternConverter::format( const LoggingEventPtr& event, LogString& toAppendTo, Pool& /* p */ ) const { int initialLength = toAppendTo.length(); toAppendTo.append(event->getLoggerName()); abbreviate(initialLength, toAppendTo); }
001-log4cxx
trunk/src/main/cpp/loggerpatternconverter.cpp
C++
asf20
1,939
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <log4cxx/logstring.h> #include <log4cxx/helpers/thread.h> #include <log4cxx/helpers/exception.h> #include <apr_thread_proc.h> #include <apr_atomic.h> #include <log4cxx/helpers/pool.h> #include <log4cxx/helpers/threadlocal.h> using namespace log4cxx::helpers; using namespace log4cxx; Thread::Thread() : thread(NULL), alive(0), interruptedStatus(0) { } Thread::~Thread() { join(); } Thread::LaunchPackage::LaunchPackage(Thread* t, Runnable r, void* d) : thread(t), runnable(r), data(d) { } Thread* Thread::LaunchPackage::getThread() const { return thread; } Runnable Thread::LaunchPackage::getRunnable() const { return runnable; } void* Thread::LaunchPackage::getData() const { return data; } void* Thread::LaunchPackage::operator new(size_t sz, Pool& p) { return p.palloc(sz); } void Thread::LaunchPackage::operator delete(void* mem, Pool& p) { } void Thread::run(Runnable start, void* data) { #if APR_HAS_THREADS // // if attempting a second run method on the same Thread object // throw an exception // if (thread != NULL) { throw IllegalStateException(); } apr_threadattr_t* attrs; apr_status_t stat = apr_threadattr_create(&attrs, p.getAPRPool()); if (stat != APR_SUCCESS) { throw ThreadException(stat); } // create LaunchPackage on the thread's memory pool LaunchPackage* package = new(p) LaunchPackage(this, start, data); stat = apr_thread_create(&thread, attrs, launcher, package, p.getAPRPool()); if (stat != APR_SUCCESS) { throw ThreadException(stat); } #else throw ThreadException(LOG4CXX_STR("APR_HAS_THREADS is not true")); #endif } Thread::LaunchStatus::LaunchStatus(volatile unsigned int* p) : alive(p) { apr_atomic_set32(alive, 0xFFFFFFFF); } Thread::LaunchStatus::~LaunchStatus() { apr_atomic_set32(alive, 0); } #if APR_HAS_THREADS void* LOG4CXX_THREAD_FUNC Thread::launcher(apr_thread_t* thread, void* data) { LaunchPackage* package = (LaunchPackage*) data; ThreadLocal& tls = getThreadLocal(); tls.set(package->getThread()); LaunchStatus alive(&package->getThread()->alive); void* retval = (package->getRunnable())(thread, package->getData()); apr_thread_exit(thread, 0); return retval; } #endif void Thread::join() { #if APR_HAS_THREADS if (thread != NULL) { apr_status_t startStat; apr_status_t stat = apr_thread_join(&startStat, thread); thread = NULL; if (stat != APR_SUCCESS) { throw ThreadException(stat); } } #endif } ThreadLocal& Thread::getThreadLocal() { static ThreadLocal tls; return tls; } void Thread::currentThreadInterrupt() { #if APR_HAS_THREADS void* tls = getThreadLocal().get(); if (tls != 0) { ((Thread*) tls)->interrupt(); } #endif } void Thread::interrupt() { apr_atomic_set32(&interruptedStatus, 0xFFFFFFFF); } bool Thread::interrupted() { #if APR_HAS_THREADS void* tls = getThreadLocal().get(); if (tls != 0) { return apr_atomic_xchg32(&(((Thread*) tls)->interruptedStatus), 0) != 0; } #endif return false; } bool Thread::isCurrentThread() const { #if APR_HAS_THREADS const void* tls = getThreadLocal().get(); return (tls == this); #else return true; #endif } bool Thread::isAlive() { return apr_atomic_read32(&alive) != 0; } void Thread::ending() { apr_atomic_set32(&alive, 0); } void Thread::sleep(int duration) { #if APR_HAS_THREADS if(interrupted()) { throw InterruptedException(); } #endif if (duration > 0) { apr_sleep(duration*1000); } }
001-log4cxx
trunk/src/main/cpp/threadcxx.cpp
C++
asf20
4,618
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <log4cxx/logstring.h> #include <log4cxx/helpers/systemerrwriter.h> #include <log4cxx/helpers/transcoder.h> #include <stdio.h> #if !defined(LOG4CXX) #define LOG4CXX 1 #endif #include <log4cxx/private/log4cxx_private.h> using namespace log4cxx; using namespace log4cxx::helpers; IMPLEMENT_LOG4CXX_OBJECT(SystemErrWriter) SystemErrWriter::SystemErrWriter() { } SystemErrWriter::~SystemErrWriter() { } void SystemErrWriter::close(Pool& /* p */) { } void SystemErrWriter::flush(Pool& /* p */) { flush(); } void SystemErrWriter::write(const LogString& str, Pool& /* p */) { write(str); } bool SystemErrWriter::isWide() { #if LOG4CXX_FORCE_WIDE_CONSOLE return true; #elif LOG4CXX_FORCE_BYTE_CONSOLE || !LOG4CXX_HAS_FWIDE return false; #else return fwide(stderr, 0) > 0; #endif } void SystemErrWriter::write(const LogString& str) { #if LOG4CXX_WCHAR_T_API if (isWide()) { LOG4CXX_ENCODE_WCHAR(msg, str); fputws(msg.c_str(), stderr); return; } #endif LOG4CXX_ENCODE_CHAR(msg, str); fputs(msg.c_str(), stderr); } void SystemErrWriter::flush() { fflush(stderr); }
001-log4cxx
trunk/src/main/cpp/systemerrwriter.cpp
C++
asf20
1,932
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #define __STDC_CONSTANT_MACROS #include <log4cxx/logstring.h> #include <log4cxx/helpers/stringhelper.h> #include <log4cxx/helpers/transcoder.h> #include <algorithm> #include <vector> #include <apr_strings.h> #include <log4cxx/helpers/pool.h> #if !defined(LOG4CXX) #define LOG4CXX 1 #endif #include <log4cxx/private/log4cxx_private.h> #include <cctype> #include <apr.h> using namespace log4cxx; using namespace log4cxx::helpers; bool StringHelper::equalsIgnoreCase(const LogString& s1, const logchar* upper, const logchar* lower) { for (LogString::const_iterator iter = s1.begin(); iter != s1.end(); iter++, upper++, lower++) { if (*iter != *upper && *iter != * lower) return false; } return (*upper == 0); } bool StringHelper::equalsIgnoreCase(const LogString& s1, const LogString& upper, const LogString& lower) { LogString::const_iterator u = upper.begin(); LogString::const_iterator l = lower.begin(); LogString::const_iterator iter = s1.begin(); for (; iter != s1.end() && u != upper.end() && l != lower.end(); iter++, u++, l++) { if (*iter != *u && *iter != *l) return false; } return u == upper.end() && iter == s1.end(); } LogString StringHelper::toLowerCase(const LogString& s) { LogString d; std::transform(s.begin(), s.end(), std::insert_iterator<LogString>(d, d.begin()), tolower); return d; } LogString StringHelper::trim(const LogString& s) { LogString::size_type pos = s.find_first_not_of(' '); if (pos == std::string::npos) { return LogString(); } LogString::size_type n = s.find_last_not_of(' ') - pos + 1; return s.substr(pos, n); } bool StringHelper::startsWith(const LogString& s, const LogString& prefix) { return s.compare(0, prefix.length(), prefix) == 0; } bool StringHelper::endsWith(const LogString& s, const LogString& suffix) { if (suffix.length() <= s.length()) { return s.compare(s.length() - suffix.length(), suffix.length(), suffix) == 0; } return false; } int StringHelper::toInt(const LogString& s) { std::string as; Transcoder::encode(s, as); return atoi(as.c_str()); } log4cxx_int64_t StringHelper::toInt64(const LogString& s) { std::string as; Transcoder::encode(s, as); return apr_atoi64(as.c_str()); } void StringHelper::toString(int n, Pool& pool, LogString& s) { char* fmt = pool.itoa(n); Transcoder::decode(fmt, s); } void StringHelper::toString(bool val, LogString& dst) { if (val) { dst.append(LOG4CXX_STR("true")); } else { dst.append(LOG4CXX_STR("false")); } } void StringHelper::toString(log4cxx_int64_t n, Pool& pool, LogString& dst) { if (n >= INT_MIN && n <= INT_MAX) { toString((int) n, pool, dst); } else { const log4cxx_int64_t BILLION = APR_INT64_C(1000000000); int billions = (int) (n / BILLION); char* upper = pool.itoa(billions); int remain = (int) (n - billions * BILLION); if (remain < 0) remain *= -1; char* lower = pool.itoa(remain); Transcoder::decode(upper, dst); dst.append(9 - strlen(lower), 0x30 /* '0' */); Transcoder::decode(lower, dst); } } void StringHelper::toString(size_t n, Pool& pool, LogString& s) { toString((log4cxx_int64_t) n, pool, s); } LogString StringHelper::format(const LogString& pattern, const std::vector<LogString>& params) { LogString result; int i = 0; while(pattern[i] != 0) { if (pattern[i] == 0x7B /* '{' */ && pattern[i + 1] >= 0x30 /* '0' */ && pattern[i + 1] <= 0x39 /* '9' */ && pattern[i + 2] == 0x7D /* '}' */) { int arg = pattern[i + 1] - 0x30 /* '0' */; result = result + params[arg]; i += 3; } else { result = result + pattern[i]; i++; } } return result; }
001-log4cxx
trunk/src/main/cpp/stringhelper.cpp
C++
asf20
4,623
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <log4cxx/logstring.h> #include <log4cxx/helpers/strftimedateformat.h> #include <apr_time.h> #include <log4cxx/helpers/transcoder.h> using namespace log4cxx; using namespace log4cxx::helpers; StrftimeDateFormat::StrftimeDateFormat(const LogString& fmt) : timeZone(TimeZone::getDefault()) { log4cxx::helpers::Transcoder::encode(fmt, pattern); } StrftimeDateFormat::~StrftimeDateFormat() { } void StrftimeDateFormat::format(LogString& s, log4cxx_time_t time, Pool& /* p */ ) const { apr_time_exp_t exploded; apr_status_t stat = timeZone->explode(&exploded, time); if (stat == APR_SUCCESS) { const apr_size_t bufSize = 255; char buf[bufSize]; apr_size_t bufLen; stat = apr_strftime(buf, &bufLen, bufSize, pattern.c_str(), &exploded); if (stat == APR_SUCCESS) { log4cxx::helpers::Transcoder::decode(std::string(buf, bufLen), s); } } } void StrftimeDateFormat::setTimeZone(const TimeZonePtr& zone) { timeZone = zone; }
001-log4cxx
trunk/src/main/cpp/strftimedateformat.cpp
C++
asf20
1,783
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #if defined(_MSC_VER) #pragma warning ( disable: 4231 4251 4275 4786 ) #endif #include <log4cxx/logstring.h> #include <log4cxx/pattern/ndcpatternconverter.h> #include <log4cxx/spi/loggingevent.h> #include <log4cxx/spi/location/locationinfo.h> using namespace log4cxx; using namespace log4cxx::pattern; using namespace log4cxx::spi; using namespace log4cxx::helpers; IMPLEMENT_LOG4CXX_OBJECT(NDCPatternConverter) NDCPatternConverter::NDCPatternConverter() : LoggingEventPatternConverter(LOG4CXX_STR("NDC"), LOG4CXX_STR("ndc")) { } PatternConverterPtr NDCPatternConverter::newInstance( const std::vector<LogString>& /* options */) { static PatternConverterPtr def(new NDCPatternConverter()); return def; } void NDCPatternConverter::format( const LoggingEventPtr& event, LogString& toAppendTo, Pool& /* p */) const { if(!event->getNDC(toAppendTo)) { toAppendTo.append(LOG4CXX_STR("null")); } }
001-log4cxx
trunk/src/main/cpp/ndcpatternconverter.cpp
C++
asf20
1,741
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <log4cxx/logstring.h> #include <log4cxx/filter/stringmatchfilter.h> #include <log4cxx/spi/loggingevent.h> #include <log4cxx/helpers/stringhelper.h> #include <log4cxx/helpers/optionconverter.h> using namespace log4cxx; using namespace log4cxx::filter; using namespace log4cxx::spi; using namespace log4cxx::helpers; IMPLEMENT_LOG4CXX_OBJECT(StringMatchFilter) StringMatchFilter::StringMatchFilter() : acceptOnMatch(true), stringToMatch() { } void StringMatchFilter::setOption(const LogString& option, const LogString& value) { if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("STRINGTOMATCH"), LOG4CXX_STR("stringtomatch"))) { stringToMatch = value; } else if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("ACCEPTONMATCH"), LOG4CXX_STR("acceptonmatch"))) { acceptOnMatch = OptionConverter::toBoolean(value, acceptOnMatch); } } Filter::FilterDecision StringMatchFilter::decide( const log4cxx::spi::LoggingEventPtr& event) const { const LogString& msg = event->getRenderedMessage(); if(msg.empty() || stringToMatch.empty()) { return Filter::NEUTRAL; } if( msg.find(stringToMatch) == LogString::npos ) { return Filter::NEUTRAL; } else { // we've got a match if(acceptOnMatch) { return Filter::ACCEPT; } else { return Filter::DENY; } } }
001-log4cxx
trunk/src/main/cpp/stringmatchfilter.cpp
C++
asf20
2,232
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #if defined(_MSC_VER) #pragma warning ( disable: 4231 4251 4275 4786 ) #endif #define __STDC_CONSTANT_MACROS #include <log4cxx/logstring.h> #include <log4cxx/helpers/timezone.h> #include <stdlib.h> #include <apr_time.h> #include <apr_pools.h> #include <apr_strings.h> #include <log4cxx/helpers/transcoder.h> #include <log4cxx/helpers/stringhelper.h> #include <log4cxx/helpers/pool.h> #include <log4cxx/logger.h> using namespace log4cxx; using namespace log4cxx::helpers; IMPLEMENT_LOG4CXX_OBJECT( TimeZone ) namespace log4cxx { namespace helpers { namespace TimeZoneImpl { /** Time zone object that represents GMT. */ class GMTTimeZone : public TimeZone { public: /** Class factory. */ static const TimeZonePtr & getInstance() { static TimeZonePtr tz( new GMTTimeZone() ); return tz; } /** Explode time to human readable form. */ log4cxx_status_t explode( apr_time_exp_t * result, log4cxx_time_t input ) const { apr_status_t stat; // APR 1.1 and early mishandles microseconds on dates // before 1970, APR bug 32520 if (LOG4CXX_UNLIKELY(input < 0 && apr_time_usec(input) < 0)) { apr_time_t floorTime = (apr_time_sec(input) -1) * APR_USEC_PER_SEC; stat = apr_time_exp_gmt(result, floorTime); result->tm_usec = (int) (input - floorTime); } else { stat = apr_time_exp_gmt( result, input ); } return stat; } private: GMTTimeZone() : TimeZone( LOG4CXX_STR("GMT") ) { } }; /** Time zone object that represents GMT. */ class LocalTimeZone : public TimeZone { public: /** Class factory. */ static const TimeZonePtr & getInstance() { static TimeZonePtr tz( new LocalTimeZone() ); return tz; } /** Explode time to human readable form. */ log4cxx_status_t explode( apr_time_exp_t * result, log4cxx_time_t input ) const { apr_status_t stat; // APR 1.1 and early mishandles microseconds on dates // before 1970, APR bug 32520 if (LOG4CXX_UNLIKELY(input < 0 && apr_time_usec(input) < 0)) { apr_time_t floorTime = (apr_time_sec(input) -1) * APR_USEC_PER_SEC; stat = apr_time_exp_lt(result, floorTime); result->tm_usec = (int) (input - floorTime); } else { stat = apr_time_exp_lt( result, input ); } return stat; } private: LocalTimeZone() : TimeZone( getTimeZoneName() ) { } static const LogString getTimeZoneName() { const int MAX_TZ_LENGTH = 255; char tzName[MAX_TZ_LENGTH]; apr_size_t tzLength; apr_time_exp_t tm; apr_time_exp_lt(&tm, 0); apr_strftime(tzName, &tzLength, MAX_TZ_LENGTH, "%Z", &tm); if (tzLength == 0) { apr_strftime(tzName, &tzLength, MAX_TZ_LENGTH, "%z", &tm); } tzName[tzLength] = 0; LogString retval; log4cxx::helpers::Transcoder::decode(tzName, retval); return retval; } }; /** Time zone object that represents a fixed offset from GMT. */ class FixedTimeZone : public TimeZone { public: FixedTimeZone( const LogString & name, apr_int32_t offset1 ) : TimeZone( name ), offset( offset1 ) { } /** Explode time to human readable form. */ log4cxx_status_t explode( apr_time_exp_t * result, log4cxx_time_t input ) const { apr_status_t stat; // APR 1.1 and early mishandles microseconds on dates // before 1970, APR bug 32520 if (LOG4CXX_UNLIKELY(input < 0 && apr_time_usec(input) < 0)) { apr_time_t floorTime = (apr_time_sec(input) -1) * APR_USEC_PER_SEC; stat = apr_time_exp_tz(result, floorTime, offset); result->tm_usec = (int) (input - floorTime); } else { stat = apr_time_exp_tz( result, input, offset ); } return stat; } private: const apr_int32_t offset; }; } } } TimeZone::TimeZone( const LogString & id1 ) : id( id1 ) { } TimeZone::~TimeZone() { } const TimeZonePtr & TimeZone::getDefault() { return log4cxx::helpers::TimeZoneImpl::LocalTimeZone::getInstance(); } const TimeZonePtr & TimeZone::getGMT() { return log4cxx::helpers::TimeZoneImpl::GMTTimeZone::getInstance(); } const TimeZonePtr TimeZone::getTimeZone( const LogString & id ) { const logchar gmt[] = { 0x47, 0x4D, 0x54, 0 }; if ( id == gmt ) { return log4cxx::helpers::TimeZoneImpl::GMTTimeZone::getInstance(); } if ( id.length() >= 5 && id.substr( 0, 3 ) == gmt ) { int hours = 0; int minutes = 0; int sign = 1; if (id[3] == 0x2D /* '-' */) { sign = -1; } LogString off( id.substr( 4 ) ); if ( id.length() >= 7 ) { size_t colonPos = off.find( 0x3A /* ':' */); if ( colonPos == LogString::npos ) { minutes = StringHelper::toInt(off.substr(off.length() - 2)); hours = StringHelper::toInt(off.substr(0, off.length() - 2)); } else { minutes = StringHelper::toInt(off.substr(colonPos + 1)); hours = StringHelper::toInt(off.substr(0, colonPos)); } } else { hours = StringHelper::toInt(off); } LogString s(gmt); Pool p; LogString hh; StringHelper::toString(hours, p, hh); if (sign > 0) { s.append(1, (logchar) 0x2B /* '+' */); } else { s.append(1, (logchar) 0x2D /* '-' */); } if (hh.length() == 1) { s.append(1, (logchar) 0x30 /* '0' */); } s.append(hh); s.append(1, (logchar) 0x3A /*' :' */); LogString mm; StringHelper::toString(minutes, p, mm); if (mm.length() == 1) { s.append(1, (logchar) 0x30 /* '0' */); } s.append(mm); apr_int32_t offset = sign * (hours * 3600 + minutes * 60); return new log4cxx::helpers::TimeZoneImpl::FixedTimeZone( s, offset ); } const TimeZonePtr & ltz = getDefault(); if ( ltz->getID() == id ) { return ltz; } return getGMT(); }
001-log4cxx
trunk/src/main/cpp/timezone.cpp
C++
asf20
7,167
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <log4cxx/rolling/gzcompressaction.h> #include <apr_thread_proc.h> #include <apr_strings.h> #include <log4cxx/helpers/exception.h> #include <log4cxx/helpers/transcoder.h> using namespace log4cxx; using namespace log4cxx::rolling; using namespace log4cxx::helpers; IMPLEMENT_LOG4CXX_OBJECT(GZCompressAction) GZCompressAction::GZCompressAction(const File& src, const File& dest, bool del) : source(src), destination(dest), deleteSource(del) { } bool GZCompressAction::execute(log4cxx::helpers::Pool& p) const { if (source.exists(p)) { apr_pool_t* pool = p.getAPRPool(); apr_procattr_t* attr; apr_status_t stat = apr_procattr_create(&attr, pool); if (stat != APR_SUCCESS) throw IOException(stat); stat = apr_procattr_io_set(attr, APR_NO_PIPE, APR_FULL_BLOCK, APR_FULL_BLOCK); if (stat != APR_SUCCESS) throw IOException(stat); stat = apr_procattr_cmdtype_set(attr, APR_PROGRAM_PATH); if (stat != APR_SUCCESS) throw IOException(stat); // // set child process output to destination file // apr_file_t* child_out; apr_int32_t flags = APR_FOPEN_READ | APR_FOPEN_WRITE | APR_FOPEN_CREATE | APR_FOPEN_TRUNCATE; stat = destination.open(&child_out, flags, APR_OS_DEFAULT, p); if (stat != APR_SUCCESS) throw IOException(stat); stat = apr_procattr_child_out_set(attr, child_out, NULL); if (stat != APR_SUCCESS) throw IOException(stat); // // redirect the child's error stream to this processes' error stream // apr_file_t* child_err; stat = apr_file_open_stderr(&child_err, pool); if (stat == APR_SUCCESS) { stat = apr_procattr_child_err_set(attr, child_err, NULL); if (stat != APR_SUCCESS) throw IOException(stat); } const char** args = (const char**) apr_palloc(pool, 4 *sizeof(*args)); int i = 0; args[i++] = "gzip"; args[i++] = "-c"; args[i++] = Transcoder::encode(source.getPath(), p); args[i++] = NULL; apr_proc_t pid; stat = apr_proc_create(&pid, "gzip", args, NULL, attr, pool); if (stat != APR_SUCCESS) throw IOException(stat); apr_proc_wait(&pid, NULL, NULL, APR_WAIT); stat = apr_file_close(child_out); if (stat != APR_SUCCESS) throw IOException(stat); if (deleteSource) { source.deleteFile(p); } return true; } return false; }
001-log4cxx
trunk/src/main/cpp/gzcompressaction.cpp
C++
asf20
3,364
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <log4cxx/mdc.h> #include <log4cxx/helpers/transcoder.h> #include <log4cxx/helpers/threadspecificdata.h> #if LOG4CXX_CFSTRING_API #include <CoreFoundation/CFString.h> #endif using namespace log4cxx; using namespace log4cxx::helpers; MDC::MDC(const std::string& key1, const std::string& value) : key() { Transcoder::decode(key1, key); LOG4CXX_DECODE_CHAR(v, value); putLS(key, v); } MDC::~MDC() { LogString prevVal; remove(key, prevVal); } void MDC::putLS(const LogString& key, const LogString& value) { ThreadSpecificData::put(key, value); } void MDC::put(const std::string& key, const std::string& value) { LOG4CXX_DECODE_CHAR(lkey, key); LOG4CXX_DECODE_CHAR(lvalue, value); putLS(lkey, lvalue); } bool MDC::get(const LogString& key, LogString& value) { ThreadSpecificData* data = ThreadSpecificData::getCurrentData(); if (data != 0) { Map& map = data->getMap(); Map::iterator it = map.find(key); if (it != map.end()) { value.append(it->second); return true; } data->recycle(); } return false; } std::string MDC::get(const std::string& key) { LOG4CXX_DECODE_CHAR(lkey, key); LogString lvalue; if (get(lkey, lvalue)) { LOG4CXX_ENCODE_CHAR(value, lvalue); return value; } return std::string(); } bool MDC::remove(const LogString& key, LogString& value) { ThreadSpecificData* data = ThreadSpecificData::getCurrentData(); if (data != 0) { Map& map = data->getMap(); Map::iterator it; if ((it = map.find(key)) != map.end()) { value = it->second; map.erase(it); data->recycle(); return true; } } return false; } std::string MDC::remove(const std::string& key) { LOG4CXX_DECODE_CHAR(lkey, key); LogString lvalue; if (remove(lkey, lvalue)) { LOG4CXX_ENCODE_CHAR(value, lvalue); return value; } return std::string(); } void MDC::clear() { ThreadSpecificData* data = ThreadSpecificData::getCurrentData(); if (data != 0) { Map& map = data->getMap(); map.erase(map.begin(), map.end()); data->recycle(); } } #if LOG4CXX_WCHAR_T_API MDC::MDC(const std::wstring& key1, const std::wstring& value) : key() { Transcoder::decode(key1, key); LOG4CXX_DECODE_WCHAR(v, value); putLS(key, v); } std::wstring MDC::get(const std::wstring& key) { LOG4CXX_DECODE_WCHAR(lkey, key); LogString lvalue; if (get(lkey, lvalue)) { LOG4CXX_ENCODE_WCHAR(value, lvalue); return value; } return std::wstring(); } void MDC::put(const std::wstring& key, const std::wstring& value) { LOG4CXX_DECODE_WCHAR(lkey, key); LOG4CXX_DECODE_WCHAR(lvalue, value); putLS(lkey, lvalue); } std::wstring MDC::remove(const std::wstring& key) { LOG4CXX_DECODE_WCHAR(lkey, key); LogString lvalue; if (remove(lkey, lvalue)) { LOG4CXX_ENCODE_WCHAR(value, lvalue); return value; } return std::wstring(); } #endif #if LOG4CXX_UNICHAR_API MDC::MDC(const std::basic_string<UniChar>& key1, const std::basic_string<UniChar>& value) { Transcoder::decode(key1, key); LOG4CXX_DECODE_UNICHAR(v, value); putLS(key, v); } std::basic_string<log4cxx::UniChar> MDC::get(const std::basic_string<log4cxx::UniChar>& key) { LOG4CXX_DECODE_UNICHAR(lkey, key); LogString lvalue; if (get(lkey, lvalue)) { LOG4CXX_ENCODE_UNICHAR(value, lvalue); return value; } return std::basic_string<UniChar>(); } void MDC::put(const std::basic_string<UniChar>& key, const std::basic_string<log4cxx::UniChar>& value) { LOG4CXX_DECODE_UNICHAR(lkey, key); LOG4CXX_DECODE_UNICHAR(lvalue, value); putLS(lkey, lvalue); } std::basic_string<log4cxx::UniChar> MDC::remove(const std::basic_string<log4cxx::UniChar>& key) { LOG4CXX_DECODE_UNICHAR(lkey, key); LogString lvalue; if (remove(lkey, lvalue)) { LOG4CXX_ENCODE_UNICHAR(value, lvalue); return value; } return std::basic_string<UniChar>(); } #endif #if LOG4CXX_CFSTRING_API MDC::MDC(const CFStringRef& key1, const CFStringRef& value) { Transcoder::decode(key1, key); LOG4CXX_DECODE_CFSTRING(v, value); putLS(key, v); } CFStringRef MDC::get(const CFStringRef& key) { LOG4CXX_DECODE_CFSTRING(lkey, key); LogString lvalue; if (get(lkey, lvalue)) { LOG4CXX_ENCODE_CFSTRING(value, lvalue); return value; } return CFSTR(""); } void MDC::put(const CFStringRef& key, const CFStringRef& value) { LOG4CXX_DECODE_CFSTRING(lkey, key); LOG4CXX_DECODE_CFSTRING(lvalue, value); putLS(lkey, lvalue); } CFStringRef MDC::remove(const CFStringRef& key) { LOG4CXX_DECODE_CFSTRING(lkey, key); LogString lvalue; if (remove(lkey, lvalue)) { LOG4CXX_ENCODE_CFSTRING(value, lvalue); return value; } return CFSTR(""); } #endif
001-log4cxx
trunk/src/main/cpp/mdc.cpp
C++
asf20
6,219
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <log4cxx/logstring.h> #if !defined(LOG4CXX) #define LOG4CXX 1 #endif #include <log4cxx/helpers/aprinitializer.h> #include <apr_pools.h> #include <apr_atomic.h> #include <apr_time.h> #include <assert.h> #include <log4cxx/helpers/threadspecificdata.h> using namespace log4cxx::helpers; using namespace log4cxx; bool APRInitializer::isDestructed = false; APRInitializer::APRInitializer() { apr_initialize(); apr_pool_create(&p, NULL); apr_atomic_init(p); startTime = apr_time_now(); #if APR_HAS_THREADS apr_status_t stat = apr_threadkey_private_create(&tlsKey, tlsDestruct, p); assert(stat == APR_SUCCESS); #endif } APRInitializer::~APRInitializer() { apr_terminate(); isDestructed = true; } APRInitializer& APRInitializer::getInstance() { static APRInitializer init; return init; } log4cxx_time_t APRInitializer::initialize() { return getInstance().startTime; } apr_pool_t* APRInitializer::getRootPool() { return getInstance().p; } apr_threadkey_t* APRInitializer::getTlsKey() { return getInstance().tlsKey; } void APRInitializer::tlsDestruct(void* ptr) { delete ((ThreadSpecificData*) ptr); }
001-log4cxx
trunk/src/main/cpp/aprinitializer.cpp
C++
asf20
1,959
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <log4cxx/logstring.h> #include <log4cxx/rolling/filterbasedtriggeringpolicy.h> #include <log4cxx/spi/filter.h> using namespace log4cxx; using namespace log4cxx::rolling; using namespace log4cxx::spi; IMPLEMENT_LOG4CXX_OBJECT(FilterBasedTriggeringPolicy) FilterBasedTriggeringPolicy::FilterBasedTriggeringPolicy() { } FilterBasedTriggeringPolicy::~FilterBasedTriggeringPolicy() { } bool FilterBasedTriggeringPolicy::isTriggeringEvent( Appender* /* appender */, const log4cxx::spi::LoggingEventPtr& event, const LogString& /* filename */, size_t /* fileLength */ ) { if (headFilter == NULL) { return false; } for(log4cxx::spi::FilterPtr f = headFilter; f != NULL; f = f->getNext()) { switch(f->decide(event)) { case Filter::DENY: return false; case Filter::ACCEPT: return true; case Filter::NEUTRAL: break; } } return true; } /** * Add a filter to end of the filter list. * @param newFilter filter to add to end of list. */ void FilterBasedTriggeringPolicy::addFilter(const log4cxx::spi::FilterPtr& newFilter) { if (headFilter == NULL) { headFilter = newFilter; tailFilter = newFilter; } else { tailFilter->setNext(newFilter); tailFilter = newFilter; } } void FilterBasedTriggeringPolicy::clearFilters() { log4cxx::spi::FilterPtr empty; headFilter = empty; tailFilter = empty; } log4cxx::spi::FilterPtr& FilterBasedTriggeringPolicy::getFilter() { return headFilter; } /** * Prepares the instance for use. */ void FilterBasedTriggeringPolicy::activateOptions(log4cxx::helpers::Pool& p) { for(log4cxx::spi::FilterPtr f = headFilter; f != NULL; f = f->getNext()) { f->activateOptions(p); } } void FilterBasedTriggeringPolicy::setOption(const LogString& /* option */, const LogString& /* value */ ) { }
001-log4cxx
trunk/src/main/cpp/filterbasedtriggeringpolicy.cpp
C++
asf20
2,658
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #if defined(_MSC_VER) #pragma warning ( disable: 4231 4251 4275 4786 ) #endif #include <log4cxx/logstring.h> #include <log4cxx/helpers/class.h> #include <log4cxx/helpers/exception.h> #include <log4cxx/helpers/object.h> #include <map> #include <log4cxx/helpers/stringhelper.h> #include <log4cxx/log4cxx.h> #if !defined(LOG4CXX) #define LOG4CXX 1 #endif #include <log4cxx/private/log4cxx_private.h> #include <log4cxx/rollingfileappender.h> #include <log4cxx/dailyrollingfileappender.h> #include <log4cxx/asyncappender.h> #include <log4cxx/consoleappender.h> #include <log4cxx/fileappender.h> #include <log4cxx/db/odbcappender.h> #if defined(WIN32) || defined(_WIN32) #if !defined(_WIN32_WCE) #include <log4cxx/nt/nteventlogappender.h> #endif #include <log4cxx/nt/outputdebugstringappender.h> #endif #include <log4cxx/net/smtpappender.h> #include <log4cxx/net/socketappender.h> #include <log4cxx/net/sockethubappender.h> #include <log4cxx/helpers/datagramsocket.h> #include <log4cxx/net/syslogappender.h> #include <log4cxx/net/telnetappender.h> #include <log4cxx/writerappender.h> #include <log4cxx/net/xmlsocketappender.h> #include <log4cxx/layout.h> #include <log4cxx/patternlayout.h> #include <log4cxx/htmllayout.h> #include <log4cxx/simplelayout.h> #include <log4cxx/xml/xmllayout.h> #include <log4cxx/ttcclayout.h> #include <log4cxx/filter/levelmatchfilter.h> #include <log4cxx/filter/levelrangefilter.h> #include <log4cxx/filter/stringmatchfilter.h> #include <log4cxx/rolling/filterbasedtriggeringpolicy.h> #include <log4cxx/rolling/fixedwindowrollingpolicy.h> #include <log4cxx/rolling/manualtriggeringpolicy.h> #include <log4cxx/rolling/rollingfileappender.h> #include <log4cxx/rolling/sizebasedtriggeringpolicy.h> #include <log4cxx/rolling/timebasedrollingpolicy.h> #include <log4cxx/xml/domconfigurator.h> #include <log4cxx/propertyconfigurator.h> #include <apr.h> using namespace log4cxx; using namespace log4cxx::helpers; using namespace log4cxx::net; using namespace log4cxx::filter; using namespace log4cxx::xml; using namespace log4cxx::rolling; Class::Class() { } Class::~Class() { } LogString Class::toString() const { return getName(); } ObjectPtr Class::newInstance() const { throw InstantiationException(LOG4CXX_STR("Cannot create new instances of Class.")); #if LOG4CXX_RETURN_AFTER_THROW return 0; #endif } Class::ClassMap& Class::getRegistry() { static ClassMap registry; return registry; } const Class& Class::forName(const LogString& className) { LogString lowerName(StringHelper::toLowerCase(className)); // // check registry using full class name // const Class* clazz = getRegistry()[lowerName]; if (clazz == 0) { LogString::size_type pos = className.find_last_of(LOG4CXX_STR(".$")); if (pos != LogString::npos) { LogString terminalName(lowerName, pos + 1, LogString::npos); clazz = getRegistry()[terminalName]; if (clazz == 0) { registerClasses(); clazz = getRegistry()[lowerName]; if (clazz == 0) { clazz = getRegistry()[terminalName]; } } } else { registerClasses(); clazz = getRegistry()[lowerName]; } } if (clazz == 0) { throw ClassNotFoundException(className); } return *clazz; } bool Class::registerClass(const Class& newClass) { getRegistry()[StringHelper::toLowerCase(newClass.getName())] = &newClass; return true; } void Class::registerClasses() { #if APR_HAS_THREADS AsyncAppender::registerClass(); #endif ConsoleAppender::registerClass(); FileAppender::registerClass(); log4cxx::db::ODBCAppender::registerClass(); #if (defined(WIN32) || defined(_WIN32)) #if !defined(_WIN32_WCE) log4cxx::nt::NTEventLogAppender::registerClass(); #endif log4cxx::nt::OutputDebugStringAppender::registerClass(); #endif log4cxx::RollingFileAppender::registerClass(); SMTPAppender::registerClass(); SocketAppender::registerClass(); #if APR_HAS_THREADS SocketHubAppender::registerClass(); #endif SyslogAppender::registerClass(); #if APR_HAS_THREADS TelnetAppender::registerClass(); #endif XMLSocketAppender::registerClass(); DateLayout::registerClass(); HTMLLayout::registerClass(); PatternLayout::registerClass(); SimpleLayout::registerClass(); TTCCLayout::registerClass(); XMLLayout::registerClass(); LevelMatchFilter::registerClass(); LevelRangeFilter::registerClass(); StringMatchFilter::registerClass(); log4cxx::RollingFileAppender::registerClass(); log4cxx::rolling::RollingFileAppender::registerClass(); DailyRollingFileAppender::registerClass(); log4cxx::rolling::SizeBasedTriggeringPolicy::registerClass(); log4cxx::rolling::TimeBasedRollingPolicy::registerClass(); log4cxx::rolling::ManualTriggeringPolicy::registerClass(); log4cxx::rolling::FixedWindowRollingPolicy::registerClass(); log4cxx::rolling::FilterBasedTriggeringPolicy::registerClass(); log4cxx::xml::DOMConfigurator::registerClass(); log4cxx::PropertyConfigurator::registerClass(); }
001-log4cxx
trunk/src/main/cpp/class.cpp
C++
asf20
6,249
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <log4cxx/logstring.h> #include <log4cxx/helpers/integer.h> using namespace log4cxx; using namespace log4cxx::helpers; IMPLEMENT_LOG4CXX_OBJECT(Integer) Integer::Integer() : val(0){ } Integer::Integer(int val1) : val(val1) { } Integer::~Integer() { }
001-log4cxx
trunk/src/main/cpp/integer.cpp
C++
asf20
1,069
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <log4cxx/writerappender.h> #include <log4cxx/helpers/loglog.h> #include <log4cxx/helpers/synchronized.h> #include <log4cxx/layout.h> #include <log4cxx/helpers/stringhelper.h> using namespace log4cxx; using namespace log4cxx::helpers; using namespace log4cxx::spi; IMPLEMENT_LOG4CXX_OBJECT(WriterAppender) WriterAppender::WriterAppender() { synchronized sync(mutex); immediateFlush = true; } WriterAppender::WriterAppender(const LayoutPtr& layout1, log4cxx::helpers::WriterPtr& writer1) : AppenderSkeleton(layout1), writer(writer1) { Pool p; synchronized sync(mutex); immediateFlush = true; activateOptions(p); } WriterAppender::WriterAppender(const LayoutPtr& layout1) : AppenderSkeleton(layout1) { synchronized sync(mutex); immediateFlush = true; } WriterAppender::~WriterAppender() { finalize(); } void WriterAppender::activateOptions(Pool& p) { int errors = 0; if(layout == 0) { errorHandler->error( ((LogString) LOG4CXX_STR("No layout set for the appender named [")) + name+ LOG4CXX_STR("].")); errors++; } if(writer == 0) { errorHandler->error( ((LogString) LOG4CXX_STR("No writer set for the appender named [")) + name+ LOG4CXX_STR("].")); errors++; } if (errors == 0) { AppenderSkeleton::activateOptions(p); } } void WriterAppender::append(const spi::LoggingEventPtr& event, Pool& pool1) { if(!checkEntryConditions()) { return; } subAppend(event, pool1); } /** This method determines if there is a sense in attempting to append. <p>It checks whether there is a set output target and also if there is a set layout. If these checks fail, then the boolean value <code>false</code> is returned. */ bool WriterAppender::checkEntryConditions() const { static bool warnedClosed = false; static bool warnedNoWriter = false; if (closed) { if(!warnedClosed) { LogLog::warn(LOG4CXX_STR("Not allowed to write to a closed appender.")); warnedClosed = true; } return false; } if (writer == 0) { if (!warnedNoWriter) { LogLog::error( LogString(LOG4CXX_STR("No output stream or file set for the appender named [")) + name + LOG4CXX_STR("].")); warnedNoWriter = true; } return false; } return true; } /** Close this appender instance. The underlying stream or writer is also closed. <p>Closed appenders cannot be reused. @see #setWriter */ void WriterAppender::close() { synchronized sync(mutex); if(closed) { return; } closed = true; closeWriter(); } /** * Close the underlying {@link java.io.Writer}. * */ void WriterAppender::closeWriter() { if (writer != NULL) { try { // before closing we have to output out layout's footer // // Using the object's pool since this is a one-shot operation // and pool is likely to be reclaimed soon when appender is destructed. // writeFooter(pool); writer->close(pool); writer = 0; } catch (IOException& e) { LogLog::error(LogString(LOG4CXX_STR("Could not close writer for WriterAppender named "))+name, e); } } } /** Returns an OutputStreamWriter when passed an OutputStream. The encoding used will depend on the value of the <code>encoding</code> property. If the encoding value is specified incorrectly the writer will be opened using the default system encoding (an error message will be printed to the loglog. */ WriterPtr WriterAppender::createWriter(OutputStreamPtr& os) { LogString enc(getEncoding()); CharsetEncoderPtr encoder; if (enc.empty()) { encoder = CharsetEncoder::getDefaultEncoder(); } else { if(StringHelper::equalsIgnoreCase(enc, LOG4CXX_STR("utf-16"), LOG4CXX_STR("UTF-16"))) { encoder = CharsetEncoder::getEncoder(LOG4CXX_STR("UTF-16BE")); } else { encoder = CharsetEncoder::getEncoder(enc); } if (encoder == NULL) { encoder = CharsetEncoder::getDefaultEncoder(); LogLog::warn(LOG4CXX_STR("Error initializing output writer.")); LogLog::warn(LOG4CXX_STR("Unsupported encoding?")); } } return new OutputStreamWriter(os, encoder); } LogString WriterAppender::getEncoding() const { return encoding; } void WriterAppender::setEncoding(const LogString& enc) { encoding = enc; } void WriterAppender::subAppend(const spi::LoggingEventPtr& event, Pool& p) { LogString msg; layout->format(msg, event, p); { synchronized sync(mutex); if (writer != NULL) { writer->write(msg, p); if (immediateFlush) { writer->flush(p); } } } } void WriterAppender::writeFooter(Pool& p) { if (layout != NULL) { LogString foot; layout->appendFooter(foot, p); synchronized sync(mutex); writer->write(foot, p); } } void WriterAppender::writeHeader(Pool& p) { if(layout != NULL) { LogString header; layout->appendHeader(header, p); synchronized sync(mutex); writer->write(header, p); } } void WriterAppender::setWriter(const WriterPtr& newWriter) { synchronized sync(mutex); writer = newWriter; } bool WriterAppender::requiresLayout() const { return true; } void WriterAppender::setOption(const LogString& option, const LogString& value) { if(StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("ENCODING"), LOG4CXX_STR("encoding"))) { setEncoding(value); } else { AppenderSkeleton::setOption(option, value); } } void WriterAppender::setImmediateFlush(bool value) { synchronized sync(mutex); immediateFlush = value; }
001-log4cxx
trunk/src/main/cpp/writerappender.cpp
C++
asf20
6,840
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #if defined(_MSC_VER) #pragma warning ( disable: 4231 4251 4275 4786 ) #endif #include <log4cxx/logstring.h> #include <log4cxx/helpers/objectoutputstream.h> #include <log4cxx/helpers/bytebuffer.h> #include <log4cxx/helpers/outputstream.h> #include <log4cxx/helpers/charsetencoder.h> #include "apr_pools.h" using namespace log4cxx; using namespace log4cxx::helpers; IMPLEMENT_LOG4CXX_OBJECT(ObjectOutputStream) ObjectOutputStream::ObjectOutputStream(OutputStreamPtr outputStream, Pool& p) : os(outputStream) , utf8Encoder(CharsetEncoder::getUTF8Encoder()), objectHandle(0x7E0000), classDescriptions(new ClassDescriptionMap()) { char start[] = { 0xAC, 0xED, 0x00, 0x05 }; ByteBuffer buf(start, sizeof(start)); os->write(buf, p); } ObjectOutputStream::~ObjectOutputStream() { delete classDescriptions; } void ObjectOutputStream::close(Pool& p) { os->close(p); } void ObjectOutputStream::flush(Pool& p) { os->flush(p); } void ObjectOutputStream::writeObject(const LogString& val, Pool& p) { objectHandle++; writeByte(TC_STRING, p); char bytes[2]; #if LOG4CXX_LOGCHAR_IS_UTF8 size_t len = val.size(); ByteBuffer dataBuf(const_cast<char*>(val.data()), val.size()); #else size_t maxSize = 6 * val.size(); char* data = p.pstralloc(maxSize); ByteBuffer dataBuf(data, maxSize); LogString::const_iterator iter(val.begin()); utf8Encoder->encode(val, iter, dataBuf); dataBuf.flip(); size_t len = dataBuf.limit(); #endif bytes[1] = (char) (len & 0xFF); bytes[0] = (char) ((len >> 8) & 0xFF); ByteBuffer lenBuf(bytes, sizeof(bytes)); os->write(lenBuf, p); os->write(dataBuf, p); } void ObjectOutputStream::writeObject(const MDC::Map& val, Pool& p) { // // TC_OBJECT and the classDesc for java.util.Hashtable // char prolog[] = { 0x72, 0x00, 0x13, 0x6A, 0x61, 0x76, 0x61, 0x2E, 0x75, 0x74, 0x69, 0x6C, 0x2E, 0x48, 0x61, 0x73, 0x68, 0x74, 0x61, 0x62, 0x6C, 0x65, 0x13, 0xBB, 0x0F, 0x25, 0x21, 0x4A, 0xE4, 0xB8, 0x03, 0x00, 0x02, 0x46, 0x00, 0x0A, 0x6C, 0x6F, 0x61, 0x64, 0x46, 0x61, 0x63, 0x74, 0x6F, 0x72, 0x49, 0x00, 0x09, 0x74, 0x68, 0x72, 0x65, 0x73, 0x68, 0x6F, 0x6C, 0x64, 0x78, 0x70 }; writeProlog("java.util.Hashtable", 1, prolog, sizeof(prolog), p); // // loadFactor = 0.75, threshold = 5, blockdata start, buckets.size = 7 char data[] = { 0x3F, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, TC_BLOCKDATA, 0x08, 0x00, 0x00, 0x00, 0x07 }; ByteBuffer dataBuf(data, sizeof(data)); os->write(dataBuf, p); char size[4]; size_t sz = val.size(); size[3] = (char) (sz & 0xFF); size[2] = (char) ((sz >> 8) & 0xFF); size[1] = (char) ((sz >> 16) & 0xFF); size[0] = (char) ((sz >> 24) & 0xFF); ByteBuffer sizeBuf(size, sizeof(size)); os->write(sizeBuf, p); for(MDC::Map::const_iterator iter = val.begin(); iter != val.end(); iter++) { writeObject(iter->first, p); writeObject(iter->second, p); } writeByte(TC_ENDBLOCKDATA, p); } void ObjectOutputStream::writeUTFString(const std::string& val, Pool& p) { char bytes[3]; size_t len = val.size(); ByteBuffer dataBuf(const_cast<char*>(val.data()), val.size()); objectHandle++; bytes[0] = 0x74; bytes[1] = (char) ((len >> 8) & 0xFF); bytes[2] = (char) (len & 0xFF); ByteBuffer lenBuf(bytes, sizeof(bytes)); os->write(lenBuf, p); os->write(dataBuf, p); } void ObjectOutputStream::writeByte(char val, Pool& p) { ByteBuffer buf(&val, 1); os->write(buf, p); } void ObjectOutputStream::writeInt(int val, Pool& p) { char bytes[4]; bytes[3] = (char) (val & 0xFF); bytes[2] = (char) ((val >> 8) & 0xFF); bytes[1] = (char) ((val >> 16) & 0xFF); bytes[0] = (char) ((val >> 24) & 0xFF); ByteBuffer buf(bytes, sizeof(bytes)); os->write(buf, p); } void ObjectOutputStream::writeLong(log4cxx_time_t val, Pool& p) { char bytes[8]; bytes[7] = (char) (val & 0xFF); bytes[6] = (char) ((val >> 8) & 0xFF); bytes[5] = (char) ((val >> 16) & 0xFF); bytes[4] = (char) ((val >> 24) & 0xFF); bytes[3] = (char) ((val >> 32) & 0xFF); bytes[2] = (char) ((val >> 40) & 0xFF); bytes[1] = (char) ((val >> 48) & 0xFF); bytes[0] = (char) ((val >> 56) & 0xFF); ByteBuffer buf(bytes, sizeof(bytes)); os->write(buf, p); } void ObjectOutputStream::writeBytes(const char* bytes, size_t len, Pool& p) { ByteBuffer buf(const_cast<char*>(bytes), len); os->write(buf, p); } void ObjectOutputStream::writeNull(Pool& p) { writeByte(TC_NULL, p); } void ObjectOutputStream::writeProlog(const char* className, int classDescIncrement, char* classDesc, size_t len, Pool& p) { ClassDescriptionMap::const_iterator match = classDescriptions->find(className); if (match != classDescriptions->end()) { char bytes[6]; bytes[0] = TC_OBJECT; bytes[1] = TC_REFERENCE; bytes[2] = (char) ((match->second >> 24) & 0xFF); bytes[3] = (char) ((match->second >> 16) & 0xFF); bytes[4] = (char) ((match->second >> 8) & 0xFF); bytes[5] = (char) (match->second & 0xFF); ByteBuffer buf(bytes, sizeof(bytes)); os->write(buf, p); objectHandle++; } else { classDescriptions->insert(ClassDescriptionMap::value_type(className, objectHandle)); writeByte(TC_OBJECT, p); ByteBuffer buf(classDesc, len); os->write(buf, p); objectHandle += (classDescIncrement + 1); } }
001-log4cxx
trunk/src/main/cpp/objectoutputstream.cpp
C++
asf20
6,480
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <log4cxx/spi/loggingevent.h> #include <log4cxx/appenderskeleton.h> #include <log4cxx/helpers/loglog.h> #include <log4cxx/helpers/onlyonceerrorhandler.h> #include <log4cxx/level.h> #include <log4cxx/helpers/stringhelper.h> #include <log4cxx/helpers/synchronized.h> #include <apr_atomic.h> using namespace log4cxx; using namespace log4cxx::spi; using namespace log4cxx::helpers; IMPLEMENT_LOG4CXX_OBJECT(AppenderSkeleton) AppenderSkeleton::AppenderSkeleton() : layout(), name(), threshold(Level::getAll()), errorHandler(new OnlyOnceErrorHandler()), headFilter(), tailFilter(), pool(), mutex(pool) { synchronized sync(mutex); closed = false; } AppenderSkeleton::AppenderSkeleton(const LayoutPtr& layout1) : layout(layout1), name(), threshold(Level::getAll()), errorHandler(new OnlyOnceErrorHandler()), headFilter(), tailFilter(), pool(), mutex(pool) { synchronized sync(mutex); closed = false; } void AppenderSkeleton::addRef() const { ObjectImpl::addRef(); } void AppenderSkeleton::releaseRef() const { ObjectImpl::releaseRef(); } void AppenderSkeleton::finalize() { // An appender might be closed then garbage collected. There is no // point in closing twice. if(closed) { return; } close(); } void AppenderSkeleton::addFilter(const spi::FilterPtr& newFilter) { synchronized sync(mutex); if(headFilter == 0) { headFilter = tailFilter = newFilter; } else { tailFilter->setNext(newFilter); tailFilter = newFilter; } } void AppenderSkeleton::clearFilters() { synchronized sync(mutex); headFilter = tailFilter = 0; } bool AppenderSkeleton::isAsSevereAsThreshold(const LevelPtr& level) const { return ((level == 0) || level->isGreaterOrEqual(threshold)); } void AppenderSkeleton::doAppend(const spi::LoggingEventPtr& event, Pool& pool1) { synchronized sync(mutex); if(closed) { LogLog::error(((LogString) LOG4CXX_STR("Attempted to append to closed appender named [")) + name + LOG4CXX_STR("].")); return; } if(!isAsSevereAsThreshold(event->getLevel())) { return; } FilterPtr f = headFilter; while(f != 0) { switch(f->decide(event)) { case Filter::DENY: return; case Filter::ACCEPT: f = 0; break; case Filter::NEUTRAL: f = f->getNext(); } } append(event, pool1); } void AppenderSkeleton::setErrorHandler(const spi::ErrorHandlerPtr& errorHandler1) { synchronized sync(mutex); if(errorHandler1 == 0) { // We do not throw exception here since the cause is probably a // bad config file. LogLog::warn(LOG4CXX_STR("You have tried to set a null error-handler.")); } else { this->errorHandler = errorHandler1; } } void AppenderSkeleton::setThreshold(const LevelPtr& threshold1) { synchronized sync(mutex); this->threshold = threshold1; } void AppenderSkeleton::setOption(const LogString& option, const LogString& value) { if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("THRESHOLD"), LOG4CXX_STR("threshold"))) { setThreshold(Level::toLevelLS(value)); } }
001-log4cxx
trunk/src/main/cpp/appenderskeleton.cpp
C++
asf20
4,552
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <log4cxx/logstring.h> #include <log4cxx/layout.h> using namespace log4cxx; using namespace log4cxx::helpers; IMPLEMENT_LOG4CXX_OBJECT(Layout) Layout::~Layout() {} void Layout::addRef() const { ObjectImpl::addRef(); } void Layout::releaseRef() const { ObjectImpl::releaseRef(); } LogString Layout::getContentType() const { return LOG4CXX_STR("text/plain"); } void Layout::appendHeader(LogString&, log4cxx::helpers::Pool&) {} void Layout::appendFooter(LogString&, log4cxx::helpers::Pool&) {}
001-log4cxx
trunk/src/main/cpp/layout.cpp
C++
asf20
1,321
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <log4cxx/logstring.h> #include <log4cxx/helpers/datelayout.h> #include <log4cxx/helpers/stringhelper.h> #include <log4cxx/spi/loggingevent.h> #include <log4cxx/helpers/dateformat.h> #include <log4cxx/helpers/relativetimedateformat.h> #include <log4cxx/helpers/absolutetimedateformat.h> #include <log4cxx/helpers/datetimedateformat.h> #include <log4cxx/helpers/iso8601dateformat.h> #include <log4cxx/helpers/timezone.h> using namespace log4cxx; using namespace log4cxx::helpers; using namespace log4cxx::spi; DateLayout::DateLayout(const LogString& dateFormatOption1) : timeZoneID(), dateFormatOption(dateFormatOption1), dateFormat(0) { } DateLayout::~DateLayout() { } void DateLayout::setOption(const LogString& option, const LogString& value) { if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("DATEFORMAT"), LOG4CXX_STR("dateformat"))) { dateFormatOption = value; } else if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("TIMEZONE"), LOG4CXX_STR("timezone"))) { timeZoneID = value; } } void DateLayout::activateOptions(Pool&) { if(!dateFormatOption.empty()) { if(dateFormatOption.empty()) { dateFormat = 0; } else if(StringHelper::equalsIgnoreCase(dateFormatOption, LOG4CXX_STR("NULL"), LOG4CXX_STR("null"))) { dateFormat = 0; dateFormatOption = LOG4CXX_STR("NULL"); } else if(StringHelper::equalsIgnoreCase(dateFormatOption, LOG4CXX_STR("RELATIVE"), LOG4CXX_STR("relative"))) { dateFormat = new RelativeTimeDateFormat(); dateFormatOption = LOG4CXX_STR("RELATIVE"); } else if(StringHelper::equalsIgnoreCase(dateFormatOption, LOG4CXX_STR("ABSOLUTE"), LOG4CXX_STR("absolute"))) { dateFormat = new AbsoluteTimeDateFormat(); dateFormatOption = LOG4CXX_STR("ABSOLUTE"); } else if(StringHelper::equalsIgnoreCase(dateFormatOption, LOG4CXX_STR("DATE"), LOG4CXX_STR("date"))) { dateFormat = new DateTimeDateFormat(); dateFormatOption = LOG4CXX_STR("DATE"); } else if(StringHelper::equalsIgnoreCase(dateFormatOption, LOG4CXX_STR("ISO8601"), LOG4CXX_STR("iso8601"))) { dateFormat = new ISO8601DateFormat(); dateFormatOption = LOG4CXX_STR("iso8601"); } else { dateFormat = new SimpleDateFormat(dateFormatOption); } } if (dateFormat != NULL) { if (timeZoneID.empty()) { dateFormat->setTimeZone(TimeZone::getDefault()); } else { dateFormat->setTimeZone(TimeZone::getTimeZone(timeZoneID)); } } } void DateLayout::formatDate(LogString &s, const spi::LoggingEventPtr& event, Pool& p) const { if(dateFormat != 0) { dateFormat->format(s, event->getTimeStamp(), p); s.append(1, (logchar) 0x20 /* ' ' */); } }
001-log4cxx
trunk/src/main/cpp/datelayout.cpp
C++
asf20
4,177
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <log4cxx/logstring.h> #include <log4cxx/helpers/synchronized.h> #include <log4cxx/helpers/mutex.h> #include <log4cxx/helpers/exception.h> #include <apr_thread_mutex.h> using namespace log4cxx::helpers; using namespace log4cxx; synchronized::synchronized(const Mutex& mutex1) : mutex(mutex1.getAPRMutex()) { #if APR_HAS_THREADS apr_status_t stat = apr_thread_mutex_lock( (apr_thread_mutex_t*) this->mutex); if (stat != APR_SUCCESS) { throw MutexException(stat); } #endif } synchronized::~synchronized() { #if APR_HAS_THREADS apr_status_t stat = apr_thread_mutex_unlock( (apr_thread_mutex_t*) mutex); if (stat != APR_SUCCESS) { throw MutexException(stat); } #endif }
001-log4cxx
trunk/src/main/cpp/synchronized.cpp
C++
asf20
1,586
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <log4cxx/logstring.h> #include <log4cxx/logger.h> #include <log4cxx/spi/loggingevent.h> #include <log4cxx/logmanager.h> #include <log4cxx/spi/loggerfactory.h> #include <log4cxx/appender.h> #include <log4cxx/level.h> #include <log4cxx/helpers/loglog.h> #include <log4cxx/spi/loggerrepository.h> #include <log4cxx/helpers/stringhelper.h> #include <log4cxx/helpers/synchronized.h> #include <log4cxx/helpers/transcoder.h> #include <log4cxx/helpers/appenderattachableimpl.h> #include <log4cxx/helpers/exception.h> #if !defined(LOG4CXX) #define LOG4CXX 1 #endif #include <log4cxx/private/log4cxx_private.h> #include <log4cxx/helpers/aprinitializer.h> using namespace log4cxx; using namespace log4cxx::helpers; using namespace log4cxx::spi; IMPLEMENT_LOG4CXX_OBJECT(Logger) Logger::Logger(Pool& p, const LogString& name1) : pool(&p), name(), level(), parent(), resourceBundle(), repository(), aai(), mutex(p) { synchronized sync(mutex); name = name1; additive = true; } Logger::~Logger() { } void Logger::addRef() const { ObjectImpl::addRef(); } void Logger::releaseRef() const { ObjectImpl::releaseRef(); } void Logger::addAppender(const AppenderPtr& newAppender) { synchronized sync(mutex); if (aai == 0) { aai = new AppenderAttachableImpl(*pool); } aai->addAppender(newAppender); if (repository != 0) { repository->fireAddAppenderEvent(this, newAppender); } } void Logger::callAppenders(const spi::LoggingEventPtr& event, Pool& p) const { int writes = 0; for(LoggerPtr logger(const_cast<Logger*>(this)); logger != 0; logger = logger->parent) { // Protected against simultaneous call to addAppender, removeAppender,... synchronized sync(logger->mutex); if (logger->aai != 0) { writes += logger->aai->appendLoopOnAppenders(event, p); } if(!logger->additive) { break; } } if(writes == 0 && repository != 0) { repository->emitNoAppenderWarning(const_cast<Logger*>(this)); } } void Logger::closeNestedAppenders() { AppenderList appenders = getAllAppenders(); for(AppenderList::iterator it=appenders.begin(); it!=appenders.end(); ++it) { (*it)->close(); } } void Logger::forcedLog(const LevelPtr& level1, const std::string& message, const LocationInfo& location) const { Pool p; LOG4CXX_DECODE_CHAR(msg, message); LoggingEventPtr event(new LoggingEvent(name, level1, msg, location)); callAppenders(event, p); } void Logger::forcedLog(const LevelPtr& level1, const std::string& message) const { Pool p; LOG4CXX_DECODE_CHAR(msg, message); LoggingEventPtr event(new LoggingEvent(name, level1, msg, LocationInfo::getLocationUnavailable())); callAppenders(event, p); } void Logger::forcedLogLS(const LevelPtr& level1, const LogString& message, const LocationInfo& location) const { Pool p; LoggingEventPtr event(new LoggingEvent(name, level1, message, location)); callAppenders(event, p); } bool Logger::getAdditivity() const { return additive; } AppenderList Logger::getAllAppenders() const { synchronized sync(mutex); if (aai == 0) { return AppenderList(); } else { return aai->getAllAppenders(); } } AppenderPtr Logger::getAppender(const LogString& name1) const { synchronized sync(mutex); if (aai == 0 || name1.empty()) { return 0; } return aai->getAppender(name1); } const LevelPtr& Logger::getEffectiveLevel() const { for(const Logger * l = this; l != 0; l=l->parent) { if(l->level != 0) { return l->level; } } throw NullPointerException(LOG4CXX_STR("No level specified for logger or ancestors.")); #if LOG4CXX_RETURN_AFTER_THROW return this->level; #endif } LoggerRepositoryPtr Logger::getLoggerRepository() const { return repository; } ResourceBundlePtr Logger::getResourceBundle() const { for (LoggerPtr l(const_cast<Logger*>(this)); l != 0; l = l->parent) { if (l->resourceBundle != 0) { return l->resourceBundle; } } // It might be the case that there is no resource bundle return 0; } LogString Logger::getResourceBundleString(const LogString& key) const { ResourceBundlePtr rb = getResourceBundle(); // This is one of the rare cases where we can use logging in order // to report errors from within log4j. if (rb == 0) { return LogString(); } else { try { return rb->getString(key); } catch (MissingResourceException&) { logLS(Level::getError(), LOG4CXX_STR("No resource is associated with key \"") + key + LOG4CXX_STR("\"."), LocationInfo::getLocationUnavailable()); return LogString(); } } } LoggerPtr Logger::getParent() const { return parent; } LevelPtr Logger::getLevel() const { return level; } bool Logger::isAttached(const AppenderPtr& appender) const { synchronized sync(mutex); if (appender == 0 || aai == 0) { return false; } else { return aai->isAttached(appender); } } bool Logger::isTraceEnabled() const { if(repository == 0 || repository->isDisabled(Level::TRACE_INT)) { return false; } return getEffectiveLevel()->toInt() <= Level::TRACE_INT; } bool Logger::isDebugEnabled() const { if(repository == 0 || repository->isDisabled(Level::DEBUG_INT)) { return false; } return getEffectiveLevel()->toInt() <= Level::DEBUG_INT; } bool Logger::isEnabledFor(const LevelPtr& level1) const { if(repository == 0 || repository->isDisabled(level1->toInt())) { return false; } return level1->isGreaterOrEqual(getEffectiveLevel()); } bool Logger::isInfoEnabled() const { if(repository == 0 || repository->isDisabled(Level::INFO_INT)) { return false; } return getEffectiveLevel()->toInt() <= Level::INFO_INT; } bool Logger::isErrorEnabled() const { if(repository == 0 || repository->isDisabled(Level::ERROR_INT)) { return false; } return getEffectiveLevel()->toInt() <= Level::ERROR_INT; } bool Logger::isWarnEnabled() const { if(repository == 0 || repository->isDisabled(Level::WARN_INT)) { return false; } return getEffectiveLevel()->toInt() <= Level::WARN_INT; } bool Logger::isFatalEnabled() const { if(repository == 0 || repository->isDisabled(Level::FATAL_INT)) { return false; } return getEffectiveLevel()->toInt() <= Level::FATAL_INT; } /*void Logger::l7dlog(const LevelPtr& level, const String& key, const char* file, int line) { if (repository == 0 || repository->isDisabled(level->level)) { return; } if (level->isGreaterOrEqual(getEffectiveLevel())) { String msg = getResourceBundleString(key); // if message corresponding to 'key' could not be found in the // resource bundle, then default to 'key'. if (msg.empty()) { msg = key; } forcedLog(FQCN, level, msg, file, line); } }*/ void Logger::l7dlog(const LevelPtr& level1, const LogString& key, const LocationInfo& location, const std::vector<LogString>& params) const { if (repository == 0 || repository->isDisabled(level1->toInt())) { return; } if (level1->isGreaterOrEqual(getEffectiveLevel())) { LogString pattern = getResourceBundleString(key); LogString msg; if (pattern.empty()) { msg = key; } else { msg = StringHelper::format(pattern, params); } forcedLogLS(level1, msg, location); } } void Logger::l7dlog(const LevelPtr& level1, const std::string& key, const LocationInfo& location) const { LOG4CXX_DECODE_CHAR(lkey, key); std::vector<LogString> values(0); l7dlog(level1, lkey, location, values); } void Logger::l7dlog(const LevelPtr& level1, const std::string& key, const LocationInfo& location, const std::string& val1) const { LOG4CXX_DECODE_CHAR(lkey, key); LOG4CXX_DECODE_CHAR(lval1, val1); std::vector<LogString> values(1); values[0] = lval1; l7dlog(level1, lkey, location, values); } void Logger::l7dlog(const LevelPtr& level1, const std::string& key, const LocationInfo& location, const std::string& val1, const std::string& val2) const { LOG4CXX_DECODE_CHAR(lkey, key); LOG4CXX_DECODE_CHAR(lval1, val1); LOG4CXX_DECODE_CHAR(lval2, val2); std::vector<LogString> values(2); values[0] = lval1; values[1] = lval2; l7dlog(level1, lkey, location, values); } void Logger::l7dlog(const LevelPtr& level1, const std::string& key, const LocationInfo& location, const std::string& val1, const std::string& val2, const std::string& val3) const { LOG4CXX_DECODE_CHAR(lkey, key); LOG4CXX_DECODE_CHAR(lval1, val1); LOG4CXX_DECODE_CHAR(lval2, val2); LOG4CXX_DECODE_CHAR(lval3, val3); std::vector<LogString> values(3); values[0] = lval1; values[1] = lval2; values[3] = lval3; l7dlog(level1, lkey, location, values); } void Logger::removeAllAppenders() { synchronized sync(mutex); if(aai != 0) { aai->removeAllAppenders(); aai = 0; } } void Logger::removeAppender(const AppenderPtr& appender) { synchronized sync(mutex); if(appender == 0 || aai == 0) { return; } aai->removeAppender(appender); } void Logger::removeAppender(const LogString& name1) { synchronized sync(mutex); if(name1.empty() || aai == 0) { return; } aai->removeAppender(name1); } void Logger::setAdditivity(bool additive1) { synchronized sync(mutex); this->additive = additive1; } void Logger::setHierarchy(spi::LoggerRepository * repository1) { this->repository = repository1; } void Logger::setLevel(const LevelPtr& level1) { this->level = level1; } LoggerPtr Logger::getLogger(const std::string& name) { return LogManager::getLogger(name); } LoggerPtr Logger::getLogger(const char* const name) { return LogManager::getLogger(name); } LoggerPtr Logger::getRootLogger() { return LogManager::getRootLogger(); } LoggerPtr Logger::getLoggerLS(const LogString& name, const spi::LoggerFactoryPtr& factory) { return LogManager::getLoggerLS(name, factory); } void Logger::getName(std::string& rv) const { Transcoder::encode(name, rv); } void Logger::trace(const std::string& msg, const log4cxx::spi::LocationInfo& location) const { if (isTraceEnabled()) { forcedLog(log4cxx::Level::getTrace(), msg, location); } } void Logger::trace(const std::string& msg) const { if (isTraceEnabled()) { forcedLog(log4cxx::Level::getTrace(), msg); } } void Logger::debug(const std::string& msg, const log4cxx::spi::LocationInfo& location) const { if (isDebugEnabled()) { forcedLog(log4cxx::Level::getDebug(), msg, location); } } void Logger::debug(const std::string& msg) const { if (isDebugEnabled()) { forcedLog(log4cxx::Level::getDebug(), msg); } } void Logger::error(const std::string& msg, const log4cxx::spi::LocationInfo& location) const { if (isErrorEnabled()) { forcedLog(log4cxx::Level::getError(), msg, location); } } void Logger::error(const std::string& msg) const { if (isErrorEnabled()) { forcedLog(log4cxx::Level::getError(), msg); } } void Logger::fatal(const std::string& msg, const log4cxx::spi::LocationInfo& location) const { if (isFatalEnabled()) { forcedLog(log4cxx::Level::getFatal(), msg, location); } } void Logger::fatal(const std::string& msg) const { if (isFatalEnabled()) { forcedLog(log4cxx::Level::getFatal(), msg); } } void Logger::info(const std::string& msg, const log4cxx::spi::LocationInfo& location) const { if (isInfoEnabled()) { forcedLog(log4cxx::Level::getInfo(), msg, location); } } void Logger::info(const std::string& msg) const { if (isInfoEnabled()) { forcedLog(log4cxx::Level::getInfo(), msg); } } void Logger::log(const LevelPtr& level1, const std::string& message, const log4cxx::spi::LocationInfo& location) const { if (isEnabledFor(level1)) { forcedLog(level1, message, location); } } void Logger::log(const LevelPtr& level1, const std::string& message) const { if (isEnabledFor(level1)) { forcedLog(level1, message); } } void Logger::logLS(const LevelPtr& level1, const LogString& message, const log4cxx::spi::LocationInfo& location) const { if (isEnabledFor(level1)) { forcedLogLS(level1, message, location); } } void Logger::warn(const std::string& msg, const log4cxx::spi::LocationInfo& location) const { if (isWarnEnabled()) { forcedLog(log4cxx::Level::getWarn(), msg, location); } } void Logger::warn(const std::string& msg) const { if (isWarnEnabled()) { forcedLog(log4cxx::Level::getWarn(), msg); } } LoggerPtr Logger::getLoggerLS(const LogString& name) { return LogManager::getLoggerLS(name); } #if LOG4CXX_WCHAR_T_API void Logger::forcedLog(const LevelPtr& level1, const std::wstring& message, const LocationInfo& location) const { Pool p; LOG4CXX_DECODE_WCHAR(msg, message); LoggingEventPtr event(new LoggingEvent(name, level1, msg, location)); callAppenders(event, p); } void Logger::forcedLog(const LevelPtr& level1, const std::wstring& message) const { Pool p; LOG4CXX_DECODE_WCHAR(msg, message); LoggingEventPtr event(new LoggingEvent(name, level1, msg, LocationInfo::getLocationUnavailable())); callAppenders(event, p); } void Logger::getName(std::wstring& rv) const { Transcoder::encode(name, rv); } LoggerPtr Logger::getLogger(const std::wstring& name) { return LogManager::getLogger(name); } LoggerPtr Logger::getLogger(const wchar_t* const name) { return LogManager::getLogger(name); } void Logger::trace(const std::wstring& msg, const log4cxx::spi::LocationInfo& location) const { if (isTraceEnabled()) { forcedLog(log4cxx::Level::getTrace(), msg, location); } } void Logger::trace(const std::wstring& msg) const { if (isTraceEnabled()) { forcedLog(log4cxx::Level::getTrace(), msg); } } void Logger::debug(const std::wstring& msg, const log4cxx::spi::LocationInfo& location) const { if (isDebugEnabled()) { forcedLog(log4cxx::Level::getDebug(), msg, location); } } void Logger::debug(const std::wstring& msg) const { if (isDebugEnabled()) { forcedLog(log4cxx::Level::getDebug(), msg); } } void Logger::error(const std::wstring& msg, const log4cxx::spi::LocationInfo& location) const { if (isErrorEnabled()) { forcedLog(log4cxx::Level::getError(), msg, location); } } void Logger::error(const std::wstring& msg) const { if (isErrorEnabled()) { forcedLog(log4cxx::Level::getError(), msg); } } void Logger::fatal(const std::wstring& msg, const log4cxx::spi::LocationInfo& location) const { if (isFatalEnabled()) { forcedLog(log4cxx::Level::getFatal(), msg, location); } } void Logger::fatal(const std::wstring& msg) const { if (isFatalEnabled()) { forcedLog(log4cxx::Level::getFatal(), msg); } } void Logger::info(const std::wstring& msg, const log4cxx::spi::LocationInfo& location) const { if (isInfoEnabled()) { forcedLog(log4cxx::Level::getInfo(), msg, location); } } void Logger::info(const std::wstring& msg) const { if (isInfoEnabled()) { forcedLog(log4cxx::Level::getInfo(), msg); } } void Logger::log(const LevelPtr& level1, const std::wstring& message, const log4cxx::spi::LocationInfo& location) const { if (isEnabledFor(level1)) { forcedLog(level1, message, location); } } void Logger::log(const LevelPtr& level1, const std::wstring& message) const { if (isEnabledFor(level1)) { forcedLog(level1, message); } } void Logger::warn(const std::wstring& msg, const log4cxx::spi::LocationInfo& location) const { if (isWarnEnabled()) { forcedLog(log4cxx::Level::getWarn(), msg, location); } } void Logger::warn(const std::wstring& msg) const { if (isWarnEnabled()) { forcedLog(log4cxx::Level::getWarn(), msg); } } #endif #if LOG4CXX_UNICHAR_API || LOG4CXX_CFSTRING_API void Logger::forcedLog(const LevelPtr& level1, const std::basic_string<UniChar>& message, const LocationInfo& location) const { Pool p; LOG4CXX_DECODE_UNICHAR(msg, message); LoggingEventPtr event(new LoggingEvent(name, level1, msg, location)); callAppenders(event, p); } void Logger::forcedLog(const LevelPtr& level1, const std::basic_string<UniChar>& message) const { Pool p; LOG4CXX_DECODE_UNICHAR(msg, message); LoggingEventPtr event(new LoggingEvent(name, level1, msg, LocationInfo::getLocationUnavailable())); callAppenders(event, p); } #endif #if LOG4CXX_UNICHAR_API void Logger::getName(std::basic_string<UniChar>& rv) const { Transcoder::encode(name, rv); } LoggerPtr Logger::getLogger(const std::basic_string<UniChar>& name) { return LogManager::getLogger(name); } void Logger::trace(const std::basic_string<UniChar>& msg, const log4cxx::spi::LocationInfo& location) const { if (isTraceEnabled()) { forcedLog(log4cxx::Level::getTrace(), msg, location); } } void Logger::trace(const std::basic_string<UniChar>& msg) const { if (isTraceEnabled()) { forcedLog(log4cxx::Level::getTrace(), msg); } } void Logger::debug(const std::basic_string<UniChar>& msg, const log4cxx::spi::LocationInfo& location) const { if (isDebugEnabled()) { forcedLog(log4cxx::Level::getDebug(), msg, location); } } void Logger::debug(const std::basic_string<UniChar>& msg) const { if (isDebugEnabled()) { forcedLog(log4cxx::Level::getDebug(), msg); } } void Logger::error(const std::basic_string<UniChar>& msg, const log4cxx::spi::LocationInfo& location) const { if (isErrorEnabled()) { forcedLog(log4cxx::Level::getError(), msg, location); } } void Logger::error(const std::basic_string<UniChar>& msg) const { if (isErrorEnabled()) { forcedLog(log4cxx::Level::getError(), msg); } } void Logger::fatal(const std::basic_string<UniChar>& msg, const log4cxx::spi::LocationInfo& location) const { if (isFatalEnabled()) { forcedLog(log4cxx::Level::getFatal(), msg, location); } } void Logger::fatal(const std::basic_string<UniChar>& msg) const { if (isFatalEnabled()) { forcedLog(log4cxx::Level::getFatal(), msg); } } void Logger::info(const std::basic_string<UniChar>& msg, const log4cxx::spi::LocationInfo& location) const { if (isInfoEnabled()) { forcedLog(log4cxx::Level::getInfo(), msg, location); } } void Logger::info(const std::basic_string<UniChar>& msg) const { if (isInfoEnabled()) { forcedLog(log4cxx::Level::getInfo(), msg); } } void Logger::log(const LevelPtr& level1, const std::basic_string<UniChar>& message, const log4cxx::spi::LocationInfo& location) const { if (isEnabledFor(level1)) { forcedLog(level1, message, location); } } void Logger::log(const LevelPtr& level1, const std::basic_string<UniChar>& message) const { if (isEnabledFor(level1)) { forcedLog(level1, message); } } void Logger::warn(const std::basic_string<UniChar>& msg, const log4cxx::spi::LocationInfo& location) const { if (isWarnEnabled()) { forcedLog(log4cxx::Level::getWarn(), msg, location); } } void Logger::warn(const std::basic_string<UniChar>& msg) const { if (isWarnEnabled()) { forcedLog(log4cxx::Level::getWarn(), msg); } } #endif #if LOG4CXX_CFSTRING_API void Logger::forcedLog(const LevelPtr& level1, const CFStringRef& message, const LocationInfo& location) const { Pool p; LOG4CXX_DECODE_CFSTRING(msg, message); LoggingEventPtr event(new LoggingEvent(name, level1, msg, location)); callAppenders(event, p); } void Logger::forcedLog(const LevelPtr& level1, const CFStringRef& message) const { Pool p; LOG4CXX_DECODE_CFSTRING(msg, message); LoggingEventPtr event(new LoggingEvent(name, level1, msg, LocationInfo::getLocationUnavailable())); callAppenders(event, p); } void Logger::getName(CFStringRef& rv) const { rv = Transcoder::encode(name); } LoggerPtr Logger::getLogger(const CFStringRef& name) { return LogManager::getLogger(name); } void Logger::trace(const CFStringRef& msg, const log4cxx::spi::LocationInfo& location) const { if (isTraceEnabled()) { forcedLog(log4cxx::Level::getTrace(), msg, location); } } void Logger::trace(const CFStringRef& msg) const { if (isTraceEnabled()) { forcedLog(log4cxx::Level::getTrace(), msg); } } void Logger::debug(const CFStringRef& msg, const log4cxx::spi::LocationInfo& location) const { if (isDebugEnabled()) { forcedLog(log4cxx::Level::getDebug(), msg, location); } } void Logger::debug(const CFStringRef& msg) const { if (isDebugEnabled()) { forcedLog(log4cxx::Level::getDebug(), msg); } } void Logger::error(const CFStringRef& msg, const log4cxx::spi::LocationInfo& location) const { if (isErrorEnabled()) { forcedLog(log4cxx::Level::getError(), msg, location); } } void Logger::error(const CFStringRef& msg) const { if (isErrorEnabled()) { forcedLog(log4cxx::Level::getError(), msg); } } void Logger::fatal(const CFStringRef& msg, const log4cxx::spi::LocationInfo& location) const { if (isFatalEnabled()) { forcedLog(log4cxx::Level::getFatal(), msg, location); } } void Logger::fatal(const CFStringRef& msg) const { if (isFatalEnabled()) { forcedLog(log4cxx::Level::getFatal(), msg); } } void Logger::info(const CFStringRef& msg, const log4cxx::spi::LocationInfo& location) const { if (isInfoEnabled()) { forcedLog(log4cxx::Level::getInfo(), msg, location); } } void Logger::info(const CFStringRef& msg) const { if (isInfoEnabled()) { forcedLog(log4cxx::Level::getInfo(), msg); } } void Logger::log(const LevelPtr& level1, const CFStringRef& message, const log4cxx::spi::LocationInfo& location) const { if (isEnabledFor(level1)) { forcedLog(level1, message, location); } } void Logger::log(const LevelPtr& level1, const CFStringRef& message) const { if (isEnabledFor(level1)) { forcedLog(level1, message); } } void Logger::warn(const CFStringRef& msg, const log4cxx::spi::LocationInfo& location) const { if (isWarnEnabled()) { forcedLog(log4cxx::Level::getWarn(), msg, location); } } void Logger::warn(const CFStringRef& msg) const { if (isWarnEnabled()) { forcedLog(log4cxx::Level::getWarn(), msg); } } #endif
001-log4cxx
trunk/src/main/cpp/logger.cpp
C++
asf20
24,986
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <log4cxx/logstring.h> #include <log4cxx/basicconfigurator.h> #include <log4cxx/patternlayout.h> #include <log4cxx/consoleappender.h> #include <log4cxx/logmanager.h> #include <log4cxx/logger.h> using namespace log4cxx; void BasicConfigurator::configure() { LogManager::getLoggerRepository()->setConfigured(true); LoggerPtr root = Logger::getRootLogger(); static const LogString TTCC_CONVERSION_PATTERN(LOG4CXX_STR("%r [%t] %p %c %x - %m%n")); LayoutPtr layout(new PatternLayout(TTCC_CONVERSION_PATTERN)); AppenderPtr appender(new ConsoleAppender(layout)); root->addAppender(appender); } void BasicConfigurator::configure(const AppenderPtr& appender) { LoggerPtr root = Logger::getRootLogger(); root->addAppender(appender); } void BasicConfigurator::resetConfiguration() { LogManager::resetConfiguration(); }
001-log4cxx
trunk/src/main/cpp/basicconfigurator.cpp
C++
asf20
1,655
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #if defined(_MSC_VER) #pragma warning ( disable: 4231 4251 4275 4786 ) #endif #include <log4cxx/logstring.h> #include <log4cxx/pattern/filedatepatternconverter.h> #include <log4cxx/pattern/datepatternconverter.h> using namespace log4cxx; using namespace log4cxx::pattern; using namespace log4cxx::spi; using namespace log4cxx::helpers; PatternConverterPtr FileDatePatternConverter::newInstance( const std::vector<LogString>& options) { if (options.size() == 0) { std::vector<LogString> altOptions; altOptions.push_back(LOG4CXX_STR("yyyy-MM-dd")); return DatePatternConverter::newInstance(altOptions); } return DatePatternConverter::newInstance(options); }
001-log4cxx
trunk/src/main/cpp/filedatepatternconverter.cpp
C++
asf20
1,490
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <log4cxx/logstring.h> #include <log4cxx/helpers/bytearrayoutputstream.h> #include <log4cxx/helpers/exception.h> #include <log4cxx/helpers/bytebuffer.h> #include <string.h> using namespace log4cxx; using namespace log4cxx::helpers; IMPLEMENT_LOG4CXX_OBJECT(ByteArrayOutputStream) ByteArrayOutputStream::ByteArrayOutputStream() { } ByteArrayOutputStream::~ByteArrayOutputStream() { } void ByteArrayOutputStream::close(Pool& /* p */) { } void ByteArrayOutputStream::flush(Pool& /* p */) { } void ByteArrayOutputStream::write(ByteBuffer& buf, Pool& /* p */ ) { size_t sz = array.size(); array.resize(sz + buf.remaining()); memcpy(&array[sz], buf.current(), buf.remaining()); buf.position(buf.limit()); } std::vector<unsigned char> ByteArrayOutputStream::toByteArray() const { return array; }
001-log4cxx
trunk/src/main/cpp/bytearrayoutputstream.cpp
C++
asf20
1,622
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <log4cxx/logstring.h> #include <log4cxx/spi/loggingevent.h> #include <log4cxx/filter/levelmatchfilter.h> #include <log4cxx/helpers/stringhelper.h> #include <log4cxx/helpers/optionconverter.h> #include <log4cxx/level.h> using namespace log4cxx; using namespace log4cxx::filter; using namespace log4cxx::spi; using namespace log4cxx::helpers; IMPLEMENT_LOG4CXX_OBJECT(LevelMatchFilter) LevelMatchFilter::LevelMatchFilter() : acceptOnMatch(true) { } void LevelMatchFilter::setOption(const LogString& option, const LogString& value) { if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("LEVELTOMATCH"), LOG4CXX_STR("leveltomatch"))) { setLevelToMatch(value); } else if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("ACCEPTONMATCH"), LOG4CXX_STR("acceptonmatch"))) { acceptOnMatch = OptionConverter::toBoolean(value, acceptOnMatch); } } void LevelMatchFilter::setLevelToMatch(const LogString& levelToMatch1) { this->levelToMatch = OptionConverter::toLevel(levelToMatch1, this->levelToMatch); } LogString LevelMatchFilter::getLevelToMatch() const { return levelToMatch->toString(); } Filter::FilterDecision LevelMatchFilter::decide( const log4cxx::spi::LoggingEventPtr& event) const { if(levelToMatch != 0 && levelToMatch->equals(event->getLevel())) { if(acceptOnMatch) { return Filter::ACCEPT; } else { return Filter::DENY; } } else { return Filter::NEUTRAL; } }
001-log4cxx
trunk/src/main/cpp/levelmatchfilter.cpp
C++
asf20
2,338
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #if defined(_MSC_VER) #pragma warning ( disable: 4231 4251 4275 4786 ) #endif #include <log4cxx/logstring.h> #include <log4cxx/pattern/literalpatternconverter.h> #include <log4cxx/spi/loggingevent.h> #include <log4cxx/spi/location/locationinfo.h> using namespace log4cxx; using namespace log4cxx::pattern; using namespace log4cxx::spi; using namespace log4cxx::helpers; IMPLEMENT_LOG4CXX_OBJECT(LiteralPatternConverter) LiteralPatternConverter::LiteralPatternConverter(const LogString& literal1) : LoggingEventPatternConverter(LOG4CXX_STR("Literal"),LOG4CXX_STR("literal")), literal(literal1) { } PatternConverterPtr LiteralPatternConverter::newInstance( const LogString& literal) { if (literal.length() == 1 && literal[0] == 0x20 /* ' ' */) { static PatternConverterPtr blank(new LiteralPatternConverter(literal)); return blank; } PatternConverterPtr pattern(new LiteralPatternConverter(literal)); return pattern; } void LiteralPatternConverter::format( const LoggingEventPtr& /* event */, LogString& toAppendTo, Pool& /* p */) const { toAppendTo.append(literal); } void LiteralPatternConverter::format( const ObjectPtr& /* event */, LogString& toAppendTo, Pool& /* p */) const { toAppendTo.append(literal); }
001-log4cxx
trunk/src/main/cpp/literalpatternconverter.cpp
C++
asf20
2,073
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <log4cxx/logstring.h> #include <log4cxx/helpers/datagramsocket.h> #include <log4cxx/helpers/datagrampacket.h> #include <log4cxx/helpers/loglog.h> #include <log4cxx/helpers/transcoder.h> #include "apr_network_io.h" #include "apr_lib.h" using namespace log4cxx::helpers; IMPLEMENT_LOG4CXX_OBJECT(DatagramSocket) DatagramSocket::DatagramSocket() : socket(0), address(), localAddress(), port(0), localPort(0) { create(); } DatagramSocket::DatagramSocket(int localPort1) : socket(0), address(), localAddress(), port(0), localPort(0) { InetAddressPtr bindAddr = InetAddress::anyAddress(); create(); bind(localPort1, bindAddr); } DatagramSocket::DatagramSocket(int localPort1, InetAddressPtr localAddress1) : socket(0), address(), localAddress(), port(0), localPort(0) { create(); bind(localPort1, localAddress1); } DatagramSocket::~DatagramSocket() { try { close(); } catch(SocketException&) { } } /** Binds a datagram socket to a local port and address.*/ void DatagramSocket::bind(int localPort1, InetAddressPtr localAddress1) { Pool addrPool; // Create server socket address (including port number) LOG4CXX_ENCODE_CHAR(hostAddr, localAddress1->getHostAddress()); apr_sockaddr_t *server_addr; apr_status_t status = apr_sockaddr_info_get(&server_addr, hostAddr.c_str(), APR_INET, localPort1, 0, addrPool.getAPRPool()); if (status != APR_SUCCESS) { throw BindException(status); } // bind the socket to the address status = apr_socket_bind(socket, server_addr); if (status != APR_SUCCESS) { throw BindException(status); } this->localPort = localPort1; this->localAddress = localAddress1; } /** Close the socket.*/ void DatagramSocket::close() { if (socket != 0) { apr_status_t status = apr_socket_close(socket); if (status != APR_SUCCESS) { throw SocketException(status); } socket = 0; localPort = 0; } } void DatagramSocket::connect(InetAddressPtr address1, int port1) { this->address = address1; this->port = port1; Pool addrPool; // create socket address LOG4CXX_ENCODE_CHAR(hostAddr, address1->getHostAddress()); apr_sockaddr_t *client_addr; apr_status_t status = apr_sockaddr_info_get(&client_addr, hostAddr.c_str(), APR_INET, port, 0, addrPool.getAPRPool()); if (status != APR_SUCCESS) { throw ConnectException(status); } // connect the socket status = apr_socket_connect(socket, client_addr); if (status != APR_SUCCESS) { throw ConnectException(status); } } /** Creates a datagram socket.*/ void DatagramSocket::create() { apr_socket_t* newSocket; apr_status_t status = apr_socket_create(&newSocket, APR_INET, SOCK_DGRAM, APR_PROTO_UDP, socketPool.getAPRPool()); socket = newSocket; if (status != APR_SUCCESS) { throw SocketException(status); } } /** Receive the datagram packet.*/ void DatagramSocket::receive(DatagramPacketPtr& p) { Pool addrPool; // Create the address from which to receive the datagram packet LOG4CXX_ENCODE_CHAR(hostAddr, p->getAddress()->getHostAddress()); apr_sockaddr_t *addr; apr_status_t status = apr_sockaddr_info_get(&addr, hostAddr.c_str(), APR_INET, p->getPort(), 0, addrPool.getAPRPool()); if (status != APR_SUCCESS) { throw SocketException(status); } // receive the datagram packet apr_size_t len = p->getLength(); status = apr_socket_recvfrom(addr, socket, 0, (char *)p->getData(), &len); if (status != APR_SUCCESS) { throw IOException(status); } } /** Sends a datagram packet.*/ void DatagramSocket::send(DatagramPacketPtr& p) { Pool addrPool; // create the adress to which to send the datagram packet LOG4CXX_ENCODE_CHAR(hostAddr, p->getAddress()->getHostAddress()); apr_sockaddr_t *addr; apr_status_t status = apr_sockaddr_info_get(&addr, hostAddr.c_str(), APR_INET, p->getPort(), 0, addrPool.getAPRPool()); if (status != APR_SUCCESS) { throw SocketException(status); } // send the datagram packet apr_size_t len = p->getLength(); status = apr_socket_sendto(socket, addr, 0, (char *)p->getData(), &len); if (status != APR_SUCCESS) { throw IOException(status); } }
001-log4cxx
trunk/src/main/cpp/datagramsocket.cpp
C++
asf20
5,266
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #if defined(_MSC_VER) #pragma warning ( disable: 4231 4251 4275 4786 ) #endif #include <log4cxx/logstring.h> #include <log4cxx/helpers/inetaddress.h> #include <log4cxx/helpers/loglog.h> #include <log4cxx/helpers/transcoder.h> #include <log4cxx/helpers/pool.h> #include "apr_network_io.h" using namespace log4cxx; using namespace log4cxx::helpers; IMPLEMENT_LOG4CXX_OBJECT(InetAddress) UnknownHostException::UnknownHostException(const LogString& msg1) : Exception(msg1) { } UnknownHostException::UnknownHostException(const UnknownHostException& src) : Exception(src) { } UnknownHostException& UnknownHostException::operator=(const UnknownHostException& src) { Exception::operator=(src); return *this; } InetAddress::InetAddress(const LogString& hostName, const LogString& hostAddr) : ipAddrString(hostAddr), hostNameString(hostName) { } /** Determines all the IP addresses of a host, given the host's name. */ std::vector<InetAddressPtr> InetAddress::getAllByName(const LogString& host) { LOG4CXX_ENCODE_CHAR(encodedHost, host); // retrieve information about the given host Pool addrPool; apr_sockaddr_t *address = 0; apr_status_t status = apr_sockaddr_info_get(&address, encodedHost.c_str(), APR_INET, 0, 0, addrPool.getAPRPool()); if (status != APR_SUCCESS) { LogString msg(LOG4CXX_STR("Cannot get information about host: ")); msg.append(host); LogLog::error(msg); throw UnknownHostException(msg); } std::vector<InetAddressPtr> result; apr_sockaddr_t *currentAddr = address; while(currentAddr != NULL) { // retrieve the IP address of this InetAddress. LogString ipAddrString; char *ipAddr; status = apr_sockaddr_ip_get(&ipAddr, currentAddr); if (status == APR_SUCCESS) { std::string ip(ipAddr); Transcoder::decode(ip, ipAddrString); } // retrieve the host name of this InetAddress. LogString hostNameString; char *hostName; status = apr_getnameinfo(&hostName, currentAddr, 0); if (status == APR_SUCCESS) { std::string host(hostName); Transcoder::decode(host, hostNameString); } result.push_back(new InetAddress(hostNameString, ipAddrString)); currentAddr = currentAddr->next; } return result; } /** Determines the IP address of a host, given the host's name. */ InetAddressPtr InetAddress::getByName(const LogString& host) { return getAllByName(host)[0]; } /** Returns the IP address string "%d.%d.%d.%d". */ LogString InetAddress::getHostAddress() const { return ipAddrString; } /** Gets the host name for this IP address. */ LogString InetAddress::getHostName() const { return hostNameString; } /** Returns the local host. */ InetAddressPtr InetAddress::getLocalHost() { return getByName(LOG4CXX_STR("127.0.0.1")); } InetAddressPtr InetAddress::anyAddress() { // APR_ANYADDR does not work with the LOG4CXX_STR macro return getByName(LOG4CXX_STR("0.0.0.0")); } /** Converts this IP address to a String. */ LogString InetAddress::toString() const { LogString rv(getHostName()); rv.append(LOG4CXX_STR("/")); rv.append(getHostAddress()); return rv; }
001-log4cxx
trunk/src/main/cpp/inetaddress.cpp
C++
asf20
4,140
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <log4cxx/rolling/manualtriggeringpolicy.h> #include <log4cxx/helpers/stringhelper.h> #include <log4cxx/helpers/optionconverter.h> using namespace log4cxx; using namespace log4cxx::rolling; using namespace log4cxx::helpers; IMPLEMENT_LOG4CXX_OBJECT(ManualTriggeringPolicy) ManualTriggeringPolicy::ManualTriggeringPolicy() { } bool ManualTriggeringPolicy::isTriggeringEvent(Appender* /* appender */, const log4cxx::spi::LoggingEventPtr& /* event */, const LogString& /* file */, size_t /* fileLength */ ) { return false; } void ManualTriggeringPolicy::activateOptions(Pool& /* p */ ) { } void ManualTriggeringPolicy::setOption(const LogString& /* option */ , const LogString& /* value */ ) { }
001-log4cxx
trunk/src/main/cpp/manualtriggeringpolicy.cpp
C++
asf20
1,543
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <log4cxx/logstring.h> #include <log4cxx/helpers/fileoutputstream.h> #include <log4cxx/helpers/exception.h> #include <log4cxx/helpers/bytebuffer.h> #include <apr_file_io.h> #include <log4cxx/helpers/transcoder.h> #if !defined(LOG4CXX) #define LOG4CXX 1 #endif #include <log4cxx/helpers/aprinitializer.h> using namespace log4cxx; using namespace log4cxx::helpers; IMPLEMENT_LOG4CXX_OBJECT(FileOutputStream) FileOutputStream::FileOutputStream(const LogString& filename, bool append) : pool(), fileptr(open(filename, append, pool)) { } FileOutputStream::FileOutputStream(const logchar* filename, bool append) : pool(), fileptr(open(filename, append, pool)) { } apr_file_t* FileOutputStream::open(const LogString& filename, bool append, Pool& pool) { apr_fileperms_t perm = APR_OS_DEFAULT; apr_int32_t flags = APR_WRITE | APR_CREATE; if (append) { flags |= APR_APPEND; } else { flags |= APR_TRUNCATE; } File fn; fn.setPath(filename); apr_file_t* fileptr = 0; apr_status_t stat = fn.open(&fileptr, flags, perm, pool); if (stat != APR_SUCCESS) { throw IOException(stat); } return fileptr; } FileOutputStream::~FileOutputStream() { if (fileptr != NULL && !APRInitializer::isDestructed) { apr_file_close(fileptr); } } void FileOutputStream::close(Pool& /* p */) { if (fileptr != NULL) { apr_status_t stat = apr_file_close(fileptr); if (stat != APR_SUCCESS) { throw IOException(stat); } fileptr = NULL; } } void FileOutputStream::flush(Pool& /* p */) { } void FileOutputStream::write(ByteBuffer& buf, Pool& /* p */ ) { if (fileptr == NULL) { throw IOException(-1); } size_t nbytes = buf.remaining(); size_t pos = buf.position(); const char* data = buf.data(); while(nbytes > 0) { apr_status_t stat = apr_file_write( fileptr, data + pos, &nbytes); if (stat != APR_SUCCESS) { throw IOException(stat); } pos += nbytes; buf.position(pos); nbytes = buf.remaining(); } }
001-log4cxx
trunk/src/main/cpp/fileoutputstream.cpp
C++
asf20
2,851
# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # lib_LTLIBRARIES = liblog4cxx.la INCLUDES = -I$(top_srcdir)/src/main/include -I$(top_builddir)/src/main/include liblog4cxx_la_SOURCES = \ action.cpp \ appenderattachableimpl.cpp \ appenderskeleton.cpp \ aprinitializer.cpp \ asyncappender.cpp \ basicconfigurator.cpp \ bufferedwriter.cpp \ bytearrayinputstream.cpp \ bytearrayoutputstream.cpp \ bytebuffer.cpp \ cacheddateformat.cpp \ charsetdecoder.cpp \ charsetencoder.cpp \ class.cpp \ classnamepatternconverter.cpp \ classregistration.cpp \ condition.cpp \ configurator.cpp \ consoleappender.cpp \ cyclicbuffer.cpp \ dailyrollingfileappender.cpp \ datagrampacket.cpp \ datagramsocket.cpp \ date.cpp \ dateformat.cpp \ datelayout.cpp \ datepatternconverter.cpp \ defaultloggerfactory.cpp \ defaultconfigurator.cpp \ defaultrepositoryselector.cpp \ domconfigurator.cpp \ exception.cpp \ fallbackerrorhandler.cpp \ file.cpp \ fileappender.cpp \ filedatepatternconverter.cpp \ fileinputstream.cpp \ filelocationpatternconverter.cpp \ fileoutputstream.cpp \ filerenameaction.cpp \ filewatchdog.cpp \ filter.cpp \ filterbasedtriggeringpolicy.cpp \ fixedwindowrollingpolicy.cpp \ formattinginfo.cpp \ fulllocationpatternconverter.cpp \ gzcompressaction.cpp \ hierarchy.cpp \ htmllayout.cpp \ inetaddress.cpp \ inputstream.cpp \ inputstreamreader.cpp \ integer.cpp \ integerpatternconverter.cpp \ layout.cpp\ level.cpp \ levelmatchfilter.cpp \ levelrangefilter.cpp \ levelpatternconverter.cpp \ linelocationpatternconverter.cpp \ lineseparatorpatternconverter.cpp \ literalpatternconverter.cpp \ loggerpatternconverter.cpp \ loggingeventpatternconverter.cpp \ loader.cpp\ locale.cpp\ locationinfo.cpp\ logger.cpp \ loggingevent.cpp \ loglog.cpp \ logmanager.cpp \ logstream.cpp \ manualtriggeringpolicy.cpp \ messagebuffer.cpp \ messagepatternconverter.cpp \ methodlocationpatternconverter.cpp \ mdc.cpp \ mutex.cpp \ nameabbreviator.cpp \ namepatternconverter.cpp \ ndcpatternconverter.cpp \ ndc.cpp \ nteventlogappender.cpp \ objectimpl.cpp \ objectptr.cpp \ objectoutputstream.cpp \ obsoleterollingfileappender.cpp \ odbcappender.cpp \ onlyonceerrorhandler.cpp \ optionconverter.cpp \ outputdebugstringappender.cpp \ outputstream.cpp \ outputstreamwriter.cpp \ patternconverter.cpp \ patternlayout.cpp \ patternparser.cpp \ pool.cpp \ properties.cpp \ propertiespatternconverter.cpp \ propertyconfigurator.cpp \ propertyresourcebundle.cpp \ propertysetter.cpp \ reader.cpp \ relativetimedateformat.cpp \ relativetimepatternconverter.cpp \ resourcebundle.cpp \ rollingfileappender.cpp \ rollingpolicy.cpp \ rollingpolicybase.cpp \ rolloverdescription.cpp \ rootlogger.cpp \ serversocket.cpp \ simpledateformat.cpp \ simplelayout.cpp \ sizebasedtriggeringpolicy.cpp \ smtpappender.cpp \ socket.cpp \ socketappender.cpp \ socketappenderskeleton.cpp \ sockethubappender.cpp \ socketoutputstream.cpp \ strftimedateformat.cpp \ stringhelper.cpp \ stringmatchfilter.cpp \ stringtokenizer.cpp \ synchronized.cpp \ syslogappender.cpp \ syslogwriter.cpp \ system.cpp \ systemerrwriter.cpp \ systemoutwriter.cpp \ telnetappender.cpp \ threadcxx.cpp \ threadlocal.cpp \ threadspecificdata.cpp \ threadpatternconverter.cpp \ throwableinformationpatternconverter.cpp \ timezone.cpp \ timebasedrollingpolicy.cpp \ transform.cpp \ triggeringpolicy.cpp \ transcoder.cpp \ ttcclayout.cpp \ writer.cpp \ writerappender.cpp \ xmllayout.cpp\ xmlsocketappender.cpp \ zipcompressaction.cpp AM_CPPFLAGS = @CPPFLAGS_ODBC@ liblog4cxx_la_LDFLAGS = -version-info @LT_VERSION@ @LIBS_ODBC@ -@APR_LIBS@
001-log4cxx
trunk/src/main/cpp/Makefile.am
Makefile
asf20
5,492
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <log4cxx/logstring.h> #include <log4cxx/helpers/fileinputstream.h> #include <log4cxx/helpers/exception.h> #include <log4cxx/helpers/bytebuffer.h> #include <apr_file_io.h> #include <log4cxx/helpers/transcoder.h> #if !defined(LOG4CXX) #define LOG4CXX 1 #endif #include <log4cxx/helpers/aprinitializer.h> using namespace log4cxx; using namespace log4cxx::helpers; IMPLEMENT_LOG4CXX_OBJECT(FileInputStream) FileInputStream::FileInputStream(const LogString& filename) : fileptr(0) { open(filename); } FileInputStream::FileInputStream(const logchar* filename) : fileptr(0) { LogString fn(filename); open(fn); } void FileInputStream::open(const LogString& filename) { apr_fileperms_t perm = APR_OS_DEFAULT; apr_int32_t flags = APR_READ; apr_status_t stat = File().setPath(filename).open(&fileptr, flags, perm, pool); if (stat != APR_SUCCESS) { throw IOException(stat); } } FileInputStream::FileInputStream(const File& aFile) { apr_fileperms_t perm = APR_OS_DEFAULT; apr_int32_t flags = APR_READ; apr_status_t stat = aFile.open(&fileptr, flags, perm, pool); if (stat != APR_SUCCESS) { throw IOException(stat); } } FileInputStream::~FileInputStream() { if (fileptr != NULL && !APRInitializer::isDestructed) { apr_file_close(fileptr); } } void FileInputStream::close() { apr_status_t stat = apr_file_close(fileptr); if (stat == APR_SUCCESS) { fileptr = NULL; } else { throw IOException(stat); } } int FileInputStream::read(ByteBuffer& buf) { apr_size_t bytesRead = buf.remaining(); apr_status_t stat = apr_file_read(fileptr, buf.current(), &bytesRead); int retval = -1; if (!APR_STATUS_IS_EOF(stat)) { if (stat != APR_SUCCESS) { throw IOException(stat); } buf.position(buf.position() + bytesRead); retval = bytesRead; } return retval; }
001-log4cxx
trunk/src/main/cpp/fileinputstream.cpp
C++
asf20
2,678
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <log4cxx/logstring.h> #include <log4cxx/helpers/writer.h> using namespace log4cxx::helpers; IMPLEMENT_LOG4CXX_OBJECT(Writer) Writer::Writer() { } Writer::~Writer() { }
001-log4cxx
trunk/src/main/cpp/writer.cpp
C++
asf20
985
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <log4cxx/logstring.h> #include <log4cxx/helpers/stringtokenizer.h> #include <log4cxx/helpers/exception.h> #if !defined(LOG4CXX) #define LOG4CXX 1 #endif #include <log4cxx/private/log4cxx_private.h> using namespace log4cxx; using namespace log4cxx::helpers; StringTokenizer::StringTokenizer(const LogString& str, const LogString& delim1) : src(str), delim(delim1), pos(0) { } StringTokenizer::~StringTokenizer() { } bool StringTokenizer::hasMoreTokens() const { return (pos != LogString::npos && src.find_first_not_of(delim, pos) != LogString::npos); } LogString StringTokenizer::nextToken() { if (pos != LogString::npos) { size_t nextPos = src.find_first_not_of(delim, pos); if (nextPos != LogString::npos) { pos = src.find_first_of(delim, nextPos); if (pos == LogString::npos) { return src.substr(nextPos); } return src.substr(nextPos, pos - nextPos); } } throw NoSuchElementException(); #if LOG4CXX_RETURN_AFTER_THROW return LogString(); #endif }
001-log4cxx
trunk/src/main/cpp/stringtokenizer.cpp
C++
asf20
1,932
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "log4cxx/helpers/threadlocal.h" #include "apr_thread_proc.h" #include "log4cxx/helpers/exception.h" using namespace log4cxx::helpers; using namespace log4cxx; apr_threadkey_t* ThreadLocal::create(Pool& p) { apr_threadkey_t* key = 0; #if APR_HAS_THREADS apr_status_t stat = apr_threadkey_private_create(&key, 0, p.getAPRPool()); if (stat != APR_SUCCESS) { throw RuntimeException(stat); } #endif return key; } ThreadLocal::ThreadLocal() : p(), key(create(p)) { } ThreadLocal::~ThreadLocal() { } void ThreadLocal::set(void* priv) { #if APR_HAS_THREADS apr_status_t stat = apr_threadkey_private_set(priv, key); if (stat != APR_SUCCESS) { throw RuntimeException(stat); } #endif } void* ThreadLocal::get() { void* retval = 0; #if APR_HAS_THREADS apr_status_t stat = apr_threadkey_private_get(&retval, key); if (stat != APR_SUCCESS) { throw RuntimeException(stat); } #endif return retval; }
001-log4cxx
trunk/src/main/cpp/threadlocal.cpp
C++
asf20
1,823
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <log4cxx/logstring.h> #include <log4cxx/helpers/dateformat.h> #include <log4cxx/helpers/stringhelper.h> using namespace log4cxx; using namespace log4cxx::helpers; IMPLEMENT_LOG4CXX_OBJECT(DateFormat) DateFormat::~DateFormat() {} void DateFormat::setTimeZone(const TimeZonePtr&) {} void DateFormat::numberFormat(LogString& s, int n, Pool& p) const { StringHelper::toString(n, p, s); } DateFormat::DateFormat() {}
001-log4cxx
trunk/src/main/cpp/dateformat.cpp
C++
asf20
1,237
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #if defined(_MSC_VER) #pragma warning ( disable: 4231 4251 4275 4786 ) #endif #include <log4cxx/logstring.h> #include <log4cxx/helpers/syslogwriter.h> #include <log4cxx/helpers/loglog.h> #include <log4cxx/helpers/inetaddress.h> #include <log4cxx/helpers/datagramsocket.h> #include <log4cxx/helpers/datagrampacket.h> #include <log4cxx/helpers/transcoder.h> #define SYSLOG_PORT 514 using namespace log4cxx; using namespace log4cxx::helpers; SyslogWriter::SyslogWriter(const LogString& syslogHost1) : syslogHost(syslogHost1) { try { this->address = InetAddress::getByName(syslogHost1); } catch(UnknownHostException& e) { LogLog::error(((LogString) LOG4CXX_STR("Could not find ")) + syslogHost1 + LOG4CXX_STR(". All logging will FAIL."), e); } try { this->ds = new DatagramSocket(); } catch (SocketException& e) { LogLog::error(((LogString) LOG4CXX_STR("Could not instantiate DatagramSocket to ")) + syslogHost1 + LOG4CXX_STR(". All logging will FAIL."), e); } } void SyslogWriter::write(const LogString& source) { if (this->ds != 0 && this->address != 0) { LOG4CXX_ENCODE_CHAR(data, source); DatagramPacketPtr packet( new DatagramPacket((void*) data.data(), data.length(), address, SYSLOG_PORT)); ds->send(packet); } }
001-log4cxx
trunk/src/main/cpp/syslogwriter.cpp
C++
asf20
2,171
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #if defined(_MSC_VER) #pragma warning ( disable: 4231 4251 4275 4786 ) #endif #include <log4cxx/rolling/rollingfileappender.h> #include <log4cxx/helpers/loglog.h> #include <log4cxx/helpers/synchronized.h> #include <log4cxx/rolling/rolloverdescription.h> #include <log4cxx/helpers/fileoutputstream.h> #include <log4cxx/helpers/bytebuffer.h> #include <log4cxx/rolling/fixedwindowrollingpolicy.h> #include <log4cxx/rolling/manualtriggeringpolicy.h> using namespace log4cxx; using namespace log4cxx::rolling; using namespace log4cxx::helpers; using namespace log4cxx::spi; IMPLEMENT_LOG4CXX_OBJECT(RollingFileAppenderSkeleton) IMPLEMENT_LOG4CXX_OBJECT(RollingFileAppender) /** * Construct a new instance. */ RollingFileAppenderSkeleton::RollingFileAppenderSkeleton() { } RollingFileAppender::RollingFileAppender() { } /** * Prepare instance of use. */ void RollingFileAppenderSkeleton::activateOptions(Pool &p) { if (rollingPolicy == NULL) { FixedWindowRollingPolicy* fwrp = new FixedWindowRollingPolicy(); fwrp->setFileNamePattern(getFile() + LOG4CXX_STR(".%i")); rollingPolicy = fwrp; } // // if no explicit triggering policy and rolling policy is both. // if (triggeringPolicy == NULL) { TriggeringPolicyPtr trig(rollingPolicy); if (trig != NULL) { triggeringPolicy = trig; } } if (triggeringPolicy == NULL) { triggeringPolicy = new ManualTriggeringPolicy(); } { synchronized sync(mutex); triggeringPolicy->activateOptions(p); rollingPolicy->activateOptions(p); try { RolloverDescriptionPtr rollover1 = rollingPolicy->initialize(getFile(), getAppend(), p); if (rollover1 != NULL) { ActionPtr syncAction(rollover1->getSynchronous()); if (syncAction != NULL) { syncAction->execute(p); } setFile(rollover1->getActiveFileName()); setAppend(rollover1->getAppend()); // // async action not yet implemented // ActionPtr asyncAction(rollover1->getAsynchronous()); if (asyncAction != NULL) { asyncAction->execute(p); } } File activeFile; activeFile.setPath(getFile()); if (getAppend()) { fileLength = activeFile.length(p); } else { fileLength = 0; } FileAppender::activateOptions(p); } catch (std::exception& ex) { LogLog::warn( LogString(LOG4CXX_STR("Exception will initializing RollingFileAppender named ")) + getName()); } } } /** Implements the usual roll over behaviour. <p>If <code>MaxBackupIndex</code> is positive, then files {<code>File.1</code>, ..., <code>File.MaxBackupIndex -1</code>} are renamed to {<code>File.2</code>, ..., <code>File.MaxBackupIndex</code>}. Moreover, <code>File</code> is renamed <code>File.1</code> and closed. A new <code>File</code> is created to receive further log output. <p>If <code>MaxBackupIndex</code> is equal to zero, then the <code>File</code> is truncated with no backup files created. * @return true if rollover performed. */ bool RollingFileAppenderSkeleton::rollover(Pool& p) { // // can't roll without a policy // if (rollingPolicy != NULL) { { synchronized sync(mutex); try { RolloverDescriptionPtr rollover1(rollingPolicy->rollover(getFile(), p)); if (rollover1 != NULL) { if (rollover1->getActiveFileName() == getFile()) { closeWriter(); bool success = true; if (rollover1->getSynchronous() != NULL) { success = false; try { success = rollover1->getSynchronous()->execute(p); } catch (std::exception& ex) { LogLog::warn(LOG4CXX_STR("Exception on rollover")); } } if (success) { if (rollover1->getAppend()) { fileLength = File().setPath(rollover1->getActiveFileName()).length(p); } else { fileLength = 0; } // // async action not yet implemented // ActionPtr asyncAction(rollover1->getAsynchronous()); if (asyncAction != NULL) { asyncAction->execute(p); } setFile( rollover1->getActiveFileName(), rollover1->getAppend(), bufferedIO, bufferSize, p); } else { setFile( rollover1->getActiveFileName(), true, bufferedIO, bufferSize, p); } } else { OutputStreamPtr os(new FileOutputStream( rollover1->getActiveFileName(), rollover1->getAppend())); WriterPtr newWriter(createWriter(os)); closeWriter(); setFile(rollover1->getActiveFileName()); setWriter(newWriter); bool success = true; if (rollover1->getSynchronous() != NULL) { success = false; try { success = rollover1->getSynchronous()->execute(p); } catch (std::exception& ex) { LogLog::warn(LOG4CXX_STR("Exception during rollover")); } } if (success) { if (rollover1->getAppend()) { fileLength = File().setPath(rollover1->getActiveFileName()).length(p); } else { fileLength = 0; } // // async action not yet implemented // ActionPtr asyncAction(rollover1->getAsynchronous()); if (asyncAction != NULL) { asyncAction->execute(p); } } writeHeader(p); } return true; } } catch (std::exception& ex) { LogLog::warn(LOG4CXX_STR("Exception during rollover")); } } } return false; } /** * {@inheritDoc} */ void RollingFileAppenderSkeleton::subAppend(const LoggingEventPtr& event, Pool& p) { // The rollover check must precede actual writing. This is the // only correct behavior for time driven triggers. if ( triggeringPolicy->isTriggeringEvent( this, event, getFile(), getFileLength())) { // // wrap rollover request in try block since // rollover may fail in case read access to directory // is not provided. However appender should still be in good // condition and the append should still happen. try { rollover(p); } catch (std::exception& ex) { LogLog::warn(LOG4CXX_STR("Exception during rollover attempt.")); } } FileAppender::subAppend(event, p); } /** * Get rolling policy. * @return rolling policy. */ RollingPolicyPtr RollingFileAppenderSkeleton::getRollingPolicy() const { return rollingPolicy; } /** * Get triggering policy. * @return triggering policy. */ TriggeringPolicyPtr RollingFileAppenderSkeleton::getTriggeringPolicy() const { return triggeringPolicy; } /** * Sets the rolling policy. * @param policy rolling policy. */ void RollingFileAppenderSkeleton::setRollingPolicy(const RollingPolicyPtr& policy) { rollingPolicy = policy; } /** * Set triggering policy. * @param policy triggering policy. */ void RollingFileAppenderSkeleton::setTriggeringPolicy(const TriggeringPolicyPtr& policy) { triggeringPolicy = policy; } /** * Close appender. Waits for any asynchronous file compression actions to be completed. */ void RollingFileAppenderSkeleton::close() { FileAppender::close(); } namespace log4cxx { namespace rolling { /** * Wrapper for OutputStream that will report all write * operations back to this class for file length calculations. */ class CountingOutputStream : public OutputStream { /** * Wrapped output stream. */ private: OutputStreamPtr os; /** * Rolling file appender to inform of stream writes. */ RollingFileAppenderSkeleton* rfa; public: /** * Constructor. * @param os output stream to wrap. * @param rfa rolling file appender to inform. */ CountingOutputStream( OutputStreamPtr& os1, RollingFileAppenderSkeleton* rfa1) : os(os1), rfa(rfa1) { } /** * {@inheritDoc} */ void close(Pool& p) { os->close(p); rfa = 0; } /** * {@inheritDoc} */ void flush(Pool& p) { os->flush(p); } /** * {@inheritDoc} */ void write(ByteBuffer& buf, Pool& p) { os->write(buf, p); if (rfa != 0) { rfa->incrementFileLength(buf.limit()); } } }; } } /** Returns an OutputStreamWriter when passed an OutputStream. The encoding used will depend on the value of the <code>encoding</code> property. If the encoding value is specified incorrectly the writer will be opened using the default system encoding (an error message will be printed to the loglog. @param os output stream, may not be null. @return new writer. */ WriterPtr RollingFileAppenderSkeleton::createWriter(OutputStreamPtr& os) { OutputStreamPtr cos(new CountingOutputStream(os, this)); return FileAppender::createWriter(cos); } /** * Get byte length of current active log file. * @return byte length of current active log file. */ size_t RollingFileAppenderSkeleton::getFileLength() const { return fileLength; } /** * Increments estimated byte length of current active log file. * @param increment additional bytes written to log file. */ void RollingFileAppenderSkeleton::incrementFileLength(size_t increment) { fileLength += increment; }
001-log4cxx
trunk/src/main/cpp/rollingfileappender.cpp
C++
asf20
10,423
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #define __STDC_CONSTANT_MACROS #include <log4cxx/logstring.h> #include <log4cxx/helpers/filewatchdog.h> #include <log4cxx/helpers/loglog.h> #include <apr_time.h> #include <apr_thread_proc.h> #include <apr_atomic.h> #include <log4cxx/helpers/transcoder.h> using namespace log4cxx; using namespace log4cxx::helpers; long FileWatchdog::DEFAULT_DELAY = 60000; #if APR_HAS_THREADS FileWatchdog::FileWatchdog(const File& file1) : file(file1), delay(DEFAULT_DELAY), lastModif(0), warnedAlready(false), interrupted(0), thread() { } FileWatchdog::~FileWatchdog() { apr_atomic_set32(&interrupted, 0xFFFF); thread.join(); } void FileWatchdog::checkAndConfigure() { Pool pool1; if (!file.exists(pool1)) { if(!warnedAlready) { LogLog::debug(((LogString) LOG4CXX_STR("[")) + file.getPath() + LOG4CXX_STR("] does not exist.")); warnedAlready = true; } } else { apr_time_t thisMod = file.lastModified(pool1); if (thisMod > lastModif) { lastModif = thisMod; doOnChange(); warnedAlready = false; } } } void* APR_THREAD_FUNC FileWatchdog::run(apr_thread_t* /* thread */, void* data) { FileWatchdog* pThis = (FileWatchdog*) data; unsigned int interrupted = apr_atomic_read32(&pThis->interrupted); while(!interrupted) { apr_sleep(APR_INT64_C(1000) * pThis->delay); interrupted = apr_atomic_read32(&pThis->interrupted); if (!interrupted) { pThis->checkAndConfigure(); interrupted = apr_atomic_read32(&pThis->interrupted); } } return NULL; } void FileWatchdog::start() { checkAndConfigure(); thread.run(run, this); } #endif
001-log4cxx
trunk/src/main/cpp/filewatchdog.cpp
C++
asf20
2,600
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <log4cxx/helpers/messagebuffer.h> #include <log4cxx/helpers/transcoder.h> using namespace log4cxx::helpers; CharMessageBuffer::CharMessageBuffer() : stream(0) {} CharMessageBuffer::~CharMessageBuffer() { delete stream; } CharMessageBuffer& CharMessageBuffer::operator<<(const std::basic_string<char>& msg) { if (stream == 0) { buf.append(msg); } else { *stream << msg; } return *this; } CharMessageBuffer& CharMessageBuffer::operator<<(const char* msg) { const char* actualMsg = msg; if (actualMsg == 0) { actualMsg = "null"; } if (stream == 0) { buf.append(actualMsg); } else { *stream << actualMsg; } return *this; } CharMessageBuffer& CharMessageBuffer::operator<<(char* msg) { return operator<<((const char*) msg); } CharMessageBuffer& CharMessageBuffer::operator<<(const char msg) { if (stream == 0) { buf.append(1, msg); } else { buf.assign(1, msg); *stream << buf; } return *this; } CharMessageBuffer::operator std::basic_ostream<char>&() { if (stream == 0) { stream = new std::basic_ostringstream<char>(); if (!buf.empty()) { *stream << buf; } } return *stream; } const std::basic_string<char>& CharMessageBuffer::str(std::basic_ostream<char>&) { buf = stream->str(); return buf; } const std::basic_string<char>& CharMessageBuffer::str(CharMessageBuffer&) { return buf; } bool CharMessageBuffer::hasStream() const { return (stream != 0); } std::ostream& CharMessageBuffer::operator<<(ios_base_manip manip) { std::ostream& s = *this; (*manip)(s); return s; } std::ostream& CharMessageBuffer::operator<<(bool val) { return ((std::ostream&) *this).operator<<(val); } std::ostream& CharMessageBuffer::operator<<(short val) { return ((std::ostream&) *this).operator<<(val); } std::ostream& CharMessageBuffer::operator<<(int val) { return ((std::ostream&) *this).operator<<(val); } std::ostream& CharMessageBuffer::operator<<(unsigned int val) { return ((std::ostream&) *this).operator<<(val); } std::ostream& CharMessageBuffer::operator<<(long val) { return ((std::ostream&) *this).operator<<(val); } std::ostream& CharMessageBuffer::operator<<(unsigned long val) { return ((std::ostream&) *this).operator<<(val); } std::ostream& CharMessageBuffer::operator<<(float val) { return ((std::ostream&) *this).operator<<(val); } std::ostream& CharMessageBuffer::operator<<(double val) { return ((std::ostream&) *this).operator<<(val); } std::ostream& CharMessageBuffer::operator<<(long double val) { return ((std::ostream&) *this).operator<<(val); } std::ostream& CharMessageBuffer::operator<<(void* val) { return ((std::ostream&) *this).operator<<(val); } #if LOG4CXX_WCHAR_T_API WideMessageBuffer::WideMessageBuffer() : stream(0) {} WideMessageBuffer::~WideMessageBuffer() { delete stream; } WideMessageBuffer& WideMessageBuffer::operator<<(const std::basic_string<wchar_t>& msg) { if (stream == 0) { buf.append(msg); } else { *stream << msg; } return *this; } WideMessageBuffer& WideMessageBuffer::operator<<(const wchar_t* msg) { const wchar_t* actualMsg = msg; if (actualMsg == 0) { actualMsg = L"null"; } if (stream == 0) { buf.append(actualMsg); } else { *stream << actualMsg; } return *this; } WideMessageBuffer& WideMessageBuffer::operator<<(wchar_t* msg) { return operator<<((const wchar_t*) msg); } WideMessageBuffer& WideMessageBuffer::operator<<(const wchar_t msg) { if (stream == 0) { buf.append(1, msg); } else { buf.assign(1, msg); *stream << buf; } return *this; } WideMessageBuffer::operator std::basic_ostream<wchar_t>&() { if (stream == 0) { stream = new std::basic_ostringstream<wchar_t>(); if (!buf.empty()) { *stream << buf; } } return *stream; } const std::basic_string<wchar_t>& WideMessageBuffer::str(std::basic_ostream<wchar_t>&) { buf = stream->str(); return buf; } const std::basic_string<wchar_t>& WideMessageBuffer::str(WideMessageBuffer&) { return buf; } bool WideMessageBuffer::hasStream() const { return (stream != 0); } std::basic_ostream<wchar_t>& WideMessageBuffer::operator<<(ios_base_manip manip) { std::basic_ostream<wchar_t>& s = *this; (*manip)(s); return s; } std::basic_ostream<wchar_t>& WideMessageBuffer::operator<<(bool val) { return ((std::basic_ostream<wchar_t>&) *this).operator<<(val); } std::basic_ostream<wchar_t>& WideMessageBuffer::operator<<(short val) { return ((std::basic_ostream<wchar_t>&) *this).operator<<(val); } std::basic_ostream<wchar_t>& WideMessageBuffer::operator<<(int val) { return ((std::basic_ostream<wchar_t>&) *this).operator<<(val); } std::basic_ostream<wchar_t>& WideMessageBuffer::operator<<(unsigned int val) { return ((std::basic_ostream<wchar_t>&) *this).operator<<(val); } std::basic_ostream<wchar_t>& WideMessageBuffer::operator<<(long val) { return ((std::basic_ostream<wchar_t>&) *this).operator<<(val); } std::basic_ostream<wchar_t>& WideMessageBuffer::operator<<(unsigned long val) { return ((std::basic_ostream<wchar_t>&) *this).operator<<(val); } std::basic_ostream<wchar_t>& WideMessageBuffer::operator<<(float val) { return ((std::basic_ostream<wchar_t>&) *this).operator<<(val); } std::basic_ostream<wchar_t>& WideMessageBuffer::operator<<(double val) { return ((std::basic_ostream<wchar_t>&) *this).operator<<(val); } std::basic_ostream<wchar_t>& WideMessageBuffer::operator<<(long double val) { return ((std::basic_ostream<wchar_t>&) *this).operator<<(val); } std::basic_ostream<wchar_t>& WideMessageBuffer::operator<<(void* val) { return ((std::basic_ostream<wchar_t>&) *this).operator<<(val); } MessageBuffer::MessageBuffer() : wbuf(0) #if LOG4CXX_UNICHAR_API || LOG4CXX_CFSTRING_API , ubuf(0) #endif { } MessageBuffer::~MessageBuffer() { delete wbuf; #if LOG4CXX_UNICHAR_API || LOG4CXX_CFSTRING_API delete ubuf; #endif } bool MessageBuffer::hasStream() const { bool retval = cbuf.hasStream() || (wbuf != 0 && wbuf->hasStream()); #if LOG4CXX_UNICHAR_API || LOG4CXX_CFSTRING_API retval = retval || (ubuf != 0 && ubuf->hasStream()); #endif return retval; } std::ostream& MessageBuffer::operator<<(ios_base_manip manip) { std::ostream& s = *this; (*manip)(s); return s; } MessageBuffer::operator std::ostream&() { return (std::ostream&) cbuf; } CharMessageBuffer& MessageBuffer::operator<<(const std::string& msg) { return cbuf.operator<<(msg); } CharMessageBuffer& MessageBuffer::operator<<(const char* msg) { return cbuf.operator<<(msg); } CharMessageBuffer& MessageBuffer::operator<<(char* msg) { return cbuf.operator<<((const char*) msg); } CharMessageBuffer& MessageBuffer::operator<<(const char msg) { return cbuf.operator<<(msg); } const std::string& MessageBuffer::str(CharMessageBuffer& buf) { return cbuf.str(buf); } const std::string& MessageBuffer::str(std::ostream& os) { return cbuf.str(os); } WideMessageBuffer& MessageBuffer::operator<<(const std::wstring& msg) { wbuf = new WideMessageBuffer(); return (*wbuf) << msg; } WideMessageBuffer& MessageBuffer::operator<<(const wchar_t* msg) { wbuf = new WideMessageBuffer(); return (*wbuf) << msg; } WideMessageBuffer& MessageBuffer::operator<<(wchar_t* msg) { wbuf = new WideMessageBuffer(); return (*wbuf) << (const wchar_t*) msg; } WideMessageBuffer& MessageBuffer::operator<<(const wchar_t msg) { wbuf = new WideMessageBuffer(); return (*wbuf) << msg; } const std::wstring& MessageBuffer::str(WideMessageBuffer& buf) { return wbuf->str(buf); } const std::wstring& MessageBuffer::str(std::basic_ostream<wchar_t>& os) { return wbuf->str(os); } std::ostream& MessageBuffer::operator<<(bool val) { return cbuf.operator<<(val); } std::ostream& MessageBuffer::operator<<(short val) { return cbuf.operator<<(val); } std::ostream& MessageBuffer::operator<<(int val) { return cbuf.operator<<(val); } std::ostream& MessageBuffer::operator<<(unsigned int val) { return cbuf.operator<<(val); } std::ostream& MessageBuffer::operator<<(long val) { return cbuf.operator<<(val); } std::ostream& MessageBuffer::operator<<(unsigned long val) { return cbuf.operator<<(val); } std::ostream& MessageBuffer::operator<<(float val) { return cbuf.operator<<(val); } std::ostream& MessageBuffer::operator<<(double val) { return cbuf.operator<<(val); } std::ostream& MessageBuffer::operator<<(long double val) { return cbuf.operator<<(val); } std::ostream& MessageBuffer::operator<<(void* val) { return cbuf.operator<<(val); } #endif #if LOG4CXX_UNICHAR_API || LOG4CXX_CFSTRING_API UniCharMessageBuffer& MessageBuffer::operator<<(const std::basic_string<log4cxx::UniChar>& msg) { ubuf = new UniCharMessageBuffer(); return (*ubuf) << msg; } UniCharMessageBuffer& MessageBuffer::operator<<(const log4cxx::UniChar* msg) { ubuf = new UniCharMessageBuffer(); return (*ubuf) << msg; } UniCharMessageBuffer& MessageBuffer::operator<<(log4cxx::UniChar* msg) { ubuf = new UniCharMessageBuffer(); return (*ubuf) << (const log4cxx::UniChar*) msg; } UniCharMessageBuffer& MessageBuffer::operator<<(const log4cxx::UniChar msg) { ubuf = new UniCharMessageBuffer(); return (*ubuf) << msg; } const std::basic_string<log4cxx::UniChar>& MessageBuffer::str(UniCharMessageBuffer& buf) { return ubuf->str(buf); } const std::basic_string<log4cxx::UniChar>& MessageBuffer::str(std::basic_ostream<log4cxx::UniChar>& os) { return ubuf->str(os); } UniCharMessageBuffer::UniCharMessageBuffer() : stream(0) {} UniCharMessageBuffer::~UniCharMessageBuffer() { delete stream; } UniCharMessageBuffer& UniCharMessageBuffer::operator<<(const std::basic_string<log4cxx::UniChar>& msg) { if (stream == 0) { buf.append(msg); } else { *stream << buf; } return *this; } UniCharMessageBuffer& UniCharMessageBuffer::operator<<(const log4cxx::UniChar* msg) { const log4cxx::UniChar* actualMsg = msg; static log4cxx::UniChar nullLiteral[] = { 0x6E, 0x75, 0x6C, 0x6C, 0}; if (actualMsg == 0) { actualMsg = nullLiteral; } if (stream == 0) { buf.append(actualMsg); } else { *stream << actualMsg; } return *this; } UniCharMessageBuffer& UniCharMessageBuffer::operator<<(log4cxx::UniChar* msg) { return operator<<((const log4cxx::UniChar*) msg); } UniCharMessageBuffer& UniCharMessageBuffer::operator<<(const log4cxx::UniChar msg) { if (stream == 0) { buf.append(1, msg); } else { *stream << msg; } return *this; } UniCharMessageBuffer::operator UniCharMessageBuffer::uostream&() { if (stream == 0) { stream = new std::basic_ostringstream<UniChar>(); if (!buf.empty()) { *stream << buf; } } return *stream; } const std::basic_string<log4cxx::UniChar>& UniCharMessageBuffer::str(UniCharMessageBuffer::uostream&) { buf = stream->str(); return buf; } const std::basic_string<log4cxx::UniChar>& UniCharMessageBuffer::str(UniCharMessageBuffer&) { return buf; } bool UniCharMessageBuffer::hasStream() const { return (stream != 0); } UniCharMessageBuffer::uostream& UniCharMessageBuffer::operator<<(ios_base_manip manip) { UniCharMessageBuffer::uostream& s = *this; (*manip)(s); return s; } UniCharMessageBuffer::uostream& UniCharMessageBuffer::operator<<(bool val) { return ((UniCharMessageBuffer::uostream&) *this).operator<<(val); } UniCharMessageBuffer::uostream& UniCharMessageBuffer::operator<<(short val) { return ((UniCharMessageBuffer::uostream&) *this).operator<<(val); } UniCharMessageBuffer::uostream& UniCharMessageBuffer::operator<<(int val) { return ((UniCharMessageBuffer::uostream&) *this).operator<<(val); } UniCharMessageBuffer::uostream& UniCharMessageBuffer::operator<<(unsigned int val) { return ((UniCharMessageBuffer::uostream&) *this).operator<<(val); } UniCharMessageBuffer::uostream& UniCharMessageBuffer::operator<<(long val) { return ((UniCharMessageBuffer::uostream&) *this).operator<<(val); } UniCharMessageBuffer::uostream& UniCharMessageBuffer::operator<<(unsigned long val) { return ((UniCharMessageBuffer::uostream&) *this).operator<<(val); } UniCharMessageBuffer::uostream& UniCharMessageBuffer::operator<<(float val) { return ((UniCharMessageBuffer::uostream&) *this).operator<<(val); } UniCharMessageBuffer::uostream& UniCharMessageBuffer::operator<<(double val) { return ((UniCharMessageBuffer::uostream&) *this).operator<<(val); } UniCharMessageBuffer::uostream& UniCharMessageBuffer::operator<<(long double val) { return ((UniCharMessageBuffer::uostream&) *this).operator<<(val); } UniCharMessageBuffer::uostream& UniCharMessageBuffer::operator<<(void* val) { return ((UniCharMessageBuffer::uostream&) *this).operator<<(val); } #endif #if LOG4CXX_CFSTRING_API #include <CoreFoundation/CFString.h> #include <vector> UniCharMessageBuffer& UniCharMessageBuffer::operator<<(const CFStringRef& msg) { const log4cxx::UniChar* chars = CFStringGetCharactersPtr(msg); if (chars != 0) { return operator<<(chars); } else { size_t length = CFStringGetLength(msg); std::vector<log4cxx::UniChar> tmp(length); CFStringGetCharacters(msg, CFRangeMake(0, length), &tmp[0]); if (stream) { std::basic_string<UniChar> s(&tmp[0], tmp.size()); *stream << s; } else { buf.append(&tmp[0], tmp.size()); } } return *this; } UniCharMessageBuffer& MessageBuffer::operator<<(const CFStringRef& msg) { ubuf = new UniCharMessageBuffer(); return (*ubuf) << msg; } #endif
001-log4cxx
trunk/src/main/cpp/messagebuffer.cpp
C++
asf20
14,451
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <log4cxx/logstring.h> #include <log4cxx/helpers/transform.h> using namespace log4cxx; using namespace log4cxx::helpers; void Transform::appendEscapingTags( LogString& buf, const LogString& input) { //Check if the string is zero length -- if so, return //what was sent in. if(input.length() == 0 ) { return; } logchar specials[] = { 0x22 /* " */, 0x26 /* & */, 0x3C /* < */, 0x3E /* > */, 0x00 }; size_t start = 0; size_t special = input.find_first_of(specials, start); while(special != LogString::npos) { if (special > start) { buf.append(input, start, special - start); } switch(input[special]) { case 0x22: buf.append(LOG4CXX_STR("&quot;")); break; case 0x26: buf.append(LOG4CXX_STR("&amp;")); break; case 0x3C: buf.append(LOG4CXX_STR("&lt;")); break; case 0x3E: buf.append(LOG4CXX_STR("&gt;")); break; default: buf.append(1, input[special]); break; } start = special+1; if (special < input.size()) { special = input.find_first_of(specials, start); } else { special = LogString::npos; } } if (start < input.size()) { buf.append(input, start, input.size() - start); } } void Transform::appendEscapingCDATA( LogString& buf, const LogString& input) { static const LogString CDATA_END(LOG4CXX_STR("]]>")); static const LogString CDATA_EMBEDED_END(LOG4CXX_STR("]]>]]&gt;<![CDATA[")); const LogString::size_type CDATA_END_LEN = 3; if(input.length() == 0 ) { return; } LogString::size_type end = input.find(CDATA_END); if (end == LogString::npos) { buf.append(input); return; } LogString::size_type start = 0; while (end != LogString::npos) { buf.append(input, start, end-start); buf.append(CDATA_EMBEDED_END); start = end + CDATA_END_LEN; if (start < input.length()) { end = input.find(CDATA_END, start); } else { return; } } buf.append(input, start, input.length() - start); }
001-log4cxx
trunk/src/main/cpp/transform.cpp
C++
asf20
3,138
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <log4cxx/logstring.h> #include <log4cxx/helpers/mutex.h> #include <log4cxx/helpers/exception.h> #include <apr_thread_mutex.h> #include <assert.h> #if !defined(LOG4CXX) #define LOG4CXX 1 #endif #include <log4cxx/helpers/aprinitializer.h> using namespace log4cxx::helpers; using namespace log4cxx; Mutex::Mutex(Pool& p) { #if APR_HAS_THREADS apr_status_t stat = apr_thread_mutex_create(&mutex, APR_THREAD_MUTEX_NESTED, p.getAPRPool()); if (stat != APR_SUCCESS) { throw MutexException(stat); } #endif } Mutex::Mutex(apr_pool_t* p) { #if APR_HAS_THREADS apr_status_t stat = apr_thread_mutex_create(&mutex, APR_THREAD_MUTEX_NESTED, p); if (stat != APR_SUCCESS) { throw MutexException(stat); } #endif } Mutex::~Mutex() { #if APR_HAS_THREADS apr_thread_mutex_destroy(mutex); #endif } apr_thread_mutex_t* Mutex::getAPRMutex() const { return mutex; }
001-log4cxx
trunk/src/main/cpp/mutex.cpp
C++
asf20
1,786
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <log4cxx/logstring.h> #include <log4cxx/appender.h> #include <log4cxx/logger.h> #include <log4cxx/varia/fallbackerrorhandler.h> #include <log4cxx/helpers/loglog.h> #include <log4cxx/helpers/stringhelper.h> #include <log4cxx/spi/loggingevent.h> using namespace log4cxx; using namespace log4cxx::helpers; using namespace log4cxx::spi; using namespace log4cxx::varia; IMPLEMENT_LOG4CXX_OBJECT(FallbackErrorHandler) FallbackErrorHandler::FallbackErrorHandler() : backup(), primary(), loggers() { } void FallbackErrorHandler::addRef() const { ObjectImpl::addRef(); } void FallbackErrorHandler::releaseRef() const { ObjectImpl::releaseRef(); } void FallbackErrorHandler::setLogger(const LoggerPtr& logger) { LogLog::debug(((LogString) LOG4CXX_STR("FB: Adding logger [")) + logger->getName() + LOG4CXX_STR("].")); loggers.push_back(logger); } void FallbackErrorHandler::error(const LogString& message, const std::exception& e, int errorCode) const { error(message, e, errorCode, 0); } void FallbackErrorHandler::error(const LogString& message, const std::exception& e, int, const spi::LoggingEventPtr&) const { LogLog::debug(((LogString) LOG4CXX_STR("FB: The following error reported: ")) + message, e); LogLog::debug(LOG4CXX_STR("FB: INITIATING FALLBACK PROCEDURE.")); for(size_t i = 0; i < loggers.size(); i++) { LoggerPtr& l = (LoggerPtr&)loggers.at(i); LogLog::debug(((LogString) LOG4CXX_STR("FB: Searching for [")) + primary->getName() + LOG4CXX_STR("] in logger [") + l->getName() + LOG4CXX_STR("].")); LogLog::debug(((LogString) LOG4CXX_STR("FB: Replacing [")) + primary->getName() + LOG4CXX_STR("] by [") + backup->getName() + LOG4CXX_STR("] in logger [") + l->getName() + LOG4CXX_STR("].")); l->removeAppender(primary); LogLog::debug(((LogString) LOG4CXX_STR("FB: Adding appender [")) + backup->getName() + LOG4CXX_STR("] to logger ") + l->getName()); l->addAppender(backup); } } void FallbackErrorHandler::setAppender(const AppenderPtr& primary1) { LogLog::debug(((LogString) LOG4CXX_STR("FB: Setting primary appender to [")) + primary1->getName() + LOG4CXX_STR("].")); this->primary = primary1; } void FallbackErrorHandler::setBackupAppender(const AppenderPtr& backup1) { LogLog::debug(((LogString) LOG4CXX_STR("FB: Setting backup appender to [")) + backup1->getName() + LOG4CXX_STR("].")); this->backup = backup1; } void FallbackErrorHandler::activateOptions(Pool&) { } void FallbackErrorHandler::setOption(const LogString&, const LogString&) { }
001-log4cxx
trunk/src/main/cpp/fallbackerrorhandler.cpp
C++
asf20
3,698
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #if defined(_MSC_VER) #pragma warning ( disable: 4231 4251 4275 4786 ) #endif #include <log4cxx/logstring.h> #include <log4cxx/pattern/relativetimepatternconverter.h> #include <log4cxx/spi/loggingevent.h> #include <log4cxx/spi/location/locationinfo.h> #include <log4cxx/helpers/stringhelper.h> using namespace log4cxx; using namespace log4cxx::pattern; using namespace log4cxx::spi; using namespace log4cxx::helpers; IMPLEMENT_LOG4CXX_OBJECT(RelativeTimePatternConverter) RelativeTimePatternConverter::RelativeTimePatternConverter() : LoggingEventPatternConverter(LOG4CXX_STR("Time"), LOG4CXX_STR("time")) { } PatternConverterPtr RelativeTimePatternConverter::newInstance( const std::vector<LogString>& /* options */) { static PatternConverterPtr def(new RelativeTimePatternConverter()); return def; } void RelativeTimePatternConverter::format( const LoggingEventPtr& event, LogString& toAppendTo, Pool& p) const { log4cxx_time_t delta = (event->getTimeStamp() - LoggingEvent::getStartTime())/1000; StringHelper::toString(delta, p, toAppendTo); }
001-log4cxx
trunk/src/main/cpp/relativetimepatternconverter.cpp
C++
asf20
1,891
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #if defined(_MSC_VER) #pragma warning ( disable: 4231 4251 4275 4786 ) #endif #include <log4cxx/logstring.h> #include <log4cxx/pattern/propertiespatternconverter.h> #include <log4cxx/spi/loggingevent.h> #include <log4cxx/spi/location/locationinfo.h> using namespace log4cxx; using namespace log4cxx::pattern; using namespace log4cxx::spi; using namespace log4cxx::helpers; IMPLEMENT_LOG4CXX_OBJECT(PropertiesPatternConverter) PropertiesPatternConverter::PropertiesPatternConverter(const LogString& name1, const LogString& propertyName) : LoggingEventPatternConverter(name1,LOG4CXX_STR("property")), option(propertyName) { } PatternConverterPtr PropertiesPatternConverter::newInstance( const std::vector<LogString>& options) { if (options.size() == 0) { static PatternConverterPtr def(new PropertiesPatternConverter( LOG4CXX_STR("Properties"), LOG4CXX_STR(""))); return def; } LogString converterName(LOG4CXX_STR("Property{")); converterName.append(options[0]); converterName.append(LOG4CXX_STR("}")); PatternConverterPtr converter(new PropertiesPatternConverter( converterName, options[0])); return converter; } void PropertiesPatternConverter::format( const LoggingEventPtr& event, LogString& toAppendTo, Pool& /* p */) const { if (option.length() == 0) { toAppendTo.append(1, (logchar) 0x7B /* '{' */); LoggingEvent::KeySet keySet(event->getMDCKeySet()); for(LoggingEvent::KeySet::const_iterator iter = keySet.begin(); iter != keySet.end(); iter++) { toAppendTo.append(1, (logchar) 0x7B /* '{' */); toAppendTo.append(*iter); toAppendTo.append(1, (logchar) 0x2C /* ',' */); event->getMDC(*iter, toAppendTo); toAppendTo.append(1, (logchar) 0x7D /* '}' */); } toAppendTo.append(1, (logchar) 0x7D /* '}' */); } else { event->getMDC(option, toAppendTo); } }
001-log4cxx
trunk/src/main/cpp/propertiespatternconverter.cpp
C++
asf20
2,760
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #if defined(_MSC_VER) #pragma warning ( disable: 4231 4251 4275 4786 ) #endif #include <log4cxx/logstring.h> #include <log4cxx/pattern/throwableinformationpatternconverter.h> #include <log4cxx/spi/loggingevent.h> #include <log4cxx/spi/location/locationinfo.h> #include <log4cxx/helpers/stringhelper.h> using namespace log4cxx; using namespace log4cxx::pattern; using namespace log4cxx::spi; using namespace log4cxx::helpers; IMPLEMENT_LOG4CXX_OBJECT(ThrowableInformationPatternConverter) ThrowableInformationPatternConverter::ThrowableInformationPatternConverter(bool shortReport1) : LoggingEventPatternConverter(LOG4CXX_STR("Throwable"), LOG4CXX_STR("throwable")), shortReport(shortReport1) { } PatternConverterPtr ThrowableInformationPatternConverter::newInstance( const std::vector<LogString>& options) { if (options.size() > 0 && options[0].compare(LOG4CXX_STR("short")) == 0) { static PatternConverterPtr shortConverter(new ThrowableInformationPatternConverter(true)); return shortConverter; } static PatternConverterPtr converter(new ThrowableInformationPatternConverter(false)); return converter; } void ThrowableInformationPatternConverter::format( const LoggingEventPtr& /* event */, LogString& /* toAppendTo */, Pool& /* p */) const { } /** * This converter obviously handles throwables. * @return true. */ bool ThrowableInformationPatternConverter::handlesThrowable() const { return true; }
001-log4cxx
trunk/src/main/cpp/throwableinformationpatternconverter.cpp
C++
asf20
2,275
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <log4cxx/logstring.h> #include <log4cxx/helpers/cyclicbuffer.h> #include <log4cxx/spi/loggingevent.h> #include <log4cxx/helpers/exception.h> #include <log4cxx/helpers/pool.h> #include <log4cxx/helpers/stringhelper.h> using namespace log4cxx; using namespace log4cxx::helpers; using namespace log4cxx::spi; /** Instantiate a new CyclicBuffer of at most <code>maxSize</code> events. The <code>maxSize</code> argument must a positive integer. @param maxSize The maximum number of elements in the buffer. */ CyclicBuffer::CyclicBuffer(int maxSize1) : ea(maxSize1), first(0), last(0), numElems(0), maxSize(maxSize1) { if(maxSize1 < 1) { LogString msg(LOG4CXX_STR("The maxSize argument (")); Pool p; StringHelper::toString(maxSize1, p, msg); msg.append(LOG4CXX_STR(") is not a positive integer.")); throw IllegalArgumentException(msg); } } CyclicBuffer::~CyclicBuffer() { } /** Add an <code>event</code> as the last event in the buffer. */ void CyclicBuffer::add(const spi::LoggingEventPtr& event) { ea[last] = event; if(++last == maxSize) { last = 0; } if(numElems < maxSize) { numElems++; } else if(++first == maxSize) { first = 0; } } /** Get the <i>i</i>th oldest event currently in the buffer. If <em>i</em> is outside the range 0 to the number of elements currently in the buffer, then <code>null</code> is returned. */ spi::LoggingEventPtr CyclicBuffer::get(int i) { if(i < 0 || i >= numElems) return 0; return ea[(first + i) % maxSize]; } /** Get the oldest (first) element in the buffer. The oldest element is removed from the buffer. */ spi::LoggingEventPtr CyclicBuffer::get() { LoggingEventPtr r; if(numElems > 0) { numElems--; r = ea[first]; ea[first] = 0; if(++first == maxSize) { first = 0; } } return r; } /** Resize the cyclic buffer to <code>newSize</code>. @throws IllegalArgumentException if <code>newSize</code> is negative. */ void CyclicBuffer::resize(int newSize) { if(newSize < 0) { LogString msg(LOG4CXX_STR("Negative array size [")); Pool p; StringHelper::toString(newSize, p, msg); msg.append(LOG4CXX_STR("] not allowed.")); throw IllegalArgumentException(msg); } if(newSize == numElems) return; // nothing to do LoggingEventList temp(newSize); int loopLen = newSize < numElems ? newSize : numElems; int i; for(i = 0; i < loopLen; i++) { temp[i] = ea[first]; ea[first] = 0; if(++first == numElems) first = 0; } ea = temp; first = 0; numElems = loopLen; maxSize = newSize; if (loopLen == newSize) { last = 0; } else { last = loopLen; } }
001-log4cxx
trunk/src/main/cpp/cyclicbuffer.cpp
C++
asf20
4,029
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #if defined(_MSC_VER) #pragma warning ( disable: 4231 4251 4275 4786 ) #endif #include <log4cxx/logstring.h> #include <log4cxx/pattern/datepatternconverter.h> #include <log4cxx/spi/loggingevent.h> #include <log4cxx/spi/location/locationinfo.h> #include <log4cxx/helpers/absolutetimedateformat.h> #include <log4cxx/helpers/datetimedateformat.h> #include <log4cxx/helpers/iso8601dateformat.h> #include <log4cxx/helpers/strftimedateformat.h> #include <log4cxx/helpers/stringhelper.h> #include <log4cxx/helpers/exception.h> #include <log4cxx/helpers/loglog.h> #include <log4cxx/helpers/date.h> using namespace log4cxx; using namespace log4cxx::pattern; using namespace log4cxx::spi; using namespace log4cxx::helpers; IMPLEMENT_LOG4CXX_OBJECT(DatePatternConverter) DatePatternConverter::DatePatternConverter( const std::vector<LogString>& options) : LoggingEventPatternConverter(LOG4CXX_STR("Class Name"), LOG4CXX_STR("class name")), df(getDateFormat(options)) { } DateFormatPtr DatePatternConverter::getDateFormat(const OptionsList& options) { DateFormatPtr df; int maximumCacheValidity = 1000000; if (options.size() == 0) { df = new ISO8601DateFormat(); } else { LogString dateFormatStr(options[0]); if(dateFormatStr.empty() || StringHelper::equalsIgnoreCase(dateFormatStr, LOG4CXX_STR("ISO8601"), LOG4CXX_STR("iso8601"))) { df = new ISO8601DateFormat(); } else if(StringHelper::equalsIgnoreCase(dateFormatStr, LOG4CXX_STR("ABSOLUTE"), LOG4CXX_STR("absolute"))) { df = new AbsoluteTimeDateFormat(); } else if(StringHelper::equalsIgnoreCase(dateFormatStr, LOG4CXX_STR("DATE"), LOG4CXX_STR("date"))) { df = new DateTimeDateFormat(); } else { if (dateFormatStr.find(0x25 /*'%'*/) == std::string::npos) { try { df = new SimpleDateFormat(dateFormatStr); maximumCacheValidity = CachedDateFormat::getMaximumCacheValidity(dateFormatStr); } catch(IllegalArgumentException& e) { df = new ISO8601DateFormat(); LogLog::warn(((LogString) LOG4CXX_STR("Could not instantiate SimpleDateFormat with pattern ")) + dateFormatStr, e); } } else { df = new StrftimeDateFormat(dateFormatStr); } } if (options.size() >= 2) { TimeZonePtr tz(TimeZone::getTimeZone(options[1])); if (tz != NULL) { df->setTimeZone(tz); } } } if (maximumCacheValidity > 0) { df = new CachedDateFormat(df, maximumCacheValidity); } return df; } PatternConverterPtr DatePatternConverter::newInstance( const std::vector<LogString>& options) { return new DatePatternConverter(options); } void DatePatternConverter::format( const LoggingEventPtr& event, LogString& toAppendTo, Pool& p) const { df->format(toAppendTo, event->getTimeStamp(), p); } /** * {@inheritDoc} */ void DatePatternConverter::format( const ObjectPtr& obj, LogString& toAppendTo, Pool& p) const { DatePtr date(obj); if (date != NULL) { format(date, toAppendTo, p); } else { LoggingEventPtr event(obj); if (event != NULL) { format(event, toAppendTo, p); } } } /** * Append formatted date to string buffer. * @param date date * @param toAppendTo buffer to which formatted date is appended. */ void DatePatternConverter::format( const DatePtr& date, LogString& toAppendTo, Pool& p) const { df->format(toAppendTo, date->getTime(), p); }
001-log4cxx
trunk/src/main/cpp/datepatternconverter.cpp
C++
asf20
4,422
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #if defined(_MSC_VER) #pragma warning ( disable: 4231 4251 4275 4786 ) #endif #include <log4cxx/logstring.h> #include <log4cxx/pattern/methodlocationpatternconverter.h> #include <log4cxx/spi/loggingevent.h> #include <log4cxx/spi/location/locationinfo.h> using namespace log4cxx; using namespace log4cxx::pattern; using namespace log4cxx::spi; using namespace log4cxx::helpers; IMPLEMENT_LOG4CXX_OBJECT(MethodLocationPatternConverter) MethodLocationPatternConverter::MethodLocationPatternConverter() : LoggingEventPatternConverter(LOG4CXX_STR("Method"), LOG4CXX_STR("method")) { } PatternConverterPtr MethodLocationPatternConverter::newInstance( const std::vector<LogString>& /* options */ ) { static PatternConverterPtr def(new MethodLocationPatternConverter()); return def; } void MethodLocationPatternConverter::format( const LoggingEventPtr& event, LogString& toAppendTo, Pool& /* p */ ) const { append(toAppendTo, event->getLocationInformation().getMethodName()); }
001-log4cxx
trunk/src/main/cpp/methodlocationpatternconverter.cpp
C++
asf20
1,809
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <log4cxx/net/xmlsocketappender.h> #include <log4cxx/helpers/loglog.h> #include <log4cxx/helpers/outputstreamwriter.h> #include <log4cxx/helpers/charsetencoder.h> #include <log4cxx/helpers/optionconverter.h> #include <log4cxx/helpers/stringhelper.h> #include <log4cxx/xml/xmllayout.h> #include <log4cxx/level.h> #include <log4cxx/helpers/transform.h> #include <apr_time.h> #include <log4cxx/helpers/synchronized.h> #include <log4cxx/helpers/transcoder.h> #include <log4cxx/helpers/socketoutputstream.h> using namespace log4cxx; using namespace log4cxx::helpers; using namespace log4cxx::net; using namespace log4cxx::xml; IMPLEMENT_LOG4CXX_OBJECT(XMLSocketAppender) // The default port number of remote logging server (4560) int XMLSocketAppender::DEFAULT_PORT = 4560; // The default reconnection delay (30000 milliseconds or 30 seconds). int XMLSocketAppender::DEFAULT_RECONNECTION_DELAY = 30000; const int XMLSocketAppender::MAX_EVENT_LEN = 1024; XMLSocketAppender::XMLSocketAppender() : SocketAppenderSkeleton(DEFAULT_PORT, DEFAULT_RECONNECTION_DELAY) { layout = new XMLLayout(); } XMLSocketAppender::XMLSocketAppender(InetAddressPtr address1, int port1) : SocketAppenderSkeleton(address1, port1, DEFAULT_RECONNECTION_DELAY) { layout = new XMLLayout(); Pool p; activateOptions(p); } XMLSocketAppender::XMLSocketAppender(const LogString& host, int port1) : SocketAppenderSkeleton(host, port1, DEFAULT_RECONNECTION_DELAY) { layout = new XMLLayout(); Pool p; activateOptions(p); } XMLSocketAppender::~XMLSocketAppender() { finalize(); } int XMLSocketAppender::getDefaultDelay() const { return DEFAULT_RECONNECTION_DELAY; } int XMLSocketAppender::getDefaultPort() const { return DEFAULT_PORT; } void XMLSocketAppender::setSocket(log4cxx::helpers::SocketPtr& socket, Pool& p) { OutputStreamPtr os(new SocketOutputStream(socket)); CharsetEncoderPtr charset(CharsetEncoder::getUTF8Encoder()); synchronized sync(mutex); writer = new OutputStreamWriter(os, charset); } void XMLSocketAppender::cleanUp(Pool& p) { if (writer != 0) { try { writer->close(p); writer = 0; } catch(std::exception &e) { } } } void XMLSocketAppender::append(const spi::LoggingEventPtr& event, log4cxx::helpers::Pool& p) { if (writer != 0) { LogString output; layout->format(output, event, p); try { writer->write(output, p); writer->flush(p); } catch(std::exception& e) { writer = 0; LogLog::warn(LOG4CXX_STR("Detected problem with connection: "), e); if (getReconnectionDelay() > 0) { fireConnector(); } } } }
001-log4cxx
trunk/src/main/cpp/xmlsocketappender.cpp
C++
asf20
3,609
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <log4cxx/logstring.h> #include <log4cxx/helpers/loglog.h> #include <log4cxx/helpers/transcoder.h> #include <iostream> #if !defined(LOG4CXX) #define LOG4CXX 1 #endif #include <log4cxx/private/log4cxx_private.h> #include <log4cxx/helpers/synchronized.h> #include <log4cxx/helpers/aprinitializer.h> #include <log4cxx/helpers/systemerrwriter.h> using namespace log4cxx; using namespace log4cxx::helpers; LogLog::LogLog() : mutex(APRInitializer::getRootPool()) { synchronized sync(mutex); debugEnabled = false; quietMode = false; } LogLog& LogLog::getInstance() { static LogLog internalLogger; return internalLogger; } void LogLog::setInternalDebugging(bool debugEnabled1) { synchronized sync(getInstance().mutex); getInstance().debugEnabled = debugEnabled1; } void LogLog::debug(const LogString& msg) { synchronized sync(getInstance().mutex); if(getInstance().debugEnabled && !getInstance().quietMode) { emit(msg); } } void LogLog::debug(const LogString& msg, const std::exception& e) { synchronized sync(getInstance().mutex); debug(msg); emit(e); } void LogLog::error(const LogString& msg) { synchronized sync(getInstance().mutex); if(!getInstance().quietMode) { emit(msg); } } void LogLog::error(const LogString& msg, const std::exception& e) { synchronized sync(getInstance().mutex); error(msg); emit(e); } void LogLog::setQuietMode(bool quietMode1) { synchronized sync(getInstance().mutex); getInstance().quietMode = quietMode1; } void LogLog::warn(const LogString& msg) { synchronized sync(getInstance().mutex); if(!getInstance().quietMode) { emit(msg); } } void LogLog::warn(const LogString& msg, const std::exception& e) { synchronized sync(getInstance().mutex); warn(msg); emit(e); } void LogLog::emit(const LogString& msg) { LogString out(LOG4CXX_STR("log4cxx: ")); out.append(msg); out.append(1, (logchar) 0x0A); SystemErrWriter::write(out); } void LogLog::emit(const std::exception& ex) { LogString out(LOG4CXX_STR("log4cxx: ")); const char* raw = ex.what(); if (raw != 0) { Transcoder::decode(raw, out); } else { out.append(LOG4CXX_STR("std::exception::what() == null")); } out.append(1, (logchar) 0x0A); SystemErrWriter::write(out); }
001-log4cxx
trunk/src/main/cpp/loglog.cpp
C++
asf20
3,273
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <log4cxx/logstring.h> #include <log4cxx/helpers/charsetdecoder.h> #include <log4cxx/helpers/bytebuffer.h> #include <log4cxx/helpers/exception.h> #include <log4cxx/helpers/mutex.h> #include <log4cxx/helpers/synchronized.h> #include <log4cxx/helpers/pool.h> #include <apr_xlate.h> #if !defined(LOG4CXX) #define LOG4CXX 1 #endif #include <log4cxx/private/log4cxx_private.h> #include <locale.h> #include <apr_portable.h> #include <log4cxx/helpers/stringhelper.h> #include <log4cxx/helpers/transcoder.h> using namespace log4cxx; using namespace log4cxx::helpers; IMPLEMENT_LOG4CXX_OBJECT(CharsetDecoder) namespace log4cxx { namespace helpers { #if APR_HAS_XLATE /** * Converts from an arbitrary encoding to LogString * using apr_xlate. Requires real iconv implementation, * apr-iconv will crash in use. */ class APRCharsetDecoder : public CharsetDecoder { public: /** * Creates a new instance. * @param frompage name of source encoding. */ APRCharsetDecoder(const LogString& frompage) : pool(), mutex(pool) { #if LOG4CXX_LOGCHAR_IS_WCHAR const char* topage = "WCHAR_T"; #endif #if LOG4CXX_LOGCHAR_IS_UTF8 const char* topage = "UTF-8"; #endif #if LOG4CXX_LOGCHAR_IS_UNICHAR const char* topage = "UTF-16"; #endif std::string fpage(Transcoder::encodeCharsetName(frompage)); apr_status_t stat = apr_xlate_open(&convset, topage, fpage.c_str(), pool.getAPRPool()); if (stat != APR_SUCCESS) { throw IllegalArgumentException(frompage); } } /** * Destructor. */ virtual ~APRCharsetDecoder() { } virtual log4cxx_status_t decode(ByteBuffer& in, LogString& out) { enum { BUFSIZE = 256 }; logchar buf[BUFSIZE]; const apr_size_t initial_outbytes_left = BUFSIZE * sizeof(logchar); apr_status_t stat = APR_SUCCESS; if (in.remaining() == 0) { size_t outbytes_left = initial_outbytes_left; { synchronized sync(mutex); stat = apr_xlate_conv_buffer((apr_xlate_t*) convset, NULL, NULL, (char*) buf, &outbytes_left); } out.append(buf, (initial_outbytes_left - outbytes_left)/sizeof(logchar)); } else { while(in.remaining() > 0 && stat == APR_SUCCESS) { size_t inbytes_left = in.remaining(); size_t initial_inbytes_left = inbytes_left; size_t pos = in.position(); apr_size_t outbytes_left = initial_outbytes_left; { synchronized sync(mutex); stat = apr_xlate_conv_buffer((apr_xlate_t*) convset, in.data() + pos, &inbytes_left, (char*) buf, &outbytes_left); } out.append(buf, (initial_outbytes_left - outbytes_left)/sizeof(logchar)); in.position(pos + (initial_inbytes_left - inbytes_left)); } } return stat; } private: APRCharsetDecoder(const APRCharsetDecoder&); APRCharsetDecoder& operator=(const APRCharsetDecoder&); log4cxx::helpers::Pool pool; Mutex mutex; apr_xlate_t *convset; }; #endif #if LOG4CXX_LOGCHAR_IS_WCHAR && LOG4CXX_HAS_MBSRTOWCS /** * Converts from the default multi-byte string to * LogString using mbstowcs. * */ class MbstowcsCharsetDecoder : public CharsetDecoder { public: MbstowcsCharsetDecoder() { } virtual ~MbstowcsCharsetDecoder() { } private: inline log4cxx_status_t append(LogString& out, const wchar_t* buf) { out.append(buf); return APR_SUCCESS; } virtual log4cxx_status_t decode(ByteBuffer& in, LogString& out) { log4cxx_status_t stat = APR_SUCCESS; enum { BUFSIZE = 256 }; wchar_t buf[BUFSIZE]; mbstate_t mbstate; memset(&mbstate, 0, sizeof(mbstate)); while(in.remaining() > 0) { size_t requested = in.remaining(); if (requested > BUFSIZE - 1) { requested = BUFSIZE - 1; } memset(buf, 0, BUFSIZE*sizeof(wchar_t)); const char* src = in.current(); if(*src == 0) { out.append(1, (logchar) 0); in.position(in.position() + 1); } else { size_t converted = mbsrtowcs(buf, &src, requested, &mbstate); if (converted == (size_t) -1) { stat = APR_BADARG; in.position(src - in.data()); break; } else { stat = append(out, buf); in.position(in.position() + converted); } } } return stat; } private: MbstowcsCharsetDecoder(const MbstowcsCharsetDecoder&); MbstowcsCharsetDecoder& operator=(const MbstowcsCharsetDecoder&); }; #endif /** * Decoder used when the external and internal charsets * are the same. * */ class TrivialCharsetDecoder : public CharsetDecoder { public: TrivialCharsetDecoder() { } virtual ~TrivialCharsetDecoder() { } virtual log4cxx_status_t decode(ByteBuffer& in, LogString& out) { size_t remaining = in.remaining(); if( remaining > 0) { const logchar* src = (const logchar*) (in.data() + in.position()); size_t count = remaining / sizeof(logchar); out.append(src, count); in.position(in.position() + remaining); } return APR_SUCCESS; } private: TrivialCharsetDecoder(const TrivialCharsetDecoder&); TrivialCharsetDecoder& operator=(const TrivialCharsetDecoder&); }; #if LOG4CXX_LOGCHAR_IS_UTF8 typedef TrivialCharsetDecoder UTF8CharsetDecoder; #else /** * Converts from UTF-8 to std::wstring * */ class UTF8CharsetDecoder : public CharsetDecoder { public: UTF8CharsetDecoder() { } virtual ~UTF8CharsetDecoder() { } private: virtual log4cxx_status_t decode(ByteBuffer& in, LogString& out) { if (in.remaining() > 0) { std::string tmp(in.current(), in.remaining()); std::string::const_iterator iter = tmp.begin(); while(iter != tmp.end()) { unsigned int sv = Transcoder::decode(tmp, iter); if (sv == 0xFFFF) { size_t offset = iter - tmp.begin(); in.position(in.position() + offset); return APR_BADARG; } else { Transcoder::encode(sv, out); } } in.position(in.limit()); } return APR_SUCCESS; } private: UTF8CharsetDecoder(const UTF8CharsetDecoder&); UTF8CharsetDecoder& operator=(const UTF8CharsetDecoder&); }; #endif /** * Converts from ISO-8859-1 to LogString. * */ class ISOLatinCharsetDecoder : public CharsetDecoder { public: ISOLatinCharsetDecoder() { } virtual ~ISOLatinCharsetDecoder() { } private: virtual log4cxx_status_t decode(ByteBuffer& in, LogString& out) { if (in.remaining() > 0) { const unsigned char* src = (unsigned char*) in.current(); const unsigned char* srcEnd = src + in.remaining(); while(src < srcEnd) { unsigned int sv = *(src++); Transcoder::encode(sv, out); } in.position(in.limit()); } return APR_SUCCESS; } private: ISOLatinCharsetDecoder(const ISOLatinCharsetDecoder&); ISOLatinCharsetDecoder& operator=(const ISOLatinCharsetDecoder&); }; /** * Converts from US-ASCII to LogString. * */ class USASCIICharsetDecoder : public CharsetDecoder { public: USASCIICharsetDecoder() { } virtual ~USASCIICharsetDecoder() { } private: virtual log4cxx_status_t decode(ByteBuffer& in, LogString& out) { log4cxx_status_t stat = APR_SUCCESS; if (in.remaining() > 0) { const unsigned char* src = (unsigned char*) in.current(); const unsigned char* srcEnd = src + in.remaining(); while(src < srcEnd) { unsigned char sv = *src; if (sv < 0x80) { src++; Transcoder::encode(sv, out); } else { stat = APR_BADARG; break; } } in.position(src - (const unsigned char*) in.data()); } return stat; } private: USASCIICharsetDecoder(const USASCIICharsetDecoder&); USASCIICharsetDecoder& operator=(const USASCIICharsetDecoder&); }; /** * Charset decoder that uses an embedded CharsetDecoder consistent * with current locale settings. */ class LocaleCharsetDecoder : public CharsetDecoder { public: LocaleCharsetDecoder() : pool(), mutex(pool), decoder(), encoding() { } virtual ~LocaleCharsetDecoder() { } virtual log4cxx_status_t decode(ByteBuffer& in, LogString& out) { const char* p = in.current(); size_t i = in.position(); #if !LOG4CXX_CHARSET_EBCDIC for (; i < in.limit() && ((unsigned int) *p) < 0x80; i++, p++) { out.append(1, *p); } in.position(i); #endif if (i < in.limit()) { Pool subpool; const char* enc = apr_os_locale_encoding(subpool.getAPRPool()); { synchronized sync(mutex); if (enc == 0) { if (decoder == 0) { encoding = "C"; decoder = new USASCIICharsetDecoder(); } } else if (encoding != enc) { encoding = enc; try { LogString e; Transcoder::decode(encoding, e); decoder = getDecoder(e); } catch (IllegalArgumentException& ex) { decoder = new USASCIICharsetDecoder(); } } } return decoder->decode(in, out); } return APR_SUCCESS; } private: Pool pool; Mutex mutex; CharsetDecoderPtr decoder; std::string encoding; }; } // namespace helpers } //namespace log4cxx CharsetDecoder::CharsetDecoder() { } CharsetDecoder::~CharsetDecoder() { } CharsetDecoder* CharsetDecoder::createDefaultDecoder() { #if LOG4CXX_CHARSET_UTF8 return new UTF8CharsetDecoder(); #elif LOG4CXX_CHARSET_ISO88591 || defined(_WIN32_WCE) return new ISOLatinCharsetDecoder(); #elif LOG4CXX_CHARSET_USASCII return new USASCIICharsetDecoder(); #elif LOG4CXX_LOGCHAR_IS_WCHAR && LOG4CXX_HAS_MBSRTOWCS return new MbstowcsCharsetDecoder(); #else return new LocaleCharsetDecoder(); #endif } CharsetDecoderPtr CharsetDecoder::getDefaultDecoder() { static CharsetDecoderPtr decoder(createDefaultDecoder()); // // if invoked after static variable destruction // (if logging is called in the destructor of a static object) // then create a new decoder. // if (decoder == 0) { return createDefaultDecoder(); } return decoder; } CharsetDecoderPtr CharsetDecoder::getUTF8Decoder() { static CharsetDecoderPtr decoder(new UTF8CharsetDecoder()); // // if invoked after static variable destruction // (if logging is called in the destructor of a static object) // then create a new decoder. // if (decoder == 0) { return new UTF8CharsetDecoder(); } return decoder; } CharsetDecoderPtr CharsetDecoder::getISOLatinDecoder() { return new ISOLatinCharsetDecoder(); } CharsetDecoderPtr CharsetDecoder::getDecoder(const LogString& charset) { if (StringHelper::equalsIgnoreCase(charset, LOG4CXX_STR("UTF-8"), LOG4CXX_STR("utf-8")) || StringHelper::equalsIgnoreCase(charset, LOG4CXX_STR("UTF8"), LOG4CXX_STR("utf8"))) { return new UTF8CharsetDecoder(); } else if (StringHelper::equalsIgnoreCase(charset, LOG4CXX_STR("C"), LOG4CXX_STR("c")) || charset == LOG4CXX_STR("646") || StringHelper::equalsIgnoreCase(charset, LOG4CXX_STR("US-ASCII"), LOG4CXX_STR("us-ascii")) || StringHelper::equalsIgnoreCase(charset, LOG4CXX_STR("ISO646-US"), LOG4CXX_STR("iso646-US")) || StringHelper::equalsIgnoreCase(charset, LOG4CXX_STR("ANSI_X3.4-1968"), LOG4CXX_STR("ansi_x3.4-1968"))) { return new USASCIICharsetDecoder(); } else if (StringHelper::equalsIgnoreCase(charset, LOG4CXX_STR("ISO-8859-1"), LOG4CXX_STR("iso-8859-1")) || StringHelper::equalsIgnoreCase(charset, LOG4CXX_STR("ISO-LATIN-1"), LOG4CXX_STR("iso-latin-1"))) { return new ISOLatinCharsetDecoder(); } #if APR_HAS_XLATE || !defined(_WIN32) return new APRCharsetDecoder(charset); #else throw IllegalArgumentException(charset); #endif }
001-log4cxx
trunk/src/main/cpp/charsetdecoder.cpp
C++
asf20
15,992
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <log4cxx/rolling/sizebasedtriggeringpolicy.h> #include <log4cxx/helpers/stringhelper.h> #include <log4cxx/helpers/optionconverter.h> using namespace log4cxx; using namespace log4cxx::rolling; using namespace log4cxx::helpers; IMPLEMENT_LOG4CXX_OBJECT(SizeBasedTriggeringPolicy) SizeBasedTriggeringPolicy::SizeBasedTriggeringPolicy() : maxFileSize(10 * 1024 * 1024) { } bool SizeBasedTriggeringPolicy::isTriggeringEvent(Appender* /* appender */, const log4cxx::spi::LoggingEventPtr& /* event */, const LogString& /* file */, size_t fileLength) { return (fileLength >= maxFileSize); } size_t SizeBasedTriggeringPolicy::getMaxFileSize() { return maxFileSize; } void SizeBasedTriggeringPolicy::setMaxFileSize(size_t l) { maxFileSize = l; } void SizeBasedTriggeringPolicy::activateOptions(Pool& /* p */) { } void SizeBasedTriggeringPolicy::setOption(const LogString& option, const LogString& value) { if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("MAXFILESIZE"), LOG4CXX_STR("maxfilesize"))) { maxFileSize = OptionConverter::toFileSize(value, 10*1024*1024); } }
001-log4cxx
trunk/src/main/cpp/sizebasedtriggeringpolicy.cpp
C++
asf20
1,954
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #if defined(_MSC_VER) #pragma warning ( disable: 4231 4251 4275 4786 ) #endif #define __STDC_CONSTANT_MACROS #include <log4cxx/net/socketappenderskeleton.h> #include <log4cxx/helpers/loglog.h> #include <log4cxx/helpers/optionconverter.h> #include <log4cxx/helpers/stringhelper.h> #include <log4cxx/spi/loggingevent.h> #include <log4cxx/helpers/synchronized.h> #include <log4cxx/helpers/transcoder.h> #include <log4cxx/helpers/bytearrayoutputstream.h> using namespace log4cxx; using namespace log4cxx::helpers; using namespace log4cxx::net; SocketAppenderSkeleton::SocketAppenderSkeleton(int defaultPort, int reconnectionDelay1) : remoteHost(), address(), port(defaultPort), reconnectionDelay(reconnectionDelay1), locationInfo(false), thread() { } SocketAppenderSkeleton::SocketAppenderSkeleton(InetAddressPtr address1, int port1, int delay) : remoteHost(), address(address1), port(port1), reconnectionDelay(delay), locationInfo(false), thread() { remoteHost = this->address->getHostName(); } SocketAppenderSkeleton::SocketAppenderSkeleton(const LogString& host, int port1, int delay) : remoteHost(host), address(InetAddress::getByName(host)), port(port1), reconnectionDelay(delay), locationInfo(false), thread() { } SocketAppenderSkeleton::~SocketAppenderSkeleton() { finalize(); } void SocketAppenderSkeleton::activateOptions(Pool& p) { AppenderSkeleton::activateOptions(p); connect(p); } void SocketAppenderSkeleton::close() { synchronized sync(mutex); if (closed) return; closed = true; cleanUp(pool); thread.interrupt(); } void SocketAppenderSkeleton::connect(Pool& p) { if (address == 0) { LogLog::error(LogString(LOG4CXX_STR("No remote host is set for Appender named \"")) + name + LOG4CXX_STR("\".")); } else { cleanUp(p); try { SocketPtr socket(new Socket(address, port)); setSocket(socket, p); } catch(SocketException& e) { LogString msg = LOG4CXX_STR("Could not connect to remote log4cxx server at [") +address->getHostName()+LOG4CXX_STR("]."); if(reconnectionDelay > 0) { msg += LOG4CXX_STR(" We will try again later. "); } fireConnector(); // fire the connector thread LogLog::error(msg, e); } } } void SocketAppenderSkeleton::setOption(const LogString& option, const LogString& value) { if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("REMOTEHOST"), LOG4CXX_STR("remotehost"))) { setRemoteHost(value); } else if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("PORT"), LOG4CXX_STR("port"))) { setPort(OptionConverter::toInt(value, getDefaultPort())); } else if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("LOCATIONINFO"), LOG4CXX_STR("locationinfo"))) { setLocationInfo(OptionConverter::toBoolean(value, false)); } else if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("RECONNECTIONDELAY"), LOG4CXX_STR("reconnectiondelay"))) { setReconnectionDelay(OptionConverter::toInt(value, getDefaultDelay())); } else { AppenderSkeleton::setOption(option, value); } } void SocketAppenderSkeleton::fireConnector() { synchronized sync(mutex); if (thread.isActive()) { thread.run(monitor, this); } } void* LOG4CXX_THREAD_FUNC SocketAppenderSkeleton::monitor(apr_thread_t* /* thread */, void* data) { SocketAppenderSkeleton* socketAppender = (SocketAppenderSkeleton*) data; SocketPtr socket; bool isClosed = socketAppender->closed; while(!isClosed) { try { Thread::sleep(socketAppender->reconnectionDelay); LogLog::debug(LogString(LOG4CXX_STR("Attempting connection to ")) + socketAppender->address->getHostName()); socket = new Socket(socketAppender->address, socketAppender->port); Pool p; socketAppender->setSocket(socket, p); LogLog::debug(LOG4CXX_STR("Connection established. Exiting connector thread.")); return NULL; } catch(ConnectException&) { LogLog::debug(LOG4CXX_STR("Remote host ") +socketAppender->address->getHostName() +LOG4CXX_STR(" refused connection.")); } catch(IOException& e) { LogString exmsg; log4cxx::helpers::Transcoder::decode(e.what(), exmsg); LogLog::debug(((LogString) LOG4CXX_STR("Could not connect to ")) + socketAppender->address->getHostName() + LOG4CXX_STR(". Exception is ") + exmsg); } isClosed = socketAppender->closed; } LogLog::debug(LOG4CXX_STR("Exiting Connector.run() method.")); return NULL; }
001-log4cxx
trunk/src/main/cpp/socketappenderskeleton.cpp
C++
asf20
6,239
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #if defined(_MSC_VER) #pragma warning ( disable: 4231 4251 4275 4786 ) #endif #include <log4cxx/logstring.h> #include <log4cxx/pattern/fulllocationpatternconverter.h> #include <log4cxx/spi/loggingevent.h> #include <log4cxx/spi/location/locationinfo.h> #include <log4cxx/helpers/stringhelper.h> using namespace log4cxx; using namespace log4cxx::pattern; using namespace log4cxx::spi; using namespace log4cxx::helpers; IMPLEMENT_LOG4CXX_OBJECT(FullLocationPatternConverter) FullLocationPatternConverter::FullLocationPatternConverter() : LoggingEventPatternConverter(LOG4CXX_STR("Full Location"), LOG4CXX_STR("fullLocation")) { } PatternConverterPtr FullLocationPatternConverter::newInstance( const std::vector<LogString>& /* options */) { static PatternConverterPtr instance(new FullLocationPatternConverter()); return instance; } void FullLocationPatternConverter::format( const LoggingEventPtr& event, LogString& toAppendTo, Pool& p) const { append(toAppendTo, event->getLocationInformation().getFileName()); toAppendTo.append(1, (logchar) 0x28 /* '(' */); StringHelper::toString( event->getLocationInformation().getLineNumber(), p, toAppendTo); toAppendTo.append(1, (logchar) 0x29 /* ')' */); }
001-log4cxx
trunk/src/main/cpp/fulllocationpatternconverter.cpp
C++
asf20
2,056
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <log4cxx/logstring.h> #include <log4cxx/level.h> #include <log4cxx/helpers/stringhelper.h> #include <log4cxx/helpers/transcoder.h> #if !defined(LOG4CXX) #define LOG4CXX 1 #endif #include <log4cxx/helpers/aprinitializer.h> using namespace log4cxx; using namespace log4cxx::helpers; IMPLEMENT_LOG4CXX_OBJECT_WITH_CUSTOM_CLASS(Level, LevelClass) LevelPtr Level::getOff() { static LevelPtr level(new Level(Level::OFF_INT, LOG4CXX_STR("OFF"), 0)); return level; } LevelPtr Level::getFatal() { static LevelPtr level(new Level(Level::FATAL_INT, LOG4CXX_STR("FATAL"), 0)); return level; } LevelPtr Level::getError() { static LevelPtr level(new Level(Level::ERROR_INT, LOG4CXX_STR("ERROR"), 3)); return level; } LevelPtr Level::getWarn() { static LevelPtr level(new Level(Level::WARN_INT, LOG4CXX_STR("WARN"), 4)); return level; } LevelPtr Level::getInfo() { static LevelPtr level(new Level(Level::INFO_INT, LOG4CXX_STR("INFO"), 6)); return level; } LevelPtr Level::getDebug() { static LevelPtr level(new Level(Level::DEBUG_INT, LOG4CXX_STR("DEBUG"), 7)); return level; } LevelPtr Level::getTrace() { static LevelPtr level(new Level(Level::TRACE_INT, LOG4CXX_STR("TRACE"), 7)); return level; } LevelPtr Level::getAll() { static LevelPtr level(new Level(Level::ALL_INT, LOG4CXX_STR("ALL"), 7)); return level; } Level::Level(int level1, const LogString& name1, int syslogEquivalent1) : level(level1), name(name1), syslogEquivalent(syslogEquivalent1) { APRInitializer::initialize(); } LevelPtr Level::toLevelLS(const LogString& sArg) { return toLevelLS(sArg, Level::getDebug()); } LogString Level::toString() const { return name; } LevelPtr Level::toLevel(int val) { return toLevel(val, Level::getDebug()); } LevelPtr Level::toLevel(int val, const LevelPtr& defaultLevel) { switch(val) { case ALL_INT: return getAll(); case DEBUG_INT: return getDebug(); case TRACE_INT: return getTrace(); case INFO_INT: return getInfo(); case WARN_INT: return getWarn(); case ERROR_INT: return getError(); case FATAL_INT: return getFatal(); case OFF_INT: return getOff(); default: return defaultLevel; } } LevelPtr Level::toLevel(const std::string& sArg) { return toLevel(sArg, Level::getDebug()); } LevelPtr Level::toLevel(const std::string& sArg, const LevelPtr& defaultLevel) { LOG4CXX_DECODE_CHAR(s, sArg); return toLevelLS(s, defaultLevel); } void Level::toString(std::string& dst) const { Transcoder::encode(name, dst); } #if LOG4CXX_WCHAR_T_API LevelPtr Level::toLevel(const std::wstring& sArg) { return toLevel(sArg, Level::getDebug()); } LevelPtr Level::toLevel(const std::wstring& sArg, const LevelPtr& defaultLevel) { LOG4CXX_DECODE_WCHAR(s, sArg); return toLevelLS(s, defaultLevel); } void Level::toString(std::wstring& dst) const { Transcoder::encode(name, dst); } #endif #if LOG4CXX_UNICHAR_API LevelPtr Level::toLevel(const std::basic_string<UniChar>& sArg) { return toLevel(sArg, Level::getDebug()); } LevelPtr Level::toLevel(const std::basic_string<UniChar>& sArg, const LevelPtr& defaultLevel) { LOG4CXX_DECODE_UNICHAR(s, sArg); return toLevelLS(s, defaultLevel); } void Level::toString(std::basic_string<UniChar>& dst) const { Transcoder::encode(name, dst); } #endif #if LOG4CXX_CFSTRING_API LevelPtr Level::toLevel(const CFStringRef& sArg) { return toLevel(sArg, Level::getDebug()); } LevelPtr Level::toLevel(const CFStringRef& sArg, const LevelPtr& defaultLevel) { LogString s; Transcoder::decode(sArg, s); return toLevelLS(s, defaultLevel); } void Level::toString(CFStringRef& dst) const { dst = Transcoder::encode(name); } #endif LevelPtr Level::toLevelLS(const LogString& sArg, const LevelPtr& defaultLevel) { const size_t len = sArg.length(); if (len == 4) { if (StringHelper::equalsIgnoreCase(sArg, LOG4CXX_STR("INFO"), LOG4CXX_STR("info"))) { return getInfo(); } if (StringHelper::equalsIgnoreCase(sArg, LOG4CXX_STR("WARN"), LOG4CXX_STR("warn"))) { return getWarn(); } } else { if (len == 5) { if (StringHelper::equalsIgnoreCase(sArg, LOG4CXX_STR("DEBUG"), LOG4CXX_STR("debug"))) { return getDebug(); } if (StringHelper::equalsIgnoreCase(sArg, LOG4CXX_STR("TRACE"), LOG4CXX_STR("trace"))) { return getTrace(); } if (StringHelper::equalsIgnoreCase(sArg, LOG4CXX_STR("ERROR"), LOG4CXX_STR("error"))) { return getError(); } if (StringHelper::equalsIgnoreCase(sArg, LOG4CXX_STR("FATAL"), LOG4CXX_STR("fatal"))) { return getFatal(); } } else { if (len == 3) { if (StringHelper::equalsIgnoreCase(sArg, LOG4CXX_STR("OFF"), LOG4CXX_STR("off"))) { return getOff(); } if (StringHelper::equalsIgnoreCase(sArg, LOG4CXX_STR("ALL"), LOG4CXX_STR("all"))) { return getAll(); } } } } return defaultLevel; } bool Level::equals(const LevelPtr& level1) const { return (this->level == level1->level); } bool Level::isGreaterOrEqual(const LevelPtr& level1) const { return this->level >= level1->level; }
001-log4cxx
trunk/src/main/cpp/level.cpp
C++
asf20
6,093
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #if defined(_MSC_VER) #pragma warning ( disable: 4231 4251 4275 4786 ) #endif #include <log4cxx/logstring.h> #include <log4cxx/spi/loggerfactory.h> #include <log4cxx/hierarchy.h> #include <log4cxx/defaultloggerfactory.h> #include <log4cxx/logger.h> #include <log4cxx/spi/hierarchyeventlistener.h> #include <log4cxx/level.h> #include <algorithm> #include <log4cxx/helpers/loglog.h> #include <log4cxx/appender.h> #include <log4cxx/helpers/synchronized.h> #include <log4cxx/logstring.h> #include <log4cxx/helpers/stringhelper.h> #if !defined(LOG4CXX) #define LOG4CXX 1 #endif #include <log4cxx/helpers/aprinitializer.h> #include <log4cxx/defaultconfigurator.h> #include <log4cxx/spi/rootlogger.h> #include <apr_atomic.h> #include "assert.h" using namespace log4cxx; using namespace log4cxx::spi; using namespace log4cxx::helpers; IMPLEMENT_LOG4CXX_OBJECT(Hierarchy) Hierarchy::Hierarchy() : pool(), mutex(pool), loggers(new LoggerMap()), provisionNodes(new ProvisionNodeMap()) { synchronized sync(mutex); root = new RootLogger(pool, Level::getDebug()); root->setHierarchy(this); defaultFactory = new DefaultLoggerFactory(); emittedNoAppenderWarning = false; configured = false; thresholdInt = Level::ALL_INT; threshold = Level::getAll(); emittedNoResourceBundleWarning = false; } Hierarchy::~Hierarchy() { delete loggers; delete provisionNodes; } void Hierarchy::addRef() const { ObjectImpl::addRef(); } void Hierarchy::releaseRef() const { ObjectImpl::releaseRef(); } void Hierarchy::addHierarchyEventListener(const spi::HierarchyEventListenerPtr& listener) { synchronized sync(mutex); if (std::find(listeners.begin(), listeners.end(), listener) != listeners.end()) { LogLog::warn(LOG4CXX_STR("Ignoring attempt to add an existent listener.")); } else { listeners.push_back(listener); } } void Hierarchy::clear() { synchronized sync(mutex); loggers->clear(); } void Hierarchy::emitNoAppenderWarning(const LoggerPtr& logger) { bool emitWarning = false; { synchronized sync(mutex); emitWarning = !emittedNoAppenderWarning; emittedNoAppenderWarning = true; } // No appender in hierarchy, warn user only once. if(emitWarning) { LogLog::warn(((LogString) LOG4CXX_STR("No appender could be found for logger (")) + logger->getName() + LOG4CXX_STR(").")); LogLog::warn(LOG4CXX_STR("Please initialize the log4cxx system properly.")); } } LoggerPtr Hierarchy::exists(const LogString& name) { synchronized sync(mutex); LoggerPtr logger; LoggerMap::iterator it = loggers->find(name); if (it != loggers->end()) { logger = it->second; } return logger; } void Hierarchy::setThreshold(const LevelPtr& l) { if (l != 0) { synchronized sync(mutex); thresholdInt = l->toInt(); threshold = l; if (thresholdInt != Level::ALL_INT) { setConfigured(true); } } } void Hierarchy::setThreshold(const LogString& levelStr) { LevelPtr l(Level::toLevelLS(levelStr, 0)); if(l != 0) { setThreshold(l); } else { LogLog::warn(((LogString) LOG4CXX_STR("No level could be found named \"")) + levelStr + LOG4CXX_STR("\".")); } } void Hierarchy::fireAddAppenderEvent(const LoggerPtr& logger, const AppenderPtr& appender) { setConfigured(true); HierarchyEventListenerList clonedList; { synchronized sync(mutex); clonedList = listeners; } HierarchyEventListenerList::iterator it, itEnd = clonedList.end(); HierarchyEventListenerPtr listener; for(it = clonedList.begin(); it != itEnd; it++) { listener = *it; listener->addAppenderEvent(logger, appender); } } void Hierarchy::fireRemoveAppenderEvent(const LoggerPtr& logger, const AppenderPtr& appender) { HierarchyEventListenerList clonedList; { synchronized sync(mutex); clonedList = listeners; } HierarchyEventListenerList::iterator it, itEnd = clonedList.end(); HierarchyEventListenerPtr listener; for(it = clonedList.begin(); it != itEnd; it++) { listener = *it; listener->removeAppenderEvent(logger, appender); } } const LevelPtr& Hierarchy::getThreshold() const { return threshold; } LoggerPtr Hierarchy::getLogger(const LogString& name) { return getLogger(name, defaultFactory); } LoggerPtr Hierarchy::getLogger(const LogString& name, const spi::LoggerFactoryPtr& factory) { synchronized sync(mutex); LoggerMap::iterator it = loggers->find(name); if (it != loggers->end()) { return it->second; } else { LoggerPtr logger(factory->makeNewLoggerInstance(pool, name)); logger->setHierarchy(this); loggers->insert(LoggerMap::value_type(name, logger)); ProvisionNodeMap::iterator it2 = provisionNodes->find(name); if (it2 != provisionNodes->end()) { updateChildren(it2->second, logger); provisionNodes->erase(it2); } updateParents(logger); return logger; } } LoggerList Hierarchy::getCurrentLoggers() const { synchronized sync(mutex); LoggerList v; LoggerMap::const_iterator it, itEnd = loggers->end(); for (it = loggers->begin(); it != itEnd; it++) { v.push_back(it->second); } return v; } LoggerPtr Hierarchy::getRootLogger() const { return root; } bool Hierarchy::isDisabled(int level) const { if(!configured) { synchronized sync(mutex); if (!configured) { DefaultConfigurator::configure( const_cast<Hierarchy*>(this)); } } return thresholdInt > level; } void Hierarchy::resetConfiguration() { synchronized sync(mutex); getRootLogger()->setLevel(Level::getDebug()); root->setResourceBundle(0); setThreshold(Level::getAll()); shutdown(); // nested locks are OK LoggerList loggers1 = getCurrentLoggers(); LoggerList::iterator it, itEnd = loggers1.end(); for (it = loggers1.begin(); it != itEnd; it++) { LoggerPtr& logger = *it; logger->setLevel(0); logger->setAdditivity(true); logger->setResourceBundle(0); } //rendererMap.clear(); } void Hierarchy::shutdown() { synchronized sync(mutex); setConfigured(false); LoggerPtr root1 = getRootLogger(); // begin by closing nested appenders root1->closeNestedAppenders(); LoggerList loggers1 = getCurrentLoggers(); LoggerList::iterator it, itEnd = loggers1.end(); for (it = loggers1.begin(); it != itEnd; it++) { LoggerPtr& logger = *it; logger->closeNestedAppenders(); } // then, remove all appenders root1->removeAllAppenders(); for (it = loggers1.begin(); it != itEnd; it++) { LoggerPtr& logger = *it; logger->removeAllAppenders(); } } void Hierarchy::updateParents(LoggerPtr logger) { synchronized sync(mutex); const LogString name(logger->getName()); int length = name.size(); bool parentFound = false; // if name = "w.x.y.z", loop thourgh "w.x.y", "w.x" and "w", but not "w.x.y.z" for(size_t i = name.find_last_of(0x2E /* '.' */, length-1); i != LogString::npos; i = name.find_last_of(0x2E /* '.' */, i-1)) { LogString substr = name.substr(0, i); LoggerMap::iterator it = loggers->find(substr); if(it != loggers->end()) { parentFound = true; logger->parent = it->second; break; // no need to update the ancestors of the closest ancestor } else { ProvisionNodeMap::iterator it2 = provisionNodes->find(substr); if (it2 != provisionNodes->end()) { it2->second.push_back(logger); } else { ProvisionNode node(1, logger); provisionNodes->insert( ProvisionNodeMap::value_type(substr, node)); } } } // If we could not find any existing parents, then link with root. if(!parentFound) { logger->parent = root; } } void Hierarchy::updateChildren(ProvisionNode& pn, LoggerPtr logger) { ProvisionNode::iterator it, itEnd = pn.end(); for(it = pn.begin(); it != itEnd; it++) { LoggerPtr& l = *it; // Unless this child already points to a correct (lower) parent, // make cat.parent point to l.parent and l.parent to cat. if(!StringHelper::startsWith(l->parent->name, logger->name)) { logger->parent = l->parent; l->parent = logger; } } } void Hierarchy::setConfigured(bool newValue) { synchronized sync(mutex); configured = newValue; } bool Hierarchy::isConfigured() { return configured; }
001-log4cxx
trunk/src/main/cpp/hierarchy.cpp
C++
asf20
10,880
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <log4cxx/logstring.h> #include <log4cxx/helpers/resourcebundle.h> #include <log4cxx/helpers/propertyresourcebundle.h> #include <log4cxx/helpers/loader.h> #include <log4cxx/helpers/pool.h> #include <log4cxx/helpers/transcoder.h> #include <log4cxx/helpers/locale.h> using namespace log4cxx; using namespace log4cxx::helpers; IMPLEMENT_LOG4CXX_OBJECT(ResourceBundle) ResourceBundlePtr ResourceBundle::getBundle(const LogString& baseName, const Locale& locale) { LogString bundleName; PropertyResourceBundlePtr resourceBundle, previous; std::vector<LogString> bundlesNames; if (!locale.getVariant().empty()) { bundlesNames.push_back(baseName + LOG4CXX_STR("_") + locale.getLanguage() + LOG4CXX_STR("_") + locale.getCountry() + LOG4CXX_STR("_") + locale.getVariant()); } if (!locale.getCountry().empty()) { bundlesNames.push_back(baseName + LOG4CXX_STR("_") + locale.getLanguage() + LOG4CXX_STR("_") + locale.getCountry()); } if (!locale.getLanguage().empty()) { bundlesNames.push_back(baseName + LOG4CXX_STR("_") + locale.getLanguage()); } bundlesNames.push_back(baseName); for (std::vector<LogString>::iterator it = bundlesNames.begin(); it != bundlesNames.end(); it++) { bundleName = *it; PropertyResourceBundlePtr current; // Try loading a class which implements ResourceBundle try { const Class& classObj = Loader::loadClass(bundleName); current = classObj.newInstance(); } catch(ClassNotFoundException&) { current = 0; } // No class found, then try to create a PropertyResourceBundle from a file if (current == 0) { InputStreamPtr bundleStream = Loader::getResourceAsStream( bundleName + LOG4CXX_STR(".properties")); if (bundleStream == 0) { continue; } try { current = new PropertyResourceBundle(bundleStream); } catch(Exception&) { throw; } } // Add the new resource bundle to the hierarchy if (resourceBundle == 0) { resourceBundle = current; previous = current; } else { previous->setParent(current); previous = current; } } // no resource bundle found at all, then throw exception if (resourceBundle == 0) { throw MissingResourceException( ((LogString) LOG4CXX_STR("Missing resource bundle ")) + baseName); } return resourceBundle; }
001-log4cxx
trunk/src/main/cpp/resourcebundle.cpp
C++
asf20
3,489
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <log4cxx/logstring.h> #include <log4cxx/helpers/exception.h> #include <string.h> #include <string> #include <log4cxx/helpers/stringhelper.h> #include <log4cxx/helpers/transcoder.h> #include <log4cxx/helpers/pool.h> using namespace log4cxx; using namespace log4cxx::helpers; Exception::Exception(const LogString& msg1) { std::string m; Transcoder::encode(msg1, m); size_t len = m.size(); if (len > MSG_SIZE) { len = MSG_SIZE; } #if defined(__STDC_LIB_EXT1__) || defined(__STDC_SECURE_LIB__) memcpy_s(msg, sizeof msg, m.data(), len); #else memcpy(msg, m.data(), len); #endif msg[len] = 0; } Exception::Exception(const char* m) { #if defined(__STDC_LIB_EXT1__) || defined(__STDC_SECURE_LIB__) strncpy_s(msg, sizeof msg, m, MSG_SIZE); #else strncpy(msg, m, MSG_SIZE); #endif msg[MSG_SIZE] = 0; } Exception::Exception(const Exception& src) : std::exception() { #if defined(__STDC_LIB_EXT1__) || defined(__STDC_SECURE_LIB__) strcpy_s(msg, sizeof msg, src.msg); #else strcpy(msg, src.msg); #endif } Exception& Exception::operator=(const Exception& src) { #if defined(__STDC_LIB_EXT1__) || defined(__STDC_SECURE_LIB__) strcpy_s(msg, sizeof msg, src.msg); #else strcpy(msg, src.msg); #endif return *this; } const char* Exception::what() const throw() { return msg; } RuntimeException::RuntimeException(log4cxx_status_t stat) : Exception(formatMessage(stat)) { } RuntimeException::RuntimeException(const LogString& msg1) : Exception(msg1) { } RuntimeException::RuntimeException(const RuntimeException& src) : Exception(src) { } RuntimeException& RuntimeException::operator=(const RuntimeException& src) { Exception::operator=(src); return *this; } LogString RuntimeException::formatMessage(log4cxx_status_t stat) { LogString s(LOG4CXX_STR("RuntimeException: return code = ")); Pool p; StringHelper::toString(stat, p, s); return s; } NullPointerException::NullPointerException(const LogString& msg1) : RuntimeException(msg1) { } NullPointerException::NullPointerException(const NullPointerException& src) : RuntimeException(src) { } NullPointerException& NullPointerException::operator=(const NullPointerException& src) { RuntimeException::operator=(src); return *this; } IllegalArgumentException::IllegalArgumentException(const LogString& msg1) : RuntimeException(msg1) { } IllegalArgumentException::IllegalArgumentException(const IllegalArgumentException& src) : RuntimeException(src) { } IllegalArgumentException& IllegalArgumentException::operator=(const IllegalArgumentException& src) { RuntimeException::operator=(src); return *this; } IOException::IOException() : Exception(LOG4CXX_STR("IO exception")) { } IOException::IOException(log4cxx_status_t stat) : Exception(formatMessage(stat)) { } IOException::IOException(const LogString& msg1) : Exception(msg1) { } IOException::IOException(const IOException& src) : Exception(src) { } IOException& IOException::operator=(const IOException& src) { Exception::operator=(src); return *this; } LogString IOException::formatMessage(log4cxx_status_t stat) { LogString s(LOG4CXX_STR("IO Exception : status code = ")); Pool p; StringHelper::toString(stat, p, s); return s; } MissingResourceException::MissingResourceException(const LogString& key) : Exception(formatMessage(key)) { } MissingResourceException::MissingResourceException(const MissingResourceException& src) : Exception(src) { } MissingResourceException& MissingResourceException::operator=(const MissingResourceException& src) { Exception::operator=(src); return *this; } LogString MissingResourceException::formatMessage(const LogString& key) { LogString s(LOG4CXX_STR("MissingResourceException: resource key = \"")); s.append(key); s.append(LOG4CXX_STR("\".")); return s; } PoolException::PoolException(log4cxx_status_t stat) : Exception(formatMessage(stat)) { } PoolException::PoolException(const PoolException &src) : Exception(src) { } PoolException& PoolException::operator=(const PoolException& src) { Exception::operator=(src); return *this; } LogString PoolException::formatMessage(log4cxx_status_t) { return LOG4CXX_STR("Pool exception"); } TranscoderException::TranscoderException(log4cxx_status_t stat) : Exception(formatMessage(stat)) { } TranscoderException::TranscoderException(const TranscoderException &src) : Exception(src) { } TranscoderException& TranscoderException::operator=(const TranscoderException& src) { Exception::operator=(src); return *this; } LogString TranscoderException::formatMessage(log4cxx_status_t) { return LOG4CXX_STR("Transcoder exception"); } MutexException::MutexException(log4cxx_status_t stat) : Exception(formatMessage(stat)) { } MutexException::MutexException(const MutexException &src) : Exception(src) { } MutexException& MutexException::operator=(const MutexException& src) { Exception::operator=(src); return *this; } LogString MutexException::formatMessage(log4cxx_status_t stat) { LogString s(LOG4CXX_STR("Mutex exception: stat = ")); Pool p; StringHelper::toString(stat, p, s); return s; } InterruptedException::InterruptedException() : Exception(LOG4CXX_STR("Thread was interrupted")) { } InterruptedException::InterruptedException(log4cxx_status_t stat) : Exception(formatMessage(stat)) { } InterruptedException::InterruptedException(const InterruptedException &src) : Exception(src) { } InterruptedException& InterruptedException::operator=(const InterruptedException& src) { Exception::operator=(src); return *this; } LogString InterruptedException::formatMessage(log4cxx_status_t stat) { LogString s(LOG4CXX_STR("InterruptedException: stat = ")); Pool p; StringHelper::toString(stat, p, s); return s; } ThreadException::ThreadException(log4cxx_status_t stat) : Exception(formatMessage(stat)) { } ThreadException::ThreadException(const LogString& msg) : Exception(msg) { } ThreadException::ThreadException(const ThreadException &src) : Exception(src) { } ThreadException& ThreadException::operator=(const ThreadException& src) { Exception::operator=(src); return *this; } LogString ThreadException::formatMessage(log4cxx_status_t stat) { LogString s(LOG4CXX_STR("Thread exception: stat = ")); Pool p; StringHelper::toString(stat, p, s); return s; } IllegalMonitorStateException::IllegalMonitorStateException(const LogString& msg1) : Exception(msg1) { } IllegalMonitorStateException::IllegalMonitorStateException(const IllegalMonitorStateException& src) : Exception(src) { } IllegalMonitorStateException& IllegalMonitorStateException::operator=(const IllegalMonitorStateException& src) { Exception::operator=(src); return *this; } InstantiationException::InstantiationException(const LogString& msg1) : Exception(msg1) { } InstantiationException::InstantiationException(const InstantiationException& src) : Exception(src) { } InstantiationException& InstantiationException::operator=(const InstantiationException& src) { Exception::operator=(src); return *this; } ClassNotFoundException::ClassNotFoundException(const LogString& className) : Exception(formatMessage(className)) { } ClassNotFoundException::ClassNotFoundException(const ClassNotFoundException& src) : Exception(src) { } ClassNotFoundException& ClassNotFoundException::operator=(const ClassNotFoundException& src) { Exception::operator=(src); return *this; } LogString ClassNotFoundException::formatMessage(const LogString& className) { LogString s(LOG4CXX_STR("Class not found: ")); s.append(className); return s; } NoSuchElementException::NoSuchElementException() : Exception(LOG4CXX_STR("No such element")) { } NoSuchElementException::NoSuchElementException(const NoSuchElementException& src) : Exception(src) { } NoSuchElementException& NoSuchElementException::operator=(const NoSuchElementException& src) { Exception::operator=(src); return *this; } IllegalStateException::IllegalStateException() : Exception(LOG4CXX_STR("Illegal state")) { } IllegalStateException::IllegalStateException(const IllegalStateException& src) : Exception(src) { } IllegalStateException& IllegalStateException::operator=(const IllegalStateException& src) { Exception::operator=(src); return *this; } SocketException::SocketException(const LogString& msg) : IOException(msg) { } SocketException::SocketException(log4cxx_status_t status) : IOException(status) { } SocketException::SocketException(const SocketException& src) : IOException(src) { } SocketException& SocketException::operator=(const SocketException& src) { IOException::operator=(src); return *this; } ConnectException::ConnectException(log4cxx_status_t status) : SocketException(status) { } ConnectException::ConnectException(const ConnectException& src) : SocketException(src) { } ConnectException& ConnectException::operator=(const ConnectException& src) { SocketException::operator=(src); return *this; } ClosedChannelException::ClosedChannelException() : SocketException(LOG4CXX_STR("Attempt to write to closed socket")) { } ClosedChannelException::ClosedChannelException(const ClosedChannelException& src) : SocketException(src) { } ClosedChannelException& ClosedChannelException::operator=(const ClosedChannelException& src) { SocketException::operator=(src); return *this; } BindException::BindException(log4cxx_status_t status) : SocketException(status) { } BindException::BindException(const BindException& src) : SocketException(src) { } BindException& BindException::operator=(const BindException& src) { SocketException::operator=(src); return *this; } InterruptedIOException::InterruptedIOException(const LogString& msg) : IOException(msg) { } InterruptedIOException::InterruptedIOException(const InterruptedIOException& src) : IOException(src) { } InterruptedIOException& InterruptedIOException::operator=(const InterruptedIOException& src) { IOException::operator=(src); return *this; } SocketTimeoutException::SocketTimeoutException() : InterruptedIOException(LOG4CXX_STR("SocketTimeoutException")) { } SocketTimeoutException::SocketTimeoutException(const SocketTimeoutException& src) : InterruptedIOException(src) { } SocketTimeoutException& SocketTimeoutException::operator=(const SocketTimeoutException& src) { InterruptedIOException::operator=(src); return *this; }
001-log4cxx
trunk/src/main/cpp/exception.cpp
C++
asf20
11,625
# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # SUBDIRS = cpp include
001-log4cxx
trunk/src/main/Makefile.am
Makefile
asf20
806
<!-- Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xsl:version="1.0"> <xsl:output method="xml" indent="yes"/> <xsl:apply-templates select="/"/> <xsl:template match="/"> <xsl:comment> Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. </xsl:comment> <document> <properties> <title>Apache log4cxx</title> </properties> <body> <release version="0.10.0" date="2008-02-29" description="First Apache release"> <xsl:apply-templates select='/rss/channel/item'> <xsl:sort select="substring-after(key, '-')" data-type="number"/> </xsl:apply-templates> </release> <release version="0.9.7" date="2004-05-10"> <action type="fix">Fixed examples source code in the "Short introduction to log4cxx".</action> <action type="fix">Fixed, in the renaming algorithm of RollingFileAppender and DailyRollingFileAppender, a problem specific to Unicode.</action> <action type="fix">Fixed conflict with Windows macros "min" and "max", by renaming StrictMath::min and StrictMath::max to StrictMath::minimum and StrictMath::maximum.</action> <action type="add">Port to HPUX 11.0.</action> <action type="fix">Fixed segmentation fault in PropertyConfigurator.</action> <action type="add">Port to Solaris.</action> <action type="fix">Fixed MutexException thrown while destroying RollingFileAppender.</action> <action type="fix">Logging macros can be used without explicity declaring the use of log4cxx namespace.</action> <action type="fix">Fixed static library unresolved externals for msvc 6 and 7.1</action> </release> <release version="0.9.6" date="2004-04-11"> <action>Timezone management has been optimized through the class TimeZone</action> <action>Inter-thread synchronization and reference counting has been optimized</action> <action>Reference counting now uses gcc atomic functions (bug 929078)</action> <action>Use of StringBuffer has been optimized.</action> <action>Support of localisation throug resourceBundles</action> <action>SyslogAppender now uses the system function 'syslog' to log on the local host. (only for POSIX systems)</action> <action>Added TimeZone configuration to PatternLayout (bug 912563)</action> <action>Support of the DailyRollingFileAppender (feature request 842765)</action> </release> <release version="0.9.5" date="2004-02-04"> <action>Port of log4j Jnuit tests with Cppunit and Boost Regex.</action> <action>Added explicit exports for MSDEV 6 and MSDEV 7 (no further need of .def files)</action> <action>Custom levels can be configured through the DOMConfigurator and PropertyConfigurator classes (Level inherites from Object)</action> <action>Added a reference counter to LoggingEvent to avoid useless copies (LoggingEvent inherites from Object)</action> <action>The file log4j.xml as well as the file log4j.properties are now search for, in log4cxx initialization.</action> <action>The root logger can be assigned the "OFF" level.</action> <action>Added MSVC6 project missing files mutext.cpp and condition.cpp (bug 847397)</action> <action>condition.cpp now compiles with MSVC6 (bug 847417)</action> <action>fixed pure virtual function call in PropertyConfigurator::configureAndWatch (bug 848521)</action> <action>XMLAppender now displays correct timestamp with MSVC 6 (bug 852836)</action> <action>SRLPORT 4.6 support.</action> <action>Fixed an infinite loop in class Properties.</action> <action>Fixed compilations problems with unicode.</action> <action>Fixed SocketAppender bug concerning MDC and NDC.</action> </release> <release version="0.9.4" date="2003-10-25"> <action>StringBuffer has been optimized.</action> <action>Fixed miscellaneous threading problems.</action> <action>Added TimeZone support in PatternLayout (bug 796894)</action> <action>Fixed threading configuration problems (bug 809125)</action> <action>Fixed miscellaneous MSVC and cygwin compilation problems.</action> </release> <release version="0.9.3" date="2003-09-19"> <action>Changed tstring to log4cxx::String and tostringstream to log4cxx::StringBuffer. </action> <action>Fixed MSVC 2003 compilation erros and warnings. </action> <action>Added helpers for NDC and MDC. </action> <action>Added TimeZone support in TTCCLayout. </action> <action>Fixed compilation problems with logger macros (LOG4CXX_...) </action> <action>Fixed milliseconds formatting problem with MSVC 6.0 and 2003 </action> <action>Fixed AsyncAppender crash </action> <action>Added new tests </action> <action>Added benchmarks </action> </release> <release version="0.9.2" date="2003-08-10"> <action>Fixed FreeBSD compilation problem with pthread mutex (class CriticalSection). </action> <action>Fixed milliseconds formatting problem (class DateFormat). </action> <action>Long events (&gt; 1024 chars) are now supported in the class XMLSocketAppender. </action> <action>Carriage returns have been normalized in the class XMLLayout. </action> </release> <release version="0.9.1" date="2003-08-06"> <action>Fixed deadlock problems in classes Logger and AsyncAppender. </action> <action>Fixed MSVC 6.0 compilation problems. </action> <action>Added MSVC 6.0 static libraty project. </action> <action>Default configuration for the SMTP options is "no". </action> </release> <release version="0.9.0" date="2003-08-06"> <action>Added ODBCAppender (matching log4j JDBCAppender) </action> <action>Added SyslogAppender </action> <action>Added SMTPAppender (only for Linux/FreeBSD) </action> <action>Added BasicConfigurator </action> <action>Added a FileWatchDog in PropertyConfigurator and DOMConfigurator </action> <action>Possibility to load a custom LoggerFactory through the DOMConfigurator </action> <action>Changed time precision from seconds to milliseconds </action> <action>Added MSVC 6.0 'Unicode Debug' and 'Unicode Release' targets </action> <action>Added Java like System class. </action> </release> <release version="0.1.1" date="2003-07-09"> <action>Fixed MSVC 6.0 compilation problems concerning the 'Release' target </action> <action>Added MSVC 6.0 tests projects </action> </release> <release version="0.1.0" date="2003-07-08"> <action>FreeBSD Autotools/Compilation support </action> <action>Fixed TelnetAppender crash when a socket bind exception occured. </action> <action>Added log4j DTD support to XMLLayout and DOMConfigurator </action> <action>Can now send events in XML format over TCP (class XMLSocketAppender) for the log4j Chainsaw UI </action> <action>Now compiles with 'configure --enable-unicode' (UTF16 Unicode support) </action> <action>Added Java like Properties class. It's a helper for the PropertyConfigurator </action> <action>Added Java like objects with dynamic cast and instanciation. Custom objects can be configured through the DOMConfigurator and PropertyConfigurator classes </action> <action>Port of the PropertyConfigurator class </action> <action>Port of the "Map Diagnostic Context" (MDC) class </action> <action>Added 13 tests (try make check) </action> </release> <release version="0.0.1" date="2003-05-31"> <action type="add">Loggers, Hierarchy, Filters, Appenders, Layouts, NDC </action> <action type="add">Appenders: AsyncAppender, ConsoleAppender, FileAppender, NTEventLogAppender, RollingFileAppender, SocketAppender, SocketHubAappender, TelnetAppender </action> <action type="add">Layouts: HTMLLayout, PatternLayout, SimpleLayout, TTCCLayout, XMLLayout </action> <action type="add">Filters: DenyAllFilter, LevelMatchFilter, LevelRangeFilter, StringMatchFilter </action> <action type="add">Configurators: DOMConfigurator </action> </release> </body> </document> </xsl:template> <xsl:template match="item"> <action issue="{key}"><xsl:value-of select="summary"/></action> </xsl:template> </xsl:transform>
001-log4cxx
trunk/src/changes/changes.xslt
XSLT
asf20
9,232
# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. #
001-log4cxx
trunk/src/changes/Makefile.am
Makefile
asf20
784
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <stdlib.h> #include <log4cxx/stream.h> #include <log4cxx/basicconfigurator.h> #include <log4cxx/helpers/exception.h> #include <log4cxx/ndc.h> #include <locale.h> using namespace log4cxx; using namespace log4cxx::helpers; int main() { setlocale(LC_ALL, ""); int result = EXIT_SUCCESS; try { BasicConfigurator::configure(); LoggerPtr rootLogger = Logger::getRootLogger(); NDC::push("trivial context"); log4cxx::logstream logstream(rootLogger, Level::getDebug()); logstream << "debug message " << 1 << LOG4CXX_ENDMSG; logstream.setLevel(Level::getInfo()); logstream << "info message" << LOG4CXX_ENDMSG; logstream << Level::getWarn() << "warn message" << LOG4CXX_ENDMSG; logstream << Level::getError() << "error message" << LOG4CXX_ENDMSG; logstream << Level::getFatal() << "fatal message" << LOG4CXX_ENDMSG; NDC::pop(); } catch(std::exception&) { result = EXIT_FAILURE; } return result; }
001-log4cxx
trunk/src/examples/cpp/stream.cpp
C++
asf20
1,951
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <stdlib.h> #include <log4cxx/logger.h> #include <log4cxx/consoleappender.h> #include <log4cxx/simplelayout.h> #include <log4cxx/logmanager.h> #include <iostream> #include <locale.h> using namespace log4cxx; using namespace log4cxx::helpers; /** * Configures console appender. * @param err if true, use stderr, otherwise stdout. */ static void configure(bool err) { log4cxx::ConsoleAppenderPtr appender(new log4cxx::ConsoleAppender()); if (err) { appender->setTarget(LOG4CXX_STR("System.err")); } log4cxx::LayoutPtr layout(new log4cxx::SimpleLayout()); appender->setLayout(layout); log4cxx::helpers::Pool pool; appender->activateOptions(pool); log4cxx::Logger::getRootLogger()->addAppender(appender); LogManager::getLoggerRepository()->setConfigured(true); } /** * Program to test compatibility of C RTL, C++ STL and log4cxx output to standard * output and error streams. * * See bug LOGCXX_126. * * */ int main(int argc, char** argv) { setlocale(LC_ALL, ""); if (argc <= 1) { puts("Console test program\nUsage: console [-err] [ puts | putws | cout | wcout | configure | log | wide | byte ]*\n"); } bool configured = false; bool err = false; for (int i = 1; i < argc; i++) { if (strcmp("-err", argv[i]) == 0) { err = true; } else if (strcmp("puts", argv[i]) == 0) { fputs("Hello, fputs\n", err ? stderr : stdout); #if LOG4CXX_WCHAR_T_API } else if (strcmp("putws", argv[i]) == 0) { fputws(L"Hello, fputws\n", err ? stderr : stdout); #endif } else if (strcmp("cout", argv[i]) == 0) { if (err) { std::cerr << "Hello, cout" << std::endl; } else { std::cout << "Hello, cout" << std::endl; } } else if (strcmp("wcout", argv[i]) == 0) { if (err) { #if LOG4CXX_HAS_STD_WCOUT std::wcerr << L"Hello, wcout" << std::endl; #else std::cerr << "Log4cxx has not wcout" << std::endl; #endif } else { #if LOG4CXX_HAS_STD_WCOUT std::wcout << L"Hello, wcout" << std::endl; #else std::cout << "Log4cxx has not wcout" << std::endl; #endif } } else if (strcmp("configure", argv[i]) == 0) { configure(err); configured = true; } else if (strcmp("log", argv[i]) == 0) { if (!configured) { configure(err); configured = true; } log4cxx::Logger::getRootLogger()->info("Hello, log4cxx"); #if LOG4CXX_WCHAR_T_API } else if (strcmp("wide", argv[i]) == 0) { fwide(err ? stderr : stdout, 1); } else if (strcmp("byte", argv[i]) == 0) { fwide(err ? stderr : stdout, -1); #endif } else { fputs("Unrecognized option: ", stderr); fputs(argv[i], stderr); fputs("\n", stderr); fflush(stderr); } } return 0; }
001-log4cxx
trunk/src/examples/cpp/console.cpp
C++
asf20
3,928
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <log4cxx/logstring.h> #include <stdlib.h> #include <log4cxx/logger.h> #include <log4cxx/basicconfigurator.h> #include <log4cxx/helpers/exception.h> #include <log4cxx/ndc.h> #include <locale.h> using namespace log4cxx; using namespace log4cxx::helpers; int main() { setlocale(LC_ALL, ""); int result = EXIT_SUCCESS; try { BasicConfigurator::configure(); LoggerPtr rootLogger = Logger::getRootLogger(); NDC::push("trivial context"); LOG4CXX_DEBUG(rootLogger, "debug message"); LOG4CXX_INFO(rootLogger, "info message"); LOG4CXX_WARN(rootLogger, "warn message"); LOG4CXX_ERROR(rootLogger, "error message"); LOG4CXX_FATAL(rootLogger, "fatal message"); NDC::pop(); } catch(std::exception&) { result = EXIT_FAILURE; } return result; }
001-log4cxx
trunk/src/examples/cpp/trivial.cpp
C++
asf20
1,758
# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # noinst_PROGRAMS = trivial delayedloop stream console INCLUDES = -I$(top_srcdir)/src/main/include -I$(top_builddir)/src/main/include trivial_SOURCES = trivial.cpp trivial_LDADD = $(top_builddir)/src/main/cpp/liblog4cxx.la delayedloop_SOURCES = delayedloop.cpp delayedloop_LDADD = $(top_builddir)/src/main/cpp/liblog4cxx.la stream_SOURCES = stream.cpp stream_LDADD = $(top_builddir)/src/main/cpp/liblog4cxx.la console_SOURCES = console.cpp console_LDADD = $(top_builddir)/src/main/cpp/liblog4cxx.la
001-log4cxx
trunk/src/examples/cpp/Makefile.am
Makefile
asf20
1,287
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <log4cxx/logger.h> #include <log4cxx/xml/domconfigurator.h> #include <log4cxx/propertyconfigurator.h> #include <apr_general.h> #include <apr_time.h> #include <iostream> #include <log4cxx/stream.h> #include <exception> #include <stdlib.h> using namespace log4cxx; using namespace log4cxx::helpers; /** This test program sits in a loop and logs things. Its logging is configured by a configuration file. Changes to this configuration file are monitored and when a change occurs, the config file is re-read. */ class DelayedLoop { static LoggerPtr logger; public: static void main(int argc, const char * const argv[]) { if(argc == 2) { init(argv[1]); } else { usage(argv[0], "Wrong number of arguments."); } test(); } static void usage(const char * programName, const char * msg) { std::cout << msg << std::endl; std::cout << "Usage: " << programName << " configFile" << std::endl; exit(1); } static void init(const std::string& configFile) { if(configFile.length() > 4 && configFile.substr(configFile.length() - 4) == ".xml") { #if APR_HAS_THREADS xml::DOMConfigurator::configureAndWatch(configFile, 3000); #else xml::DOMConfigurator::configure(configFile); #endif } else { #if APR_HAS_THREADS PropertyConfigurator::configureAndWatch(configFile, 3000); #else PropertyConfigurator::configure(configFile); #endif } } static void test() { int i = 0; while(true) { LOG4CXX_DEBUG(logger, "MSG " << i++); try { apr_sleep(1000000); } catch(std::exception& e) { } } } }; LoggerPtr DelayedLoop::logger = Logger::getLogger("DelayedLoop"); int main(int argc, const char * const argv[]) { apr_app_initialize(&argc, &argv, NULL); int result = EXIT_SUCCESS; try { DelayedLoop::main(argc, argv); } catch(std::exception&) { result = EXIT_FAILURE; } apr_terminate(); return result; }
001-log4cxx
trunk/src/examples/cpp/delayedloop.cpp
C++
asf20
3,444
# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # SUBDIRS = cpp
001-log4cxx
trunk/src/examples/Makefile.am
Makefile
asf20
798
/* Copyright 2000-2005 The Apache Software Foundation or its licensors, as * applicable. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * apr_uri.c: URI related utility things * */ #include <stdlib.h> #include "apu.h" #include "apr.h" #include "apr_general.h" #include "apr_strings.h" #define APR_WANT_STRFUNC #include "apr_want.h" #include "apr_uri.h" typedef struct schemes_t schemes_t; /** Structure to store various schemes and their default ports */ struct schemes_t { /** The name of the scheme */ const char *name; /** The default port for the scheme */ apr_port_t default_port; }; /* Some WWW schemes and their default ports; this is basically /etc/services */ /* This will become global when the protocol abstraction comes */ /* As the schemes are searched by a linear search, */ /* they are sorted by their expected frequency */ static schemes_t schemes[] = { {"http", APR_URI_HTTP_DEFAULT_PORT}, {"ftp", APR_URI_FTP_DEFAULT_PORT}, {"https", APR_URI_HTTPS_DEFAULT_PORT}, {"gopher", APR_URI_GOPHER_DEFAULT_PORT}, {"ldap", APR_URI_LDAP_DEFAULT_PORT}, {"nntp", APR_URI_NNTP_DEFAULT_PORT}, {"snews", APR_URI_SNEWS_DEFAULT_PORT}, {"imap", APR_URI_IMAP_DEFAULT_PORT}, {"pop", APR_URI_POP_DEFAULT_PORT}, {"sip", APR_URI_SIP_DEFAULT_PORT}, {"rtsp", APR_URI_RTSP_DEFAULT_PORT}, {"wais", APR_URI_WAIS_DEFAULT_PORT}, {"z39.50r", APR_URI_WAIS_DEFAULT_PORT}, {"z39.50s", APR_URI_WAIS_DEFAULT_PORT}, {"prospero", APR_URI_PROSPERO_DEFAULT_PORT}, {"nfs", APR_URI_NFS_DEFAULT_PORT}, {"tip", APR_URI_TIP_DEFAULT_PORT}, {"acap", APR_URI_ACAP_DEFAULT_PORT}, {"telnet", APR_URI_TELNET_DEFAULT_PORT}, {"ssh", APR_URI_SSH_DEFAULT_PORT}, { NULL, 0xFFFF } /* unknown port */ }; APU_DECLARE(apr_port_t) apr_uri_port_of_scheme(const char *scheme_str) { schemes_t *scheme; if (scheme_str) { for (scheme = schemes; scheme->name != NULL; ++scheme) { if (strcasecmp(scheme_str, scheme->name) == 0) { return scheme->default_port; } } } return 0; } /* Unparse a apr_uri_t structure to an URI string. * Optionally suppress the password for security reasons. */ APU_DECLARE(char *) apr_uri_unparse(apr_pool_t *p, const apr_uri_t *uptr, unsigned flags) { char *ret = ""; /* If suppressing the site part, omit both user name & scheme://hostname */ if (!(flags & APR_URI_UNP_OMITSITEPART)) { /* Construct a "user:password@" string, honoring the passed * APR_URI_UNP_ flags: */ if (uptr->user || uptr->password) { ret = apr_pstrcat(p, (uptr->user && !(flags & APR_URI_UNP_OMITUSER)) ? uptr->user : "", (uptr->password && !(flags & APR_URI_UNP_OMITPASSWORD)) ? ":" : "", (uptr->password && !(flags & APR_URI_UNP_OMITPASSWORD)) ? ((flags & APR_URI_UNP_REVEALPASSWORD) ? uptr->password : "XXXXXXXX") : "", ((uptr->user && !(flags & APR_URI_UNP_OMITUSER)) || (uptr->password && !(flags & APR_URI_UNP_OMITPASSWORD))) ? "@" : "", NULL); } /* Construct scheme://site string */ if (uptr->hostname) { int is_default_port; const char *lbrk = "", *rbrk = ""; if (strchr(uptr->hostname, ':')) { /* v6 literal */ lbrk = "["; rbrk = "]"; } is_default_port = (uptr->port_str == NULL || uptr->port == 0 || uptr->port == apr_uri_port_of_scheme(uptr->scheme)); if (uptr->scheme) { ret = apr_pstrcat(p, uptr->scheme, "://", ret, lbrk, uptr->hostname, rbrk, is_default_port ? "" : ":", is_default_port ? "" : uptr->port_str, NULL); } else { /* A violation of RFC2396, but it is clear from section 3.2 * that the : belongs above to the scheme, while // belongs * to the authority, so include the authority prefix while * omitting the "scheme:" that the user neglected to pass us. */ ret = apr_pstrcat(p, "//", ret, lbrk, uptr->hostname, rbrk, is_default_port ? "" : ":", is_default_port ? "" : uptr->port_str, NULL); } } } /* Should we suppress all path info? */ if (!(flags & APR_URI_UNP_OMITPATHINFO)) { /* Append path, query and fragment strings: */ ret = apr_pstrcat(p, ret, (uptr->path) ? uptr->path : "", (uptr->query && !(flags & APR_URI_UNP_OMITQUERY)) ? "?" : "", (uptr->query && !(flags & APR_URI_UNP_OMITQUERY)) ? uptr->query : "", (uptr->fragment && !(flags & APR_URI_UNP_OMITQUERY)) ? "#" : NULL, (uptr->fragment && !(flags & APR_URI_UNP_OMITQUERY)) ? uptr->fragment : NULL, NULL); } return ret; } /* Here is the hand-optimized parse_uri_components(). There are some wild * tricks we could pull in assembly language that we don't pull here... like we * can do word-at-time scans for delimiter characters using the same technique * that fast memchr()s use. But that would be way non-portable. -djg */ /* We have a apr_table_t that we can index by character and it tells us if the * character is one of the interesting delimiters. Note that we even get * compares for NUL for free -- it's just another delimiter. */ #define T_COLON 0x01 /* ':' */ #define T_SLASH 0x02 /* '/' */ #define T_QUESTION 0x04 /* '?' */ #define T_HASH 0x08 /* '#' */ #define T_NUL 0x80 /* '\0' */ #if APR_CHARSET_EBCDIC /* Delimiter table for the EBCDIC character set */ static const unsigned char uri_delims[256] = { T_NUL,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, 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,T_SLASH,0,0,0,0,0,0,0,0,0,0,0,0,0,T_QUESTION, 0,0,0,0,0,0,0,0,0,0,T_COLON,T_HASH,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,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,0,0,0,0,0,0 }; #else /* Delimiter table for the ASCII character set */ static const unsigned char uri_delims[256] = { T_NUL,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,T_HASH,0,0,0,0,0,0,0,0,0,0,0,T_SLASH, 0,0,0,0,0,0,0,0,0,0,T_COLON,0,0,0,0,T_QUESTION, 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,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,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,0,0,0 }; #endif /* it works like this: if (uri_delims[ch] & NOTEND_foobar) { then we're not at a delimiter for foobar } */ /* Note that we optimize the scheme scanning here, we cheat and let the * compiler know that it doesn't have to do the & masking. */ #define NOTEND_SCHEME (0xff) #define NOTEND_HOSTINFO (T_SLASH | T_QUESTION | T_HASH | T_NUL) #define NOTEND_PATH (T_QUESTION | T_HASH | T_NUL) /* parse_uri_components(): * Parse a given URI, fill in all supplied fields of a uri_components * structure. This eliminates the necessity of extracting host, port, * path, query info repeatedly in the modules. * Side effects: * - fills in fields of uri_components *uptr * - none on any of the r->* fields */ APU_DECLARE(apr_status_t) apr_uri_parse(apr_pool_t *p, const char *uri, apr_uri_t *uptr) { const char *s; const char *s1; const char *hostinfo; char *endstr; int port; int v6_offset1 = 0, v6_offset2 = 0; /* Initialize the structure. parse_uri() and parse_uri_components() * can be called more than once per request. */ memset (uptr, '\0', sizeof(*uptr)); uptr->is_initialized = 1; /* We assume the processor has a branch predictor like most -- * it assumes forward branches are untaken and backwards are taken. That's * the reason for the gotos. -djg */ if (uri[0] == '/') { /* RFC2396 #4.3 says that two leading slashes mean we have an * authority component, not a path! Fixing this looks scary * with the gotos here. But if the existing logic is valid, * then presumably a goto pointing to deal_with_authority works. * * RFC2396 describes this as resolving an ambiguity. In the * case of three or more slashes there would seem to be no * ambiguity, so it is a path after all. */ if (uri[1] == '/' && uri[2] != '/') { s = uri + 2 ; goto deal_with_authority ; } deal_with_path: /* we expect uri to point to first character of path ... remember * that the path could be empty -- http://foobar?query for example */ s = uri; while ((uri_delims[*(unsigned char *)s] & NOTEND_PATH) == 0) { ++s; } if (s != uri) { uptr->path = apr_pstrmemdup(p, uri, s - uri); } if (*s == 0) { return APR_SUCCESS; } if (*s == '?') { ++s; s1 = strchr(s, '#'); if (s1) { uptr->fragment = apr_pstrdup(p, s1 + 1); uptr->query = apr_pstrmemdup(p, s, s1 - s); } else { uptr->query = apr_pstrdup(p, s); } return APR_SUCCESS; } /* otherwise it's a fragment */ uptr->fragment = apr_pstrdup(p, s + 1); return APR_SUCCESS; } /* find the scheme: */ s = uri; while ((uri_delims[*(unsigned char *)s] & NOTEND_SCHEME) == 0) { ++s; } /* scheme must be non-empty and followed by :// */ if (s == uri || s[0] != ':' || s[1] != '/' || s[2] != '/') { goto deal_with_path; /* backwards predicted taken! */ } uptr->scheme = apr_pstrmemdup(p, uri, s - uri); s += 3; deal_with_authority: hostinfo = s; while ((uri_delims[*(unsigned char *)s] & NOTEND_HOSTINFO) == 0) { ++s; } uri = s; /* whatever follows hostinfo is start of uri */ uptr->hostinfo = apr_pstrmemdup(p, hostinfo, uri - hostinfo); /* If there's a username:password@host:port, the @ we want is the last @... * too bad there's no memrchr()... For the C purists, note that hostinfo * is definately not the first character of the original uri so therefore * &hostinfo[-1] < &hostinfo[0] ... and this loop is valid C. */ do { --s; } while (s >= hostinfo && *s != '@'); if (s < hostinfo) { /* again we want the common case to be fall through */ deal_with_host: /* We expect hostinfo to point to the first character of * the hostname. If there's a port it is the first colon, * except with IPv6. */ if (*hostinfo == '[') { v6_offset1 = 1; v6_offset2 = 2; s = memchr(hostinfo, ']', uri - hostinfo); if (s == NULL) { return APR_EGENERAL; } if (*++s != ':') { s = NULL; /* no port */ } } else { s = memchr(hostinfo, ':', uri - hostinfo); } if (s == NULL) { /* we expect the common case to have no port */ uptr->hostname = apr_pstrmemdup(p, hostinfo + v6_offset1, uri - hostinfo - v6_offset2); goto deal_with_path; } uptr->hostname = apr_pstrmemdup(p, hostinfo + v6_offset1, s - hostinfo - v6_offset2); ++s; uptr->port_str = apr_pstrmemdup(p, s, uri - s); if (uri != s) { port = strtol(uptr->port_str, &endstr, 10); uptr->port = port; if (*endstr == '\0') { goto deal_with_path; } /* Invalid characters after ':' found */ return APR_EGENERAL; } uptr->port = apr_uri_port_of_scheme(uptr->scheme); goto deal_with_path; } /* first colon delimits username:password */ s1 = memchr(hostinfo, ':', s - hostinfo); if (s1) { uptr->user = apr_pstrmemdup(p, hostinfo, s1 - hostinfo); ++s1; uptr->password = apr_pstrmemdup(p, s1, s - s1); } else { uptr->user = apr_pstrmemdup(p, hostinfo, s - hostinfo); } hostinfo = s + 1; goto deal_with_host; } /* Special case for CONNECT parsing: it comes with the hostinfo part only */ /* See the INTERNET-DRAFT document "Tunneling SSL Through a WWW Proxy" * currently at http://www.mcom.com/newsref/std/tunneling_ssl.html * for the format of the "CONNECT host:port HTTP/1.0" request */ APU_DECLARE(apr_status_t) apr_uri_parse_hostinfo(apr_pool_t *p, const char *hostinfo, apr_uri_t *uptr) { const char *s; char *endstr; const char *rsb; int v6_offset1 = 0; /* Initialize the structure. parse_uri() and parse_uri_components() * can be called more than once per request. */ memset(uptr, '\0', sizeof(*uptr)); uptr->is_initialized = 1; uptr->hostinfo = apr_pstrdup(p, hostinfo); /* We expect hostinfo to point to the first character of * the hostname. There must be a port, separated by a colon */ if (*hostinfo == '[') { if ((rsb = strchr(hostinfo, ']')) == NULL || *(rsb + 1) != ':') { return APR_EGENERAL; } /* literal IPv6 address */ s = rsb + 1; ++hostinfo; v6_offset1 = 1; } else { s = strchr(hostinfo, ':'); } if (s == NULL) { return APR_EGENERAL; } uptr->hostname = apr_pstrndup(p, hostinfo, s - hostinfo - v6_offset1); ++s; uptr->port_str = apr_pstrdup(p, s); if (*s != '\0') { uptr->port = (unsigned short) strtol(uptr->port_str, &endstr, 10); if (*endstr == '\0') { return APR_SUCCESS; } /* Invalid characters after ':' found */ } return APR_EGENERAL; }
001-log4cxx
trunk/src/apr-util/uri/apr_uri.c
C
asf20
16,290
/* Copyright 2000-2005 The Apache Software Foundation or its licensors, as * applicable. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <apr_thread_proc.h> #include <apr_errno.h> #include <apr_general.h> #include <apr_getopt.h> #include <apr_strings.h> #include "errno.h" #include <stdio.h> #include <stdlib.h> #include <apr_time.h> #if APR_HAVE_UNISTD_H #include <unistd.h> #endif #include <apr_portable.h> #include "apr_queue.h" #if !APR_HAS_THREADS int main(void) { fprintf(stderr, "This program won't work on this platform because there is no " "support for threads.\n"); return 0; } #else /* !APR_HAS_THREADS */ apr_pool_t *context; int consumer_activity=400; int producer_activity=300; int verbose=0; static void * APR_THREAD_FUNC consumer(apr_thread_t *thd, void *data); static void * APR_THREAD_FUNC producer(apr_thread_t *thd, void *data); static void usage(void); static void * APR_THREAD_FUNC consumer(apr_thread_t *thd, void *data) { long sleeprate; apr_queue_t *q = (apr_queue_t*)data; apr_status_t rv; int val; void *v; char current_thread_str[30]; apr_os_thread_t current_thread = apr_os_thread_current(); apr_snprintf(current_thread_str, sizeof current_thread_str, "%pT", &current_thread); sleeprate = 1000000/consumer_activity; apr_sleep( (rand() % 4 ) * 1000000 ); /* sleep random seconds */ while (1) { do { rv = apr_queue_pop(q, &v); if (rv == APR_EINTR) { fprintf(stderr, "%s\tconsumer intr\n", current_thread_str); } } while (rv == APR_EINTR) ; if (rv != APR_SUCCESS) { if (rv == APR_EOF) { fprintf(stderr, "%s\tconsumer:queue terminated APR_EOF\n", current_thread_str); rv=APR_SUCCESS; } else fprintf(stderr, "%s\tconsumer thread exit rv %d\n", current_thread_str, rv); apr_thread_exit(thd, rv); return NULL; } val = *(int*)v; if (verbose) fprintf(stderr, "%s\tpop %d\n", current_thread_str, val); apr_sleep( sleeprate ); /* sleep this long to acheive our rate */ } /* not reached */ return NULL; } static void * APR_THREAD_FUNC producer(apr_thread_t *thd, void *data) { int i=0; long sleeprate; apr_queue_t *q = (apr_queue_t*)data; apr_status_t rv; int *val; char current_thread_str[30]; apr_os_thread_t current_thread = apr_os_thread_current(); apr_snprintf(current_thread_str, sizeof current_thread_str, "%pT", &current_thread); sleeprate = 1000000/producer_activity; apr_sleep( (rand() % 4 ) * 1000000 ); /* sleep random seconds */ while(1) { val = apr_palloc(context, sizeof(int)); *val=i; if (verbose) fprintf(stderr, "%s\tpush %d\n", current_thread_str, *val); do { rv = apr_queue_push(q, val); if (rv == APR_EINTR) fprintf(stderr, "%s\tproducer intr\n", current_thread_str); } while (rv == APR_EINTR); if (rv != APR_SUCCESS) { if (rv == APR_EOF) { fprintf(stderr, "%s\tproducer: queue terminated APR_EOF\n", current_thread_str); rv = APR_SUCCESS; } else fprintf(stderr, "%s\tproducer thread exit rv %d\n", current_thread_str, rv); apr_thread_exit(thd, rv); return NULL; } i++; apr_sleep( sleeprate ); /* sleep this long to acheive our rate */ } /* not reached */ return NULL; } static void usage(void) { fprintf(stderr,"usage: testqueue -p n -P n -c n -C n -q n -s n\n"); fprintf(stderr,"-c # of consumer\n"); fprintf(stderr,"-C amount they consumer before dying\n"); fprintf(stderr,"-p # of producers\n"); fprintf(stderr,"-P amount they produce before dying\n"); fprintf(stderr,"-q queue size\n"); fprintf(stderr,"-s amount of time to sleep before killing it\n"); fprintf(stderr,"-v verbose\n"); } int main(int argc, const char* const argv[]) { apr_thread_t **t; apr_queue_t *queue; int i; apr_status_t rv; apr_getopt_t *opt; const char *optarg; char c; int numconsumers=3; int numproducers=4; int queuesize=100; int sleeptime=30; char errorbuf[200]; apr_initialize(); srand((unsigned int)apr_time_now()); printf("APR Queue Test\n======================\n\n"); printf("%-60s", "Initializing the context"); if (apr_pool_create(&context, NULL) != APR_SUCCESS) { fflush(stdout); fprintf(stderr, "Failed.\nCould not initialize\n"); exit(-1); } printf("OK\n"); apr_getopt_init(&opt, context, argc, argv); while ((rv = apr_getopt(opt, "p:c:P:C:q:s:v", &c, &optarg)) == APR_SUCCESS) { switch (c) { case 'c': numconsumers = atoi( optarg); break; case 'p': numproducers = atoi( optarg); break; case 'C': consumer_activity = atoi( optarg); break; case 'P': producer_activity = atoi( optarg); break; case 's': sleeptime= atoi(optarg); break; case 'q': queuesize = atoi(optarg); break; case 'v': verbose= 1; break; default: usage(); exit(-1); } } /* bad cmdline option? then we die */ if (rv != APR_EOF || opt->ind < opt->argc) { usage(); exit(-1); } printf("test stats %d consumers (rate %d/sec) %d producers (rate %d/sec) queue size %d sleep %d\n", numconsumers,consumer_activity, numproducers, producer_activity, queuesize,sleeptime); printf("%-60s", "Initializing the queue"); rv = apr_queue_create(&queue, queuesize, context); if (rv != APR_SUCCESS) { fflush(stdout); fprintf(stderr, "Failed\nCould not create queue %d\n",rv); apr_strerror(rv, errorbuf,200); fprintf(stderr,"%s\n",errorbuf); exit(-1); } printf("OK\n"); t = apr_palloc( context, sizeof(apr_thread_t*) * (numconsumers+numproducers)); printf("%-60s", "Starting consumers"); for (i=0;i<numconsumers;i++) { rv = apr_thread_create(&t[i], NULL, consumer, queue, context); if (rv != APR_SUCCESS) { apr_strerror(rv, errorbuf,200); fprintf(stderr, "Failed\nError starting consumer thread (%d) rv=%d:%s\n",i, rv,errorbuf); exit(-1); } } for (i=numconsumers;i<(numconsumers+numproducers);i++) { rv = apr_thread_create(&t[i], NULL, producer, queue, context); if (rv != APR_SUCCESS) { apr_strerror(rv, errorbuf,200); fprintf(stderr, "Failed\nError starting producer thread (%d) rv=%d:%s\n",i, rv,errorbuf); exit(-1); } } printf("OK\n"); printf("%-60s", "Sleeping\n"); apr_sleep( sleeptime * 1000000 ); /* sleep 10 seconds */ printf("OK\n"); printf("%-60s", "Terminating queue"); rv = apr_queue_term(queue); if (rv != APR_SUCCESS) { apr_strerror(rv, errorbuf,200); fprintf( stderr, "apr_queue_term failed %d:%s\n",rv,errorbuf); } printf("OK\n"); printf("%-60s", "Waiting for threads to exit\n"); fflush(stdout); for (i=0;i<numconsumers+numproducers;i++) { apr_thread_join(&rv, t[i]); if (rv != 0 ) { apr_strerror(rv, errorbuf,200); if (i<numconsumers) fprintf( stderr, "consumer thread %d failed rv %d:%s\n",i,rv,errorbuf); else fprintf( stderr, "producer thread %d failed rv %d:%s\n",i,rv,errorbuf); } } printf("OK\n"); apr_terminate(); return 0; } #endif /* !APR_HAS_THREADS */
001-log4cxx
trunk/src/apr-util/test/testqueue.c
C
asf20
8,527
/* Copyright 2000-2005 The Apache Software Foundation or its licensors, as * applicable. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "abts.h" #include "testutil.h" #include "apr_buckets.h" #include "apr_strings.h" static void test_create(abts_case *tc, void *data) { apr_bucket_alloc_t *ba; apr_bucket_brigade *bb; ba = apr_bucket_alloc_create(p); bb = apr_brigade_create(p, ba); ABTS_ASSERT(tc, "new brigade not NULL", bb != NULL); ABTS_ASSERT(tc, "new brigade is empty", APR_BRIGADE_EMPTY(bb)); apr_brigade_destroy(bb); apr_bucket_alloc_destroy(ba); } static void test_simple(abts_case *tc, void *data) { apr_bucket_alloc_t *ba; apr_bucket_brigade *bb; apr_bucket *fb, *tb; ba = apr_bucket_alloc_create(p); bb = apr_brigade_create(p, ba); fb = APR_BRIGADE_FIRST(bb); ABTS_ASSERT(tc, "first bucket of empty brigade is sentinel", fb == APR_BRIGADE_SENTINEL(bb)); fb = apr_bucket_flush_create(ba); APR_BRIGADE_INSERT_HEAD(bb, fb); ABTS_ASSERT(tc, "first bucket of brigade is flush", APR_BRIGADE_FIRST(bb) == fb); ABTS_ASSERT(tc, "bucket after flush is sentinel", APR_BUCKET_NEXT(fb) == APR_BRIGADE_SENTINEL(bb)); tb = apr_bucket_transient_create("aaa", 3, ba); APR_BUCKET_INSERT_BEFORE(fb, tb); ABTS_ASSERT(tc, "bucket before flush now transient", APR_BUCKET_PREV(fb) == tb); ABTS_ASSERT(tc, "bucket after transient is flush", APR_BUCKET_NEXT(tb) == fb); ABTS_ASSERT(tc, "bucket before transient is sentinel", APR_BUCKET_PREV(tb) == APR_BRIGADE_SENTINEL(bb)); apr_brigade_cleanup(bb); ABTS_ASSERT(tc, "cleaned up brigade was empty", APR_BRIGADE_EMPTY(bb)); apr_brigade_destroy(bb); apr_bucket_alloc_destroy(ba); } static apr_bucket_brigade *make_simple_brigade(apr_bucket_alloc_t *ba, const char *first, const char *second) { apr_bucket_brigade *bb = apr_brigade_create(p, ba); apr_bucket *e; e = apr_bucket_transient_create(first, strlen(first), ba); APR_BRIGADE_INSERT_TAIL(bb, e); e = apr_bucket_transient_create(second, strlen(second), ba); APR_BRIGADE_INSERT_TAIL(bb, e); return bb; } /* tests that 'bb' flattens to string 'expect'. */ static void flatten_match(abts_case *tc, const char *ctx, apr_bucket_brigade *bb, const char *expect) { apr_size_t elen = strlen(expect); char *buf = malloc(elen); apr_size_t len = elen; char msg[200]; sprintf(msg, "%s: flatten brigade", ctx); apr_assert_success(tc, msg, apr_brigade_flatten(bb, buf, &len)); sprintf(msg, "%s: length match (%ld not %ld)", ctx, (long)len, (long)elen); ABTS_ASSERT(tc, msg, len == elen); sprintf(msg, "%s: result match", msg); ABTS_STR_NEQUAL(tc, expect, buf, len); free(buf); } static void test_flatten(abts_case *tc, void *data) { apr_bucket_alloc_t *ba = apr_bucket_alloc_create(p); apr_bucket_brigade *bb; bb = make_simple_brigade(ba, "hello, ", "world"); flatten_match(tc, "flatten brigade", bb, "hello, world"); apr_brigade_destroy(bb); apr_bucket_alloc_destroy(ba); } static int count_buckets(apr_bucket_brigade *bb) { apr_bucket *e; int count = 0; for (e = APR_BRIGADE_FIRST(bb); e != APR_BRIGADE_SENTINEL(bb); e = APR_BUCKET_NEXT(e)) { count++; } return count; } static void test_split(abts_case *tc, void *data) { apr_bucket_alloc_t *ba = apr_bucket_alloc_create(p); apr_bucket_brigade *bb, *bb2; apr_bucket *e; bb = make_simple_brigade(ba, "hello, ", "world"); /* split at the "world" bucket */ e = APR_BRIGADE_LAST(bb); bb2 = apr_brigade_split(bb, e); ABTS_ASSERT(tc, "split brigade contains one bucket", count_buckets(bb2) == 1); ABTS_ASSERT(tc, "original brigade contains one bucket", count_buckets(bb) == 1); flatten_match(tc, "match original brigade", bb, "hello, "); flatten_match(tc, "match split brigade", bb2, "world"); apr_brigade_destroy(bb2); apr_brigade_destroy(bb); apr_bucket_alloc_destroy(ba); } #define COUNT 3000 #define THESTR "hello" static void test_bwrite(abts_case *tc, void *data) { apr_bucket_alloc_t *ba = apr_bucket_alloc_create(p); apr_bucket_brigade *bb = apr_brigade_create(p, ba); apr_off_t length; int n; for (n = 0; n < COUNT; n++) { apr_assert_success(tc, "brigade_write", apr_brigade_write(bb, NULL, NULL, THESTR, sizeof THESTR)); } apr_assert_success(tc, "determine brigade length", apr_brigade_length(bb, 1, &length)); ABTS_ASSERT(tc, "brigade has correct length", length == (COUNT * sizeof THESTR)); apr_brigade_destroy(bb); apr_bucket_alloc_destroy(ba); } static void test_splitline(abts_case *tc, void *data) { apr_bucket_alloc_t *ba = apr_bucket_alloc_create(p); apr_bucket_brigade *bin, *bout; bin = make_simple_brigade(ba, "blah blah blah-", "end of line.\nfoo foo foo"); bout = apr_brigade_create(p, ba); apr_assert_success(tc, "split line", apr_brigade_split_line(bout, bin, APR_BLOCK_READ, 100)); flatten_match(tc, "split line", bout, "blah blah blah-end of line.\n"); flatten_match(tc, "remainder", bin, "foo foo foo"); apr_brigade_destroy(bout); apr_brigade_destroy(bin); apr_bucket_alloc_destroy(ba); } /* Test that bucket E has content EDATA of length ELEN. */ static void test_bucket_content(abts_case *tc, apr_bucket *e, const char *edata, apr_size_t elen) { const char *adata; apr_size_t alen; apr_assert_success(tc, "read from bucket", apr_bucket_read(e, &adata, &alen, APR_BLOCK_READ)); ABTS_ASSERT(tc, "read expected length", alen == elen); ABTS_STR_NEQUAL(tc, edata, adata, elen); } static void test_splits(abts_case *tc, void *ctx) { apr_bucket_alloc_t *ba = apr_bucket_alloc_create(p); apr_bucket_brigade *bb; apr_bucket *e; char *str = "alphabeta"; int n; bb = apr_brigade_create(p, ba); APR_BRIGADE_INSERT_TAIL(bb, apr_bucket_immortal_create(str, 9, ba)); APR_BRIGADE_INSERT_TAIL(bb, apr_bucket_transient_create(str, 9, ba)); APR_BRIGADE_INSERT_TAIL(bb, apr_bucket_heap_create(strdup(str), 9, free, ba)); APR_BRIGADE_INSERT_TAIL(bb, apr_bucket_pool_create(apr_pstrdup(p, str), 9, p, ba)); ABTS_ASSERT(tc, "four buckets inserted", count_buckets(bb) == 4); /* now split each of the buckets after byte 5 */ for (n = 0, e = APR_BRIGADE_FIRST(bb); n < 4; n++) { ABTS_ASSERT(tc, "reached end of brigade", e != APR_BRIGADE_SENTINEL(bb)); ABTS_ASSERT(tc, "split bucket OK", apr_bucket_split(e, 5) == APR_SUCCESS); e = APR_BUCKET_NEXT(e); ABTS_ASSERT(tc, "split OK", e != APR_BRIGADE_SENTINEL(bb)); e = APR_BUCKET_NEXT(e); } ABTS_ASSERT(tc, "four buckets split into eight", count_buckets(bb) == 8); for (n = 0, e = APR_BRIGADE_FIRST(bb); n < 4; n++) { const char *data; apr_size_t len; apr_assert_success(tc, "read alpha from bucket", apr_bucket_read(e, &data, &len, APR_BLOCK_READ)); ABTS_ASSERT(tc, "read 5 bytes", len == 5); ABTS_STR_NEQUAL(tc, "alpha", data, 5); e = APR_BUCKET_NEXT(e); apr_assert_success(tc, "read beta from bucket", apr_bucket_read(e, &data, &len, APR_BLOCK_READ)); ABTS_ASSERT(tc, "read 4 bytes", len == 4); ABTS_STR_NEQUAL(tc, "beta", data, 5); e = APR_BUCKET_NEXT(e); } /* now delete the "alpha" buckets */ for (n = 0, e = APR_BRIGADE_FIRST(bb); n < 4; n++) { apr_bucket *f; ABTS_ASSERT(tc, "reached end of brigade", e != APR_BRIGADE_SENTINEL(bb)); f = APR_BUCKET_NEXT(e); apr_bucket_delete(e); e = APR_BUCKET_NEXT(f); } ABTS_ASSERT(tc, "eight buckets reduced to four", count_buckets(bb) == 4); flatten_match(tc, "flatten beta brigade", bb, "beta" "beta" "beta" "beta"); apr_brigade_destroy(bb); apr_bucket_alloc_destroy(ba); } #define TIF_FNAME "testfile.txt" static void test_insertfile(abts_case *tc, void *ctx) { apr_bucket_alloc_t *ba = apr_bucket_alloc_create(p); apr_bucket_brigade *bb; const apr_off_t bignum = (APR_INT64_C(2) << 32) + 424242; apr_off_t count; apr_file_t *f; apr_bucket *e; ABTS_ASSERT(tc, "open test file", apr_file_open(&f, TIF_FNAME, APR_WRITE|APR_TRUNCATE|APR_CREATE, APR_OS_DEFAULT, p) == APR_SUCCESS); if (apr_file_trunc(f, bignum)) { apr_file_close(f); apr_file_remove(TIF_FNAME, p); ABTS_NOT_IMPL(tc, "Skipped: could not create large file"); return; } bb = apr_brigade_create(p, ba); e = apr_brigade_insert_file(bb, f, 0, bignum, p); ABTS_ASSERT(tc, "inserted file was not at end of brigade", e == APR_BRIGADE_LAST(bb)); /* check that the total size of inserted buckets is equal to the * total size of the file. */ count = 0; for (e = APR_BRIGADE_FIRST(bb); e != APR_BRIGADE_SENTINEL(bb); e = APR_BUCKET_NEXT(e)) { ABTS_ASSERT(tc, "bucket size sane", e->length != (apr_size_t)-1); count += e->length; } ABTS_ASSERT(tc, "total size of buckets incorrect", count == bignum); apr_brigade_destroy(bb); /* Truncate the file to zero size before close() so that we don't * actually write out the large file if we are on a non-sparse file * system - like Mac OS X's HFS. Otherwise, pity the poor user who * has to wait for the 8GB file to be written to disk. */ apr_file_trunc(f, 0); apr_file_close(f); apr_bucket_alloc_destroy(ba); apr_file_remove(TIF_FNAME, p); } /* Make a test file named FNAME, and write CONTENTS to it. */ static apr_file_t *make_test_file(abts_case *tc, const char *fname, const char *contents) { apr_file_t *f; ABTS_ASSERT(tc, "create test file", apr_file_open(&f, fname, APR_READ|APR_WRITE|APR_TRUNCATE|APR_CREATE, APR_OS_DEFAULT, p) == APR_SUCCESS); ABTS_ASSERT(tc, "write test file contents", apr_file_puts(contents, f) == APR_SUCCESS); return f; } static void test_manyfile(abts_case *tc, void *data) { apr_bucket_alloc_t *ba = apr_bucket_alloc_create(p); apr_bucket_brigade *bb = apr_brigade_create(p, ba); apr_file_t *f; f = make_test_file(tc, "manyfile.bin", "world" "hello" "brave" " ,\n"); apr_brigade_insert_file(bb, f, 5, 5, p); apr_brigade_insert_file(bb, f, 16, 1, p); apr_brigade_insert_file(bb, f, 15, 1, p); apr_brigade_insert_file(bb, f, 10, 5, p); apr_brigade_insert_file(bb, f, 15, 1, p); apr_brigade_insert_file(bb, f, 0, 5, p); apr_brigade_insert_file(bb, f, 17, 1, p); /* can you tell what it is yet? */ flatten_match(tc, "file seek test", bb, "hello, brave world\n"); apr_file_close(f); apr_brigade_destroy(bb); apr_bucket_alloc_destroy(ba); } /* Regression test for PR 34708, where a file bucket will keep * duplicating itself on being read() when EOF is reached * prematurely. */ static void test_truncfile(abts_case *tc, void *data) { apr_bucket_alloc_t *ba = apr_bucket_alloc_create(p); apr_bucket_brigade *bb = apr_brigade_create(p, ba); apr_file_t *f = make_test_file(tc, "testfile.txt", "hello"); apr_bucket *e; const char *buf; apr_size_t len; apr_brigade_insert_file(bb, f, 0, 5, p); apr_file_trunc(f, 0); e = APR_BRIGADE_FIRST(bb); ABTS_ASSERT(tc, "single bucket in brigade", APR_BUCKET_NEXT(e) == APR_BRIGADE_SENTINEL(bb)); apr_bucket_file_enable_mmap(e, 0); ABTS_ASSERT(tc, "read gave APR_EOF", apr_bucket_read(e, &buf, &len, APR_BLOCK_READ) == APR_EOF); ABTS_ASSERT(tc, "read length 0", len == 0); ABTS_ASSERT(tc, "still a single bucket in brigade", APR_BUCKET_NEXT(e) == APR_BRIGADE_SENTINEL(bb)); apr_file_close(f); apr_brigade_destroy(bb); apr_bucket_alloc_destroy(ba); } static const char hello[] = "hello, world"; static void test_partition(abts_case *tc, void *data) { apr_bucket_alloc_t *ba = apr_bucket_alloc_create(p); apr_bucket_brigade *bb = apr_brigade_create(p, ba); apr_bucket *e; e = apr_bucket_immortal_create(hello, strlen(hello), ba); APR_BRIGADE_INSERT_HEAD(bb, e); apr_assert_success(tc, "partition brigade", apr_brigade_partition(bb, 5, &e)); test_bucket_content(tc, APR_BRIGADE_FIRST(bb), "hello", 5); test_bucket_content(tc, APR_BRIGADE_LAST(bb), ", world", 7); ABTS_ASSERT(tc, "partition returns APR_INCOMPLETE", apr_brigade_partition(bb, 8192, &e)); ABTS_ASSERT(tc, "APR_INCOMPLETE partition returned sentinel", e == APR_BRIGADE_SENTINEL(bb)); apr_brigade_destroy(bb); apr_bucket_alloc_destroy(ba); } abts_suite *testbuckets(abts_suite *suite) { suite = ADD_SUITE(suite); abts_run_test(suite, test_create, NULL); abts_run_test(suite, test_simple, NULL); abts_run_test(suite, test_flatten, NULL); abts_run_test(suite, test_split, NULL); abts_run_test(suite, test_bwrite, NULL); abts_run_test(suite, test_splitline, NULL); abts_run_test(suite, test_splits, NULL); abts_run_test(suite, test_insertfile, NULL); abts_run_test(suite, test_manyfile, NULL); abts_run_test(suite, test_truncfile, NULL); abts_run_test(suite, test_partition, NULL); return suite; }
001-log4cxx
trunk/src/apr-util/test/testbuckets.c
C
asf20
15,234
/* Copyright 2000-2005 The Apache Software Foundation or its licensors, as * applicable. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <assert.h> #include <stdio.h> #include <stdlib.h> #include "apr_errno.h" #include "apr_strings.h" #include "apr_file_io.h" #include "apr_thread_proc.h" #include "apr_md5.h" #include "apr_sha1.h" #include "abts.h" #include "testutil.h" static struct { const char *password; const char *hash; } passwords[] = { /* passwords and hashes created with Apache's htpasswd utility like this: htpasswd -c -b passwords pass1 pass1 htpasswd -b passwords pass2 pass2 htpasswd -b passwords pass3 pass3 htpasswd -b passwords pass4 pass4 htpasswd -b passwords pass5 pass5 htpasswd -b passwords pass6 pass6 htpasswd -b passwords pass7 pass7 htpasswd -b passwords pass8 pass8 (insert Perl one-liner to convert to initializer :) ) */ {"pass1", "1fWDc9QWYCWrQ"}, {"pass2", "1fiGx3u7QoXaM"}, {"pass3", "1fzijMylTiwCs"}, {"pass4", "nHUYc8U2UOP7s"}, {"pass5", "nHpETGLGPwAmA"}, {"pass6", "nHbsbWmJ3uyhc"}, {"pass7", "nHQ3BbF0Y9vpI"}, {"pass8", "nHZA1rViSldQk"} }; static int num_passwords = sizeof(passwords) / sizeof(passwords[0]); static void test_crypt(abts_case *tc, void *data) { int i; for (i = 0; i < num_passwords; i++) { apr_assert_success(tc, "check for valid password", apr_password_validate(passwords[i].password, passwords[i].hash)); } } #if APR_HAS_THREADS static void * APR_THREAD_FUNC testing_thread(apr_thread_t *thd, void *data) { abts_case *tc = data; int i; for (i = 0; i < 100; i++) { test_crypt(tc, NULL); } return APR_SUCCESS; } /* test for threadsafe crypt() */ static void test_threadsafe(abts_case *tc, void *data) { #define NUM_THR 20 apr_thread_t *my_threads[NUM_THR]; int i; apr_status_t rv; for (i = 0; i < NUM_THR; i++) { apr_assert_success(tc, "create test thread", apr_thread_create(&my_threads[i], NULL, testing_thread, tc, p)); } for (i = 0; i < NUM_THR; i++) { apr_thread_join(&rv, my_threads[i]); } } #endif static void test_shapass(abts_case *tc, void *data) { const char *pass = "hellojed"; char hash[100]; apr_sha1_base64(pass, strlen(pass), hash); apr_assert_success(tc, "SHA1 password validated", apr_password_validate(pass, hash)); } static void test_md5pass(abts_case *tc, void *data) { const char *pass = "hellojed", *salt = "sardine"; char hash[100]; apr_md5_encode(pass, salt, hash, sizeof hash); apr_assert_success(tc, "MD5 password validated", apr_password_validate(pass, hash)); } abts_suite *testpass(abts_suite *suite) { suite = ADD_SUITE(suite); abts_run_test(suite, test_crypt, NULL); #if APR_HAS_THREADS abts_run_test(suite, test_threadsafe, NULL); #endif abts_run_test(suite, test_shapass, NULL); abts_run_test(suite, test_md5pass, NULL); return suite; }
001-log4cxx
trunk/src/apr-util/test/testpass.c
C
asf20
3,731
/* Copyright 2000-2005 The Apache Software Foundation or its licensors, as * applicable. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "apu.h" #include "apr_pools.h" #include "apr_dbd.h" #include <stdio.h> #define TEST(msg,func) \ printf("======== %s ========\n", msg); \ rv = func(pool, sql, driver); \ if (rv != 0) { \ printf("Error in %s: rc=%d\n\n", msg, rv); \ } \ else { \ printf("%s test successful\n\n", msg); \ } \ fflush(stdout); static int create_table(apr_pool_t* pool, apr_dbd_t* handle, const apr_dbd_driver_t* driver) { int rv = 0; int nrows; const char *statement = "CREATE TABLE apr_dbd_test (" "col1 varchar(40) not null," "col2 varchar(40)," "col3 integer)" ; rv = apr_dbd_query(driver, handle, &nrows, statement); return rv; } static int drop_table(apr_pool_t* pool, apr_dbd_t* handle, const apr_dbd_driver_t* driver) { int rv = 0; int nrows; const char *statement = "DROP TABLE apr_dbd_test" ; rv = apr_dbd_query(driver, handle, &nrows, statement); return rv; } static int insert_rows(apr_pool_t* pool, apr_dbd_t* handle, const apr_dbd_driver_t* driver) { int i; int rv = 0; int nrows; int nerrors = 0; const char *statement = "INSERT into apr_dbd_test (col1) values ('foo');" "INSERT into apr_dbd_test values ('wibble', 'other', 5);" "INSERT into apr_dbd_test values ('wibble', 'nothing', 5);" "INSERT into apr_dbd_test values ('qwerty', 'foo', 0);" "INSERT into apr_dbd_test values ('asdfgh', 'bar', 1);" ; rv = apr_dbd_query(driver, handle, &nrows, statement); if (rv) { const char* stmt[] = { "INSERT into apr_dbd_test (col1) values ('foo');", "INSERT into apr_dbd_test values ('wibble', 'other', 5);", "INSERT into apr_dbd_test values ('wibble', 'nothing', 5);", "INSERT into apr_dbd_test values ('qwerty', 'foo', 0);", "INSERT into apr_dbd_test values ('asdfgh', 'bar', 1);", NULL }; printf("Compound insert failed; trying statements one-by-one\n") ; for (i=0; stmt[i] != NULL; ++i) { statement = stmt[i]; rv = apr_dbd_query(driver, handle, &nrows, statement); if (rv) { nerrors++; } } if (nerrors) { printf("%d single inserts failed too.\n", nerrors) ; } } return rv; } static int invalid_op(apr_pool_t* pool, apr_dbd_t* handle, const apr_dbd_driver_t* driver) { int rv = 0; int nrows; const char *statement = "INSERT into apr_dbd_test1 (col2) values ('foo')" ; rv = apr_dbd_query(driver, handle, &nrows, statement); printf("invalid op returned %d (should be nonzero). Error msg follows\n", rv); printf("'%s'\n", apr_dbd_error(driver, handle, rv)); statement = "INSERT into apr_dbd_test (col1, col2) values ('bar', 'foo')" ; rv = apr_dbd_query(driver, handle, &nrows, statement); printf("valid op returned %d (should be zero; error shouldn't affect subsequent ops)\n", rv); return rv; } static int select_sequential(apr_pool_t* pool, apr_dbd_t* handle, const apr_dbd_driver_t* driver) { int rv = 0; int i = 0; int n; const char* entry; const char* statement = "SELECT * FROM apr_dbd_test ORDER BY col1, col2"; apr_dbd_results_t *res = NULL; apr_dbd_row_t *row = NULL; rv = apr_dbd_select(driver,pool,handle,&res,statement,0); if (rv) { printf("Select failed: %s", apr_dbd_error(driver, handle, rv)); return rv; } for (rv = apr_dbd_get_row(driver, pool, res, &row, -1); rv == 0; rv = apr_dbd_get_row(driver, pool, res, &row, -1)) { printf("ROW %d: ", i++) ; for (n = 0; n < apr_dbd_num_cols(driver, res); ++n) { entry = apr_dbd_get_entry(driver, row, n); if (entry == NULL) { printf("(null) ") ; } else { printf("%s ", entry); } } fputs("\n", stdout); } return (rv == -1) ? 0 : 1; } static int select_random(apr_pool_t* pool, apr_dbd_t* handle, const apr_dbd_driver_t* driver) { int rv = 0; int n; const char* entry; const char* statement = "SELECT * FROM apr_dbd_test ORDER BY col1, col2"; apr_dbd_results_t *res = NULL; apr_dbd_row_t *row = NULL; rv = apr_dbd_select(driver,pool,handle,&res,statement,1); if (rv) { printf("Select failed: %s", apr_dbd_error(driver, handle, rv)); return rv; } rv = apr_dbd_get_row(driver, pool, res, &row, 5) ; if (rv) { printf("get_row failed: %s", apr_dbd_error(driver, handle, rv)); return rv; } printf("ROW 5: "); for (n = 0; n < apr_dbd_num_cols(driver, res); ++n) { entry = apr_dbd_get_entry(driver, row, n); if (entry == NULL) { printf("(null) ") ; } else { printf("%s ", entry); } } fputs("\n", stdout); rv = apr_dbd_get_row(driver, pool, res, &row, 1) ; if (rv) { printf("get_row failed: %s", apr_dbd_error(driver, handle, rv)); return rv; } printf("ROW 1: "); for (n = 0; n < apr_dbd_num_cols(driver, res); ++n) { entry = apr_dbd_get_entry(driver, row, n); if (entry == NULL) { printf("(null) ") ; } else { printf("%s ", entry); } } fputs("\n", stdout); rv = apr_dbd_get_row(driver, pool, res, &row, 11) ; if (rv != -1) { printf("Oops! get_row out of range but thinks it succeeded!\n%s\n", apr_dbd_error(driver, handle, rv)); return -1; } rv = 0; return rv; } static int test_transactions(apr_pool_t* pool, apr_dbd_t* handle, const apr_dbd_driver_t* driver) { int rv = 0; int nrows; apr_dbd_transaction_t *trans = NULL; const char* statement; /* trans 1 - error out early */ printf("Transaction 1\n"); rv = apr_dbd_transaction_start(driver, pool, handle, &trans); if (rv) { printf("Start transaction failed!\n%s\n", apr_dbd_error(driver, handle, rv)); return rv; } statement = "UPDATE apr_dbd_test SET col2 = 'failed'"; rv = apr_dbd_query(driver, handle, &nrows, statement); if (rv) { printf("Update failed: '%s'\n", apr_dbd_error(driver, handle, rv)); apr_dbd_transaction_end(driver, pool, trans); return rv; } printf("%d rows updated\n", nrows); statement = "INSERT INTO apr_dbd_test1 (col3) values (3)"; rv = apr_dbd_query(driver, handle, &nrows, statement); if (!rv) { printf("Oops, invalid op succeeded but shouldn't!\n"); } statement = "INSERT INTO apr_dbd_test values ('zzz', 'aaa', 3)"; rv = apr_dbd_query(driver, handle, &nrows, statement); printf("Valid insert returned %d. Should be nonzero (fail) because transaction is bad\n", rv) ; rv = apr_dbd_transaction_end(driver, pool, trans); if (rv) { printf("End transaction failed!\n%s\n", apr_dbd_error(driver, handle, rv)); return rv; } printf("Transaction ended (should be rollback) - viewing table\n" "A column of \"failed\" indicates transaction failed (no rollback)\n"); select_sequential(pool, handle, driver); /* trans 2 - complete successfully */ printf("Transaction 2\n"); rv = apr_dbd_transaction_start(driver, pool, handle, &trans); if (rv) { printf("Start transaction failed!\n%s\n", apr_dbd_error(driver, handle, rv)); return rv; } statement = "UPDATE apr_dbd_test SET col2 = 'success'"; rv = apr_dbd_query(driver, handle, &nrows, statement); if (rv) { printf("Update failed: '%s'\n", apr_dbd_error(driver, handle, rv)); apr_dbd_transaction_end(driver, pool, trans); return rv; } printf("%d rows updated\n", nrows); statement = "INSERT INTO apr_dbd_test values ('aaa', 'zzz', 3)"; rv = apr_dbd_query(driver, handle, &nrows, statement); printf("Valid insert returned %d. Should be zero (OK)\n", rv) ; rv = apr_dbd_transaction_end(driver, pool, trans); if (rv) { printf("End transaction failed!\n%s\n", apr_dbd_error(driver, handle, rv)); return rv; } printf("Transaction ended (should be commit) - viewing table\n"); select_sequential(pool, handle, driver); return rv; } static int test_pselect(apr_pool_t* pool, apr_dbd_t* handle, const apr_dbd_driver_t* driver) { int rv = 0; int i, n; const char *query = "SELECT * FROM apr_dbd_test WHERE col3 <= %s or col1 = 'bar'" ; const char *label = "lowvalues"; apr_dbd_prepared_t *statement = NULL; apr_dbd_results_t *res = NULL; apr_dbd_row_t *row = NULL; const char *entry = NULL; rv = apr_dbd_prepare(driver, pool, handle, query, label, &statement); if (rv) { printf("Prepare statement failed!\n%s\n", apr_dbd_error(driver, handle, rv)); return rv; } rv = apr_dbd_pvselect(driver, pool, handle, &res, statement, 0, "3", NULL); if (rv) { printf("Exec of prepared statement failed!\n%s\n", apr_dbd_error(driver, handle, rv)); return rv; } i = 0; printf("Selecting rows where col3 <= 3 and bar row where it's unset.\nShould show four rows.\n"); for (rv = apr_dbd_get_row(driver, pool, res, &row, -1); rv == 0; rv = apr_dbd_get_row(driver, pool, res, &row, -1)) { printf("ROW %d: ", i++) ; for (n = 0; n < apr_dbd_num_cols(driver, res); ++n) { entry = apr_dbd_get_entry(driver, row, n); if (entry == NULL) { printf("(null) ") ; } else { printf("%s ", entry); } } fputs("\n", stdout); } return (rv == -1) ? 0 : 1; } static int test_pquery(apr_pool_t* pool, apr_dbd_t* handle, const apr_dbd_driver_t* driver) { int rv = 0; const char *query = "INSERT INTO apr_dbd_test VALUES (%s, %s, %d)"; apr_dbd_prepared_t *statement = NULL; const char *label = "testpquery"; int nrows; apr_dbd_transaction_t *trans =0; rv = apr_dbd_prepare(driver, pool, handle, query, label, &statement); /* rv = apr_dbd_prepare(driver, pool, handle, query, NULL, &statement); */ if (rv) { printf("Prepare statement failed!\n%s\n", apr_dbd_error(driver, handle, rv)); return rv; } apr_dbd_transaction_start(driver, pool, handle, &trans); rv = apr_dbd_pvquery(driver, pool, handle, &nrows, statement, "prepared", "insert", "2", NULL); apr_dbd_transaction_end(driver, pool, trans); if (rv) { printf("Exec of prepared statement failed!\n%s\n", apr_dbd_error(driver, handle, rv)); return rv; } printf("Showing table (should now contain row \"prepared insert 2\")\n"); select_sequential(pool, handle, driver); return rv; } int main(int argc, char** argv) { const char *name; const char *params; apr_pool_t *pool = NULL; apr_dbd_t *sql = NULL; const apr_dbd_driver_t *driver = NULL; int rv; apr_initialize(); apr_pool_create(&pool, NULL); if (argc >= 2 && argc <= 3) { name = argv[1]; params = ( argc == 3 ) ? argv[2] : ""; apr_dbd_init(pool); setbuf(stdout,NULL); rv = apr_dbd_get_driver(pool, name, &driver); switch (rv) { case APR_SUCCESS: printf("Loaded %s driver OK.\n", name); break; case APR_EDSOOPEN: printf("Failed to load driver file apr_dbd_%s.so\n", name); goto finish; case APR_ESYMNOTFOUND: printf("Failed to load driver apr_dbd_%s_driver.\n", name); goto finish; case APR_ENOTIMPL: printf("No driver available for %s.\n", name); goto finish; default: /* it's a bug if none of the above happen */ printf("Internal error loading %s.\n", name); goto finish; } rv = apr_dbd_open(driver, pool, params, &sql); switch (rv) { case APR_SUCCESS: printf("Opened %s[%s] OK\n", name, params); break; case APR_EGENERAL: printf("Failed to open %s[%s]\n", name, params); goto finish; default: /* it's a bug if none of the above happen */ printf("Internal error opening %s[%s]\n", name, params); goto finish; } TEST("create table", create_table); TEST("insert rows", insert_rows); TEST("invalid op", invalid_op); TEST("select random", select_random); TEST("select sequential", select_sequential); TEST("transactions", test_transactions); TEST("prepared select", test_pselect); TEST("prepared query", test_pquery); TEST("drop table", drop_table); apr_dbd_close(driver, sql); } else { fprintf(stderr, "Usage: %s driver-name [params]\n", argv[0]); } finish: apr_pool_destroy(pool); apr_terminate(); return 0; }
001-log4cxx
trunk/src/apr-util/test/dbd.c
C
asf20
14,095
/* Copyright 2000-2005 The Apache Software Foundation or its licensors, as * applicable. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "apr_shm.h" #include "apr_rmm.h" #include "apr_errno.h" #include "apr_general.h" #include "apr_lib.h" #include "apr_strings.h" #include "apr_time.h" #include <errno.h> #include <stdio.h> #include <stdlib.h> #if APR_HAVE_UNISTD_H #include <unistd.h> #endif #if APR_HAS_SHARED_MEMORY #define FRAG_SIZE 80 #define FRAG_COUNT 10 #define SHARED_SIZE (apr_size_t)(FRAG_SIZE * FRAG_COUNT * sizeof(char*)) static apr_status_t test_rmm(apr_pool_t *parpool) { apr_status_t rv; apr_pool_t *pool; apr_shm_t *shm; apr_rmm_t *rmm; apr_size_t size, fragsize; apr_rmm_off_t *off; int i; void *entity; rv = apr_pool_create(&pool, parpool); if (rv != APR_SUCCESS) { fprintf(stderr, "Error creating child pool\n"); return rv; } /* We're going to want 10 blocks of data from our target rmm. */ size = SHARED_SIZE + apr_rmm_overhead_get(FRAG_COUNT + 1); printf("Creating anonymous shared memory (%" APR_SIZE_T_FMT " bytes).....", size); rv = apr_shm_create(&shm, size, NULL, pool); if (rv != APR_SUCCESS) { fprintf(stderr, "Error allocating shared memory block\n"); return rv; } fprintf(stdout, "OK\n"); printf("Creating rmm segment............................."); rv = apr_rmm_init(&rmm, NULL, apr_shm_baseaddr_get(shm), size, pool); if (rv != APR_SUCCESS) { fprintf(stderr, "Error allocating rmm..............\n"); return rv; } fprintf(stdout, "OK\n"); fragsize = SHARED_SIZE / FRAG_COUNT; printf("Creating each fragment of size %" APR_SIZE_T_FMT "................", fragsize); off = apr_palloc(pool, FRAG_COUNT * sizeof(apr_rmm_off_t)); for (i = 0; i < FRAG_COUNT; i++) { off[i] = apr_rmm_malloc(rmm, fragsize); } fprintf(stdout, "OK\n"); printf("Checking for out of memory allocation............"); if (apr_rmm_malloc(rmm, FRAG_SIZE * FRAG_COUNT) == 0) { fprintf(stdout, "OK\n"); } else { return APR_EGENERAL; } printf("Checking each fragment for address alignment....."); for (i = 0; i < FRAG_COUNT; i++) { char *c = apr_rmm_addr_get(rmm, off[i]); apr_size_t sc = (apr_size_t)c; if (off[i] == 0) { printf("allocation failed for offset %d\n", i); return APR_ENOMEM; } if (sc & 7) { printf("Bad alignment for fragment %d; %p not %p!\n", i, c, (void *)APR_ALIGN_DEFAULT((apr_size_t)c)); return APR_EGENERAL; } } fprintf(stdout, "OK\n"); printf("Setting each fragment to a unique value.........."); for (i = 0; i < FRAG_COUNT; i++) { int j; char **c = apr_rmm_addr_get(rmm, off[i]); for (j = 0; j < FRAG_SIZE; j++, c++) { *c = apr_itoa(pool, i + j); } } fprintf(stdout, "OK\n"); printf("Checking each fragment for its unique value......"); for (i = 0; i < FRAG_COUNT; i++) { int j; char **c = apr_rmm_addr_get(rmm, off[i]); for (j = 0; j < FRAG_SIZE; j++, c++) { char *d = apr_itoa(pool, i + j); if (strcmp(*c, d) != 0) { return APR_EGENERAL; } } } fprintf(stdout, "OK\n"); printf("Freeing each fragment............................"); for (i = 0; i < FRAG_COUNT; i++) { rv = apr_rmm_free(rmm, off[i]); if (rv != APR_SUCCESS) { return rv; } } fprintf(stdout, "OK\n"); printf("Creating one large segment......................."); off[0] = apr_rmm_calloc(rmm, SHARED_SIZE); fprintf(stdout, "OK\n"); printf("Setting large segment............................"); for (i = 0; i < FRAG_COUNT * FRAG_SIZE; i++) { char **c = apr_rmm_addr_get(rmm, off[0]); c[i] = apr_itoa(pool, i); } fprintf(stdout, "OK\n"); printf("Freeing large segment............................"); apr_rmm_free(rmm, off[0]); fprintf(stdout, "OK\n"); printf("Creating each fragment of size %" APR_SIZE_T_FMT " (again)........", fragsize); for (i = 0; i < FRAG_COUNT; i++) { off[i] = apr_rmm_malloc(rmm, fragsize); } fprintf(stdout, "OK\n"); printf("Freeing each fragment backwards.................."); for (i = FRAG_COUNT - 1; i >= 0; i--) { rv = apr_rmm_free(rmm, off[i]); if (rv != APR_SUCCESS) { return rv; } } fprintf(stdout, "OK\n"); printf("Creating one large segment (again)..............."); off[0] = apr_rmm_calloc(rmm, SHARED_SIZE); fprintf(stdout, "OK\n"); printf("Freeing large segment............................"); apr_rmm_free(rmm, off[0]); fprintf(stdout, "OK\n"); printf("Checking realloc................................."); off[0] = apr_rmm_calloc(rmm, SHARED_SIZE - 100); off[1] = apr_rmm_calloc(rmm, 100); if (off[0] == 0 || off[1] == 0) { printf("FAILED\n"); return APR_EINVAL; } entity = apr_rmm_addr_get(rmm, off[1]); rv = apr_rmm_free(rmm, off[0]); if (rv != APR_SUCCESS) { printf("FAILED\n"); return rv; } { unsigned char *c = entity; /* Fill in the region; the first half with zereos, which will * likely catch the apr_rmm_realloc offset calculation bug by * making it think the old region was zero length. */ for (i = 0; i < 100; i++) { c[i] = (i < 50) ? 0 : i; } } /* now we can realloc off[1] and get many more bytes */ off[0] = apr_rmm_realloc(rmm, entity, SHARED_SIZE - 100); if (off[0] == 0) { printf("FAILED\n"); return APR_EINVAL; } { unsigned char *c = apr_rmm_addr_get(rmm, off[0]); /* fill in the region */ for (i = 0; i < 100; i++) { if (c[i] != (i < 50 ? 0 : i)) { printf("FAILED at offset %d: %hx\n", i, c[i]); return APR_EGENERAL; } } } fprintf(stdout, "OK\n"); printf("Destroying rmm segment..........................."); rv = apr_rmm_destroy(rmm); if (rv != APR_SUCCESS) { printf("FAILED\n"); return rv; } printf("OK\n"); printf("Destroying shared memory segment................."); rv = apr_shm_destroy(shm); if (rv != APR_SUCCESS) { printf("FAILED\n"); return rv; } printf("OK\n"); apr_pool_destroy(pool); return APR_SUCCESS; } int main(void) { apr_status_t rv; apr_pool_t *pool; char errmsg[200]; apr_initialize(); printf("APR RMM Memory Test\n"); printf("======================\n\n"); printf("Initializing the pool............................"); if (apr_pool_create(&pool, NULL) != APR_SUCCESS) { printf("could not initialize pool\n"); exit(-1); } printf("OK\n"); rv = test_rmm(pool); if (rv != APR_SUCCESS) { printf("Anonymous shared memory test FAILED: [%d] %s\n", rv, apr_strerror(rv, errmsg, sizeof(errmsg))); exit(-2); } printf("RMM test passed!\n"); return 0; } #else /* APR_HAS_SHARED_MEMORY */ #error shmem is not supported on this platform #endif /* APR_HAS_SHARED_MEMORY */
001-log4cxx
trunk/src/apr-util/test/testrmm.c
C
asf20
8,021
/* Copyright 2000-2005 The Apache Software Foundation or its licensors, as * applicable. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "testutil.h" #include "apr.h" #include "apu.h" #include "apr_pools.h" #include "apr_dbd.h" #include "apr_strings.h" static void test_dbd_init(abts_case *tc, void *data) { apr_pool_t *pool = p; apr_status_t rv; rv = apr_dbd_init(pool); ABTS_ASSERT(tc, "failed to init apr_dbd", rv == APR_SUCCESS); } #if APU_HAVE_SQLITE2 || APU_HAVE_SQLITE3 static void test_statement(abts_case *tc, apr_dbd_t* handle, const apr_dbd_driver_t* driver, const char* sql) { int nrows; apr_status_t rv; rv = apr_dbd_query(driver, handle, &nrows, sql); ABTS_ASSERT(tc, sql, rv == APR_SUCCESS); } static void create_table(abts_case *tc, apr_dbd_t* handle, const apr_dbd_driver_t* driver) { const char *sql = "CREATE TABLE apr_dbd_test (" "col1 varchar(40) not null," "col2 varchar(40)," "col3 integer)"; test_statement(tc, handle, driver, sql); } static void drop_table(abts_case *tc, apr_dbd_t* handle, const apr_dbd_driver_t* driver) { const char *sql = "DROP TABLE apr_dbd_test"; test_statement(tc, handle, driver, sql); } static void delete_rows(abts_case *tc, apr_dbd_t* handle, const apr_dbd_driver_t* driver) { const char *sql = "DELETE FROM apr_dbd_test"; test_statement(tc, handle, driver, sql); } static void insert_data(abts_case *tc, apr_dbd_t* handle, const apr_dbd_driver_t* driver, int count) { apr_pool_t* pool = p; const char* sql = "INSERT INTO apr_dbd_test VALUES('%d', '%d', %d)"; char* sqf = NULL; int i; int nrows; apr_status_t rv; for (i=0; i<count; i++) { sqf = apr_psprintf(pool, sql, i, i, i); rv = apr_dbd_query(driver, handle, &nrows, sqf); ABTS_ASSERT(tc, sqf, rv == APR_SUCCESS); ABTS_ASSERT(tc, sqf, 1 == nrows); } } static void select_rows(abts_case *tc, apr_dbd_t* handle, const apr_dbd_driver_t* driver, int count) { apr_status_t rv; apr_pool_t* pool = p; apr_pool_t* tpool; const char* sql = "SELECT * FROM apr_dbd_test ORDER BY col1"; apr_dbd_results_t *res = NULL; apr_dbd_row_t *row = NULL; int i; rv = apr_dbd_select(driver, pool, handle, &res, sql, 0); ABTS_ASSERT(tc, sql, rv == APR_SUCCESS); ABTS_PTR_NOTNULL(tc, res); apr_pool_create(&tpool, pool); i = count; while (i > 0) { row = NULL; rv = apr_dbd_get_row(driver, pool, res, &row, -1); ABTS_ASSERT(tc, sql, rv == APR_SUCCESS); ABTS_PTR_NOTNULL(tc, row); apr_pool_clear(tpool); i--; } ABTS_ASSERT(tc, "Missing Rows!", i == 0); res = NULL; i = count; rv = apr_dbd_select(driver, pool, handle, &res, sql, 1); ABTS_ASSERT(tc, sql, rv == APR_SUCCESS); ABTS_PTR_NOTNULL(tc, res); rv = apr_dbd_num_tuples(driver, res); ABTS_ASSERT(tc, "invalid row count", rv == count); while (i > 0) { row = NULL; rv = apr_dbd_get_row(driver, pool, res, &row, i); ABTS_ASSERT(tc, sql, rv == APR_SUCCESS); ABTS_PTR_NOTNULL(tc, row); apr_pool_clear(tpool); i--; } ABTS_ASSERT(tc, "Missing Rows!", i == 0); rv = apr_dbd_get_row(driver, pool, res, &row, count+100); ABTS_ASSERT(tc, "If we overseek, get_row should return -1", rv == -1); } static void test_escape(abts_case *tc, apr_dbd_t *handle, const apr_dbd_driver_t *driver) { const char *escaped = apr_dbd_escape(driver, p, "foo'bar", handle); ABTS_STR_EQUAL(tc, "foo''bar", escaped); } static void test_dbd_generic(abts_case *tc, apr_dbd_t* handle, const apr_dbd_driver_t* driver) { void* native; apr_pool_t *pool = p; apr_status_t rv; native = apr_dbd_native_handle(driver, handle); ABTS_PTR_NOTNULL(tc, native); rv = apr_dbd_check_conn(driver, pool, handle); create_table(tc, handle, driver); select_rows(tc, handle, driver, 0); insert_data(tc, handle, driver, 5); select_rows(tc, handle, driver, 5); delete_rows(tc, handle, driver); select_rows(tc, handle, driver, 0); drop_table(tc, handle, driver); test_escape(tc, handle, driver); rv = apr_dbd_close(driver, handle); ABTS_ASSERT(tc, "failed to close database", rv == APR_SUCCESS); } #endif #if APU_HAVE_SQLITE2 static void test_dbd_sqlite2(abts_case *tc, void *data) { apr_pool_t *pool = p; apr_status_t rv; const apr_dbd_driver_t* driver = NULL; apr_dbd_t* handle = NULL; rv = apr_dbd_get_driver(pool, "sqlite2", &driver); ABTS_ASSERT(tc, "failed to fetch driver", rv == APR_SUCCESS); ABTS_PTR_NOTNULL(tc, driver); ABTS_STR_EQUAL(tc, apr_dbd_name(driver), "sqlite2"); rv = apr_dbd_open(driver, pool, "data/sqlite2.db:600", &handle); ABTS_ASSERT(tc, "failed to open database", rv == APR_SUCCESS); ABTS_PTR_NOTNULL(tc, handle); test_dbd_generic(tc, handle, driver); } #endif #if APU_HAVE_SQLITE3 static void test_dbd_sqlite3(abts_case *tc, void *data) { apr_pool_t *pool = p; apr_status_t rv; const apr_dbd_driver_t* driver = NULL; apr_dbd_t* handle = NULL; rv = apr_dbd_get_driver(pool, "sqlite3", &driver); ABTS_ASSERT(tc, "failed to fetch driver", rv == APR_SUCCESS); ABTS_PTR_NOTNULL(tc, driver); ABTS_STR_EQUAL(tc, apr_dbd_name(driver), "sqlite3"); rv = apr_dbd_open(driver, pool, "data/sqlite3.db", &handle); ABTS_ASSERT(tc, "failed to open database", rv == APR_SUCCESS); ABTS_PTR_NOTNULL(tc, handle); test_dbd_generic(tc, handle, driver); } #endif abts_suite *testdbd(abts_suite *suite) { suite = ADD_SUITE(suite); abts_run_test(suite, test_dbd_init, NULL); #if APU_HAVE_SQLITE2 abts_run_test(suite, test_dbd_sqlite2, NULL); #endif #if APU_HAVE_SQLITE3 abts_run_test(suite, test_dbd_sqlite3, NULL); #endif return suite; }
001-log4cxx
trunk/src/apr-util/test/testdbd.c
C
asf20
6,690
# -*- Makefile -*- !IF "$(OS)" == "Windows_NT" NULL= rmdir=rd /s /q !ELSE NULL=nul rmdir=deltree /y !ENDIF SILENT=@ # Default build and bind modes BUILD_MODE = release BIND_MODE = shared !IF "$(BUILD_MODE)" == "release" || "$(BUILD_MODE)" == "Release" !IF "$(BIND_MODE)" == "shared" # release shared APR_LIB_PFX = $(APR_SOURCE)\Release\lib APU_LIB_PFX = $(APU_SOURCE)\Release\lib API_LIB_PFX = $(API_SOURCE)\Release\lib CFG_CFLAGS = /MD /O2 CFG_DEFINES = /D "NDEBUG" CFG_OUTPUT = Release !ELSE !IF "$(BIND_MODE)" == "static" # release static APR_LIB_PFX = $(APR_SOURCE)\LibR\ # no line continuation APU_LIB_PFX = $(APU_SOURCE)\LibR\ # no line continuation API_LIB_PFX = $(API_SOURCE)\LibR\ # no line continuation CFG_CFLAGS = /MD /O2 CFG_DEFINES = /D "NDEBUG" /D "APR_DECLARE_STATIC" \ /D "APU_DECLARE_STATIC" /D "API_DECLARE_STATIC" CFG_API_LIB = $(API_LIB_PFX)apriconv-1.lib CFG_OUTPUT = LibR !ELSE !ERROR Unknown bind mode "$(BIND_MODE)" !ENDIF !ENDIF !ELSE !IF "$(BUILD_MODE)" == "debug" || "$(BUILD_MODE)" == "Debug" !IF "$(BIND_MODE)" == "shared" # debug shared APR_LIB_PFX = $(APR_SOURCE)\Debug\lib APU_LIB_PFX = $(APU_SOURCE)\Debug\lib API_LIB_PFX = $(API_SOURCE)\Debug\lib CFG_CFLAGS = /MDd /Zi /Od CFG_DEFINES = /D "_DEBUG" CFG_LDFLAGS = /DEBUG CFG_OUTPUT = Debug !ELSE !IF "$(BIND_MODE)" == "static" # debug static APR_LIB_PFX = $(APR_SOURCE)\LibD\ # no line continuation APU_LIB_PFX = $(APU_SOURCE)\LibD\ # no line continuation API_LIB_PFX = $(API_SOURCE)\LibD\ # no line continuation CFG_CFLAGS = /MDd /Zi /Od CFG_DEFINES = /D "_DEBUG" /D "APR_DECLARE_STATIC" \ /D "APU_DECLARE_STATIC" /D "API_DECLARE_STATIC" CFG_LDFLAGS = /DEBUG CFG_API_LIB = $(API_LIB_PFX)apriconv-1.lib CFG_OUTPUT = LibD !ELSE !ERROR Unknown bind mode "$(BIND_MODE)" !ENDIF !ENDIF !ELSE !ERROR Unknown build mode "$(BUILD_MODE)" !ENDIF !ENDIF APR_SOURCE = ..\..\apr APU_SOURCE = .. API_SOURCE = ..\..\apr-iconv OUTPUT_DIR = .\$(CFG_OUTPUT) INT_CFLAGS = /nologo $(CFG_CFLAGS) /Fp"$(OUTPUT_DIR)\iconv.pch" /YX"iconv.h" INT_INCLUDES = /I "$(APU_SOURCE)\include" /I "$(APR_SOURCE)\include" # /I "$(API_SOURCE)\include" INT_DEFINES = /D "WIN32" /D "_CONSOLE" /D "_MBCS" $(CFG_DEFINES) INT_LDFLAGS = /nologo /incremental:no /subsystem:console $(CFG_LDFLAGS) CFLAGS = /W3 ALL_CFLAGS = $(INT_CFLAGS) $(INT_INCLUDES) $(INT_DEFINES) $(CFLAGS) LDFLAGS = /WARN:0 ALL_LDFLAGS = $(INT_LDFLAGS) $(LDFLAGS) .c{$(OUTPUT_DIR)}.exe: -$(SILENT)if not exist "$(OUTPUT_DIR)\$(NULL)" mkdir "$(OUTPUT_DIR)" $(SILENT)echo Compiling and linking $@... $(SILENT)cl $(ALL_CFLAGS) /Fo"$*.obj" /Fd"$*" $< \ /link $(ALL_LDFLAGS) /out:$@ \ "$(APU_LIB_PFX)aprutil-1.lib" \ "$(APR_LIB_PFX)apr-1.lib" \ "$(CFG_API)" \ kernel32.lib advapi32.lib ws2_32.lib mswsock.lib ##!ALL_TARGETS = $(OUTPUT_DIR)\testdate.exe \ ##! $(OUTPUT_DIR)\testdbm.exe \ ##! $(OUTPUT_DIR)\testmd4.exe \ ##! $(OUTPUT_DIR)\testmd5.exe \ ##! $(OUTPUT_DIR)\testqueue.exe \ ##! $(OUTPUT_DIR)\testreslist.exe \ ##! $(OUTPUT_DIR)\testrmm.exe \ ##! $(OUTPUT_DIR)\teststrmatch.exe \ ##! $(OUTPUT_DIR)\testuri.exe \ ##! $(OUTPUT_DIR)\testuuid.exe \ ##! $(OUTPUT_DIR)\testxlate.exe \ ##! $(OUTPUT_DIR)\testxml.exe ALL_TARGETS = $(OUTPUT_DIR)\testxlate.exe \ $(OUTPUT_DIR)\testdbm.exe \ $(OUTPUT_DIR)\testqueue.exe \ $(OUTPUT_DIR)\testrmm.exe \ $(OUTPUT_DIR)\testmd4.exe \ $(OUTPUT_DIR)\testmd5.exe \ $(OUTPUT_DIR)\testxml.exe all: $(ALL_TARGETS) clean: -$(SILENT)if exist "$(OUTPUT_DIR)/$(NULL)" $(rmdir) $(OUTPUT_DIR)
001-log4cxx
trunk/src/apr-util/test/Makefile.win
Makefile
asf20
3,545
/* Copyright 2000-2005 The Apache Software Foundation or its licensors, as * applicable. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <stdio.h> #include <stdlib.h> #include "abts.h" #include "testutil.h" #include "apr_pools.h" apr_pool_t *p; void apr_assert_success(abts_case* tc, const char* context, apr_status_t rv) { if (rv == APR_ENOTIMPL) { ABTS_NOT_IMPL(tc, context); } if (rv != APR_SUCCESS) { char buf[STRING_MAX], ebuf[128]; sprintf(buf, "%s (%d): %s\n", context, rv, apr_strerror(rv, ebuf, sizeof ebuf)); ABTS_FAIL(tc, buf); } } void initialize(void) { if (apr_initialize() != APR_SUCCESS) { abort(); } atexit(apr_terminate); apr_pool_create(&p, NULL); apr_pool_tag(p, "apr-util global test pool"); }
001-log4cxx
trunk/src/apr-util/test/testutil.c
C
asf20
1,342
/* Copyright 2000-2005 The Apache Software Foundation or its licensors, as * applicable. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "apr.h" #include "apr_general.h" #include "apr_xml.h" #if APR_HAVE_STDLIB_H #include <stdlib.h> /* for exit() */ #endif static const char *progname; static const char *usage = "%s [xmlfile]\nIt will create " "a dummy XML file if none is supplied"; /* * If our platform knows about the tmpnam() external buffer size, create * a buffer to pass in. This is needed in a threaded environment, or * one that thinks it is (like HP-UX). */ #ifdef L_tmpnam static char tname_buf[L_tmpnam]; #else static char *tname_buf = NULL; #endif static apr_status_t create_dummy_file_error(apr_pool_t *p, apr_file_t **fd) { apr_status_t rv; char *tmpfile; int i; apr_off_t off = 0L; tmpfile = tmpnam(tname_buf); if ((tmpfile == NULL) || (*tmpfile == '\0')) { fprintf(stderr, "unable to generate temporary filename\n"); if (errno == 0) { errno = ENOENT; } perror("tmpnam"); return APR_ENOENT; } rv = apr_file_open(fd, tmpfile, APR_CREATE|APR_TRUNCATE|APR_DELONCLOSE| APR_READ|APR_WRITE|APR_EXCL, APR_OS_DEFAULT, p); if (rv != APR_SUCCESS) return rv; rv = apr_file_puts("<?xml version=\"1.0\" ?>\n<maryx>" "<had a=\"little\"/><lamb its='fleece " "was white as snow' />\n", *fd); if (rv != APR_SUCCESS) return rv; for (i = 0; i < 5000; i++) { rv = apr_file_puts("<hmm roast=\"lamb\" " "for=\"dinner\">yummy</hmm>\n", *fd); if (rv != APR_SUCCESS) return rv; } rv = apr_file_puts("</mary>\n", *fd); if (rv != APR_SUCCESS) return rv; return apr_file_seek(*fd, APR_SET, &off); } static apr_status_t create_dummy_file(apr_pool_t *p, apr_file_t **fd) { apr_status_t rv; char *tmpfile; int i; apr_off_t off = 0L; tmpfile = tmpnam(tname_buf); if ((tmpfile == NULL) || (*tmpfile == '\0')) { fprintf(stderr, "unable to generate temporary filename\n"); if (errno == 0) { errno = ENOENT; } perror("tmpnam"); return APR_ENOENT; } rv = apr_file_open(fd, tmpfile, APR_CREATE|APR_TRUNCATE|APR_DELONCLOSE| APR_READ|APR_WRITE|APR_EXCL, APR_OS_DEFAULT, p); if (rv != APR_SUCCESS) return rv; rv = apr_file_puts("<?xml version=\"1.0\" ?>\n<mary>" "<had a=\"little\"/><lamb its='fleece " "was white as snow' />\n", *fd); if (rv != APR_SUCCESS) return rv; for (i = 0; i < 5000; i++) { rv = apr_file_puts("<hmm roast=\"lamb\" " "for=\"dinner\">yummy</hmm>\n", *fd); if (rv != APR_SUCCESS) return rv; } rv = apr_file_puts("</mary>\n", *fd); if (rv != APR_SUCCESS) return rv; rv = apr_file_seek(*fd, APR_SET, &off); return rv; } static void dump_xml(apr_xml_elem *e, int level) { apr_xml_attr *a; apr_xml_elem *ec; printf("%d: element %s\n", level, e->name); if (e->attr) { a = e->attr; printf("%d:\tattrs\t", level); while (a) { printf("%s=%s\t", a->name, a->value); a = a->next; } printf("\n"); } if (e->first_child) { ec = e->first_child; while (ec) { dump_xml(ec, level + 1); ec = ec->next; } } } static void oops(const char *s1, const char *s2, apr_status_t rv) { if (progname) fprintf(stderr, "%s: ", progname); fprintf(stderr, s1, s2); if (rv != APR_SUCCESS) { char buf[120]; fprintf(stderr, " (%s)", apr_strerror(rv, buf, sizeof buf)); } fprintf(stderr, "\n"); exit(1); } int main(int argc, const char *const * argv) { apr_pool_t *pool; apr_file_t *fd; apr_xml_parser *parser; apr_xml_doc *doc; apr_status_t rv; char errbuf[2000]; char errbufXML[2000]; (void) apr_initialize(); apr_pool_create(&pool, NULL); progname = argv[0]; if (argc == 1) { rv = create_dummy_file(pool, &fd); if (rv != APR_SUCCESS) { oops("cannot create dummy file", "oops", rv); } } else { if (argc == 2) { rv = apr_file_open(&fd, argv[1], APR_READ, APR_OS_DEFAULT, pool); if (rv != APR_SUCCESS) { oops("cannot open: %s", argv[1], rv); } } else { oops("usage: %s", usage, 0); } } rv = apr_xml_parse_file(pool, &parser, &doc, fd, 2000); if (rv != APR_SUCCESS) { fprintf(stderr, "APR Error %s\nXML Error: %s\n", apr_strerror(rv, errbuf, sizeof(errbuf)), apr_xml_parser_geterror(parser, errbufXML, sizeof(errbufXML))); return rv; } dump_xml(doc->root, 0); apr_file_close(fd); if (argc == 1) { rv = create_dummy_file_error(pool, &fd); if (rv != APR_SUCCESS) { oops("cannot create error dummy file", "oops", rv); } rv = apr_xml_parse_file(pool, &parser, &doc, fd, 2000); if (rv != APR_SUCCESS) { fprintf(stdout, "APR Error %s\nXML Error: %s " "(EXPECTED) This is good.\n", apr_strerror(rv, errbuf, sizeof(errbuf)), apr_xml_parser_geterror(parser, errbufXML, sizeof(errbufXML))); rv = APR_SUCCESS; /* reset the return code, as the test is supposed to get this error */ } else { fprintf(stderr, "Expected an error, but didn't get one ;( "); return APR_EGENERAL; } } apr_pool_destroy(pool); apr_terminate(); return rv; }
001-log4cxx
trunk/src/apr-util/test/testxml.c
C
asf20
6,436
/* Copyright 2000-2004 Ryan Bloom * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifdef __cplusplus extern "C" { #endif #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #ifndef ABTS_H #define ABTS_H #ifndef FALSE #define FALSE 0 #endif #ifndef TRUE #define TRUE 1 #endif struct sub_suite { const char *name; int num_test; int failed; int not_run; int not_impl; struct sub_suite *next; }; typedef struct sub_suite sub_suite; struct abts_suite { sub_suite *head; sub_suite *tail; }; typedef struct abts_suite abts_suite; struct abts_case { int failed; sub_suite *suite; }; typedef struct abts_case abts_case; typedef void (*test_func)(abts_case *tc, void *data); #define ADD_SUITE(suite) abts_add_suite(suite, __FILE__); abts_suite *abts_add_suite(abts_suite *suite, const char *suite_name); void abts_run_test(abts_suite *ts, test_func f, void *value); void abts_log_message(const char *fmt, ...); void abts_int_equal(abts_case *tc, const int expected, const int actual, int lineno); void abts_int_nequal(abts_case *tc, const int expected, const int actual, int lineno); void abts_str_equal(abts_case *tc, const char *expected, const char *actual, int lineno); void abts_str_nequal(abts_case *tc, const char *expected, const char *actual, size_t n, int lineno); void abts_ptr_notnull(abts_case *tc, const void *ptr, int lineno); void abts_ptr_equal(abts_case *tc, const void *expected, const void *actual, int lineno); void abts_true(abts_case *tc, int condition, int lineno); void abts_fail(abts_case *tc, const char *message, int lineno); void abts_not_impl(abts_case *tc, const char *message, int lineno); void abts_assert(abts_case *tc, const char *message, int condition, int lineno); /* Convenience macros. Ryan hates these! */ #define ABTS_INT_EQUAL(a, b, c) abts_int_equal(a, b, c, __LINE__) #define ABTS_INT_NEQUAL(a, b, c) abts_int_nequal(a, b, c, __LINE__) #define ABTS_STR_EQUAL(a, b, c) abts_str_equal(a, b, c, __LINE__) #define ABTS_STR_NEQUAL(a, b, c, d) abts_str_nequal(a, b, c, d, __LINE__) #define ABTS_PTR_NOTNULL(a, b) abts_ptr_notnull(a, b, __LINE__) #define ABTS_PTR_EQUAL(a, b, c) abts_ptr_equal(a, b, c, __LINE__) #define ABTS_TRUE(a, b) abts_true(a, b, __LINE__); #define ABTS_FAIL(a, b) abts_fail(a, b, __LINE__); #define ABTS_NOT_IMPL(a, b) abts_not_impl(a, b, __LINE__); #define ABTS_ASSERT(a, b, c) abts_assert(a, b, c, __LINE__); abts_suite *run_tests(abts_suite *suite); abts_suite *run_tests1(abts_suite *suite); #endif #ifdef __cplusplus } #endif
001-log4cxx
trunk/src/apr-util/test/abts.h
C
asf20
3,164
/* Copyright 2002-2005 The Apache Software Foundation or its licensors, as * applicable. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* Setup: * - Create or edit the file data/host.data and add an * ldap server DN. Multiple DNs may be listed on * a single line. * - Copy the server certificates to the data/ directory. * All DER type certificates must have the .der extention. * All BASE64 or PEM certificates must have the .b64 * extension. All certificate files copied to the /data * directory will be added to the ldap certificate store. */ /* This test covers the following three types of connections: * - Unsecure ldap:// * - Secure ldaps:// * - Secure ldap://+Start_TLS * * - (TBD) Mutual authentication * * There are other variations that should be tested: * - All of the above with multiple redundant LDAP servers * This can be done by listing more than one server DN * in the host.data file. The DNs should all be listed * on one line separated by a space. * - All of the above with multiple certificates * If more than one certificate is found in the data/ * directory, each certificate found will be added * to the certificate store. * - All of the above on alternate ports * An alternate port can be specified as part of the * host in the host.data file. The ":port" should * follow each DN listed. Default is 389 and 636. * - Secure connections with mutual authentication */ #include "testutil.h" #include "apr.h" #include "apr_general.h" #include "apr_ldap.h" #include "apr_file_io.h" #include "apr_file_info.h" #include "apr_strings.h" #if APR_HAVE_STDLIB_H #include <stdlib.h> #endif #define APR_WANT_STDIO #define APR_WANT_STRFUNC #include "apr_want.h" #define DIRNAME "data" #define FILENAME DIRNAME "/host.data" #define CERTFILEDER DIRNAME "/*.der" #define CERTFILEB64 DIRNAME "/*.b64" #if APR_HAS_LDAP static char ldap_host[256]; static int get_ldap_host(void) { apr_status_t rv; apr_file_t *thefile = NULL; char *ptr; ldap_host[0] = '\0'; rv = apr_file_open(&thefile, FILENAME, APR_READ, APR_UREAD | APR_UWRITE | APR_GREAD, p); if (rv != APR_SUCCESS) { return 0; } rv = apr_file_gets(ldap_host, sizeof(ldap_host), thefile); if (rv != APR_SUCCESS) { return 0; } ptr = strstr (ldap_host, "\r\n"); if (ptr) { *ptr = '\0'; } apr_file_close(thefile); return 1; } static int add_ldap_certs(abts_case *tc) { apr_status_t status; apr_dir_t *thedir; apr_finfo_t dirent; apr_ldap_err_t *result = NULL; if ((status = apr_dir_open(&thedir, DIRNAME, p)) == APR_SUCCESS) { apr_ldap_opt_tls_cert_t *cert = (apr_ldap_opt_tls_cert_t *)apr_pcalloc(p, sizeof(apr_ldap_opt_tls_cert_t)); do { status = apr_dir_read(&dirent, APR_FINFO_MIN | APR_FINFO_NAME, thedir); if (APR_STATUS_IS_INCOMPLETE(status)) { continue; /* ignore un-stat()able files */ } else if (status != APR_SUCCESS) { break; } if (strstr(dirent.name, ".der")) { cert->type = APR_LDAP_CA_TYPE_DER; cert->path = apr_pstrcat (p, DIRNAME, "/", dirent.name, NULL); apr_ldap_set_option(p, NULL, APR_LDAP_OPT_TLS_CERT, (void *)cert, &result); ABTS_TRUE(tc, result->rc == LDAP_SUCCESS); } if (strstr(dirent.name, ".b64")) { cert->type = APR_LDAP_CA_TYPE_BASE64; cert->path = apr_pstrcat (p, DIRNAME, "/", dirent.name, NULL); apr_ldap_set_option(p, NULL, APR_LDAP_OPT_TLS_CERT, (void *)cert, &result); ABTS_TRUE(tc, result->rc == LDAP_SUCCESS); } } while (1); apr_dir_close(thedir); } return 0; } static void test_ldap_connection(abts_case *tc, LDAP *ldap) { int version = LDAP_VERSION3; int failures, result; /* always default to LDAP V3 */ ldap_set_option(ldap, LDAP_OPT_PROTOCOL_VERSION, &version); for (failures=0; failures<10; failures++) { result = ldap_simple_bind_s(ldap, (char *)NULL, (char *)NULL); if (LDAP_SERVER_DOWN != result) break; } ABTS_TRUE(tc, result == LDAP_SUCCESS); if (result != LDAP_SUCCESS) { abts_log_message("%s\n", ldap_err2string(result)); } ldap_unbind_s(ldap); return; } static void test_ldap(abts_case *tc, void *data) { apr_pool_t *pool = p; LDAP *ldap; apr_ldap_err_t *result = NULL; ABTS_ASSERT(tc, "failed to get host", ldap_host[0] != '\0'); apr_ldap_init(pool, &ldap, ldap_host, LDAP_PORT, APR_LDAP_NONE, &(result)); ABTS_TRUE(tc, ldap != NULL); ABTS_PTR_NOTNULL(tc, result); if (result->rc == LDAP_SUCCESS) { test_ldap_connection(tc, ldap); } } static void test_ldaps(abts_case *tc, void *data) { apr_pool_t *pool = p; LDAP *ldap; apr_ldap_err_t *result = NULL; apr_ldap_init(pool, &ldap, ldap_host, LDAPS_PORT, APR_LDAP_SSL, &(result)); ABTS_TRUE(tc, ldap != NULL); ABTS_PTR_NOTNULL(tc, result); if (result->rc == LDAP_SUCCESS) { add_ldap_certs(tc); test_ldap_connection(tc, ldap); } } static void test_ldap_tls(abts_case *tc, void *data) { apr_pool_t *pool = p; LDAP *ldap; apr_ldap_err_t *result = NULL; apr_ldap_init(pool, &ldap, ldap_host, LDAP_PORT, APR_LDAP_STARTTLS, &(result)); ABTS_TRUE(tc, ldap != NULL); ABTS_PTR_NOTNULL(tc, result); if (result->rc == LDAP_SUCCESS) { add_ldap_certs(tc); test_ldap_connection(tc, ldap); } } #endif /* APR_HAS_LDAP */ abts_suite *testldap(abts_suite *suite) { #if APR_HAS_LDAP apr_ldap_err_t *result = NULL; suite = ADD_SUITE(suite); apr_ldap_ssl_init(p, NULL, 0, &result); if (get_ldap_host()) { abts_run_test(suite, test_ldap, NULL); abts_run_test(suite, test_ldaps, NULL); abts_run_test(suite, test_ldap_tls, NULL); } #endif /* APR_HAS_LDAP */ return suite; }
001-log4cxx
trunk/src/apr-util/test/testldap.c
C
asf20
6,940
/* This program tests the date_parse_http routine in ../main/util_date.c. * * It is only semiautomated in that I would run it, modify the code to * use a different algorithm or seed, recompile and run again, etc. * Obviously it should use an argument for that, but I never got around * to changing the implementation. * * gcc -g -O2 -I../main -o test_date ../main/util_date.o test_date.c * test_date | egrep '^No ' * * Roy Fielding, 1996 */ #include <stdio.h> #include <stdlib.h> #include <time.h> #include "apr_date.h" #ifndef srand48 #define srand48 srandom #endif #ifndef mrand48 #define mrand48 random #endif void gm_timestr_822(char *ts, apr_time_t sec); void gm_timestr_850(char *ts, apr_time_t sec); void gm_timestr_ccc(char *ts, apr_time_t sec); static const apr_time_t year2secs[] = { 0LL, /* 1970 */ 31536000LL, /* 1971 */ 63072000LL, /* 1972 */ 94694400LL, /* 1973 */ 126230400LL, /* 1974 */ 157766400LL, /* 1975 */ 189302400LL, /* 1976 */ 220924800LL, /* 1977 */ 252460800LL, /* 1978 */ 283996800LL, /* 1979 */ 315532800LL, /* 1980 */ 347155200LL, /* 1981 */ 378691200LL, /* 1982 */ 410227200LL, /* 1983 */ 441763200LL, /* 1984 */ 473385600LL, /* 1985 */ 504921600LL, /* 1986 */ 536457600LL, /* 1987 */ 567993600LL, /* 1988 */ 599616000LL, /* 1989 */ 631152000LL, /* 1990 */ 662688000LL, /* 1991 */ 694224000LL, /* 1992 */ 725846400LL, /* 1993 */ 757382400LL, /* 1994 */ 788918400LL, /* 1995 */ 820454400LL, /* 1996 */ 852076800LL, /* 1997 */ 883612800LL, /* 1998 */ 915148800LL, /* 1999 */ 946684800LL, /* 2000 */ 978307200LL, /* 2001 */ 1009843200LL, /* 2002 */ 1041379200LL, /* 2003 */ 1072915200LL, /* 2004 */ 1104537600LL, /* 2005 */ 1136073600LL, /* 2006 */ 1167609600LL, /* 2007 */ 1199145600LL, /* 2008 */ 1230768000LL, /* 2009 */ 1262304000LL, /* 2010 */ 1293840000LL, /* 2011 */ 1325376000LL, /* 2012 */ 1356998400LL, /* 2013 */ 1388534400LL, /* 2014 */ 1420070400LL, /* 2015 */ 1451606400LL, /* 2016 */ 1483228800LL, /* 2017 */ 1514764800LL, /* 2018 */ 1546300800LL, /* 2019 */ 1577836800LL, /* 2020 */ 1609459200LL, /* 2021 */ 1640995200LL, /* 2022 */ 1672531200LL, /* 2023 */ 1704067200LL, /* 2024 */ 1735689600LL, /* 2025 */ 1767225600LL, /* 2026 */ 1798761600LL, /* 2027 */ 1830297600LL, /* 2028 */ 1861920000LL, /* 2029 */ 1893456000LL, /* 2030 */ 1924992000LL, /* 2031 */ 1956528000LL, /* 2032 */ 1988150400LL, /* 2033 */ 2019686400LL, /* 2034 */ 2051222400LL, /* 2035 */ 2082758400LL, /* 2036 */ 2114380800LL, /* 2037 */ 2145916800LL /* 2038 */ }; const char month_snames[12][4] = { "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec" }; void gm_timestr_822(char *ts, apr_time_t sec) { static const char *const days[7]= {"Sun","Mon", "Tue", "Wed", "Thu", "Fri", "Sat"}; struct tm *tms; time_t ls = (time_t)sec; tms = gmtime(&ls); sprintf(ts, "%s, %.2d %s %d %.2d:%.2d:%.2d GMT", days[tms->tm_wday], tms->tm_mday, month_snames[tms->tm_mon], tms->tm_year + 1900, tms->tm_hour, tms->tm_min, tms->tm_sec); } void gm_timestr_850(char *ts, apr_time_t sec) { static const char *const days[7]= {"Sunday","Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}; struct tm *tms; int year; time_t ls = (time_t)sec; tms = gmtime(&ls); year = tms->tm_year; if (year >= 100) year -= 100; sprintf(ts, "%s, %.2d-%s-%.2d %.2d:%.2d:%.2d GMT", days[tms->tm_wday], tms->tm_mday, month_snames[tms->tm_mon], year, tms->tm_hour, tms->tm_min, tms->tm_sec); } void gm_timestr_ccc(char *ts, apr_time_t sec) { static const char *const days[7]= {"Sun","Mon", "Tue", "Wed", "Thu", "Fri", "Sat"}; struct tm *tms; time_t ls = (time_t)sec; tms = gmtime(&ls); sprintf(ts, "%s %s %2d %.2d:%.2d:%.2d %d", days[tms->tm_wday], month_snames[tms->tm_mon], tms->tm_mday, tms->tm_hour, tms->tm_min, tms->tm_sec, tms->tm_year + 1900); } int main (void) { int year, i; apr_time_t guess; apr_time_t offset = 0; /* apr_time_t offset = 0; */ /* apr_time_t offset = ((31 + 28) * 24 * 3600) - 1; */ apr_time_t secstodate, newsecs; char datestr[50]; for (year = 1970; year < 2038; ++year) { secstodate = year2secs[year - 1970] + offset; gm_timestr_822(datestr, secstodate); secstodate *= APR_USEC_PER_SEC; newsecs = apr_date_parse_http(datestr); if (secstodate == newsecs) printf("Yes %4d %19" APR_TIME_T_FMT " %s\n", year, secstodate, datestr); else if (newsecs == APR_DATE_BAD) printf("No %4d %19" APR_TIME_T_FMT " %19" APR_TIME_T_FMT " %s\n", year, secstodate, newsecs, datestr); else printf("No* %4d %19" APR_TIME_T_FMT " %19" APR_TIME_T_FMT " %s\n", year, secstodate, newsecs, datestr); } srand48(978245L); for (i = 0; i < 10000; ++i) { guess = (time_t)mrand48(); if (guess < 0) guess *= -1; secstodate = guess + offset; gm_timestr_822(datestr, secstodate); secstodate *= APR_USEC_PER_SEC; newsecs = apr_date_parse_http(datestr); if (secstodate == newsecs) printf("Yes %" APR_TIME_T_FMT " %s\n", secstodate, datestr); else if (newsecs == APR_DATE_BAD) printf("No %" APR_TIME_T_FMT " %" APR_TIME_T_FMT " %s\n", secstodate, newsecs, datestr); else printf("No* %" APR_TIME_T_FMT " %" APR_TIME_T_FMT " %s\n", secstodate, newsecs, datestr); } exit(0); }
001-log4cxx
trunk/src/apr-util/test/testdate.c
C
asf20
6,158
/* Copyright 2000-2005 The Apache Software Foundation or its licensors, as * applicable. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* This file came from the SDBM package (written by oz@nexus.yorku.ca). * That package was under public domain. This file has been ported to * APR, updated to ANSI C and other, newer idioms, and added to the Apache * codebase under the above copyright and license. */ /* * testdbm: Simple APR dbm tester. * Automatic test case: ./testdbm auto foo * - Attempts to store and fetch values from the DBM. * * Run the program for more help. */ #include "apr.h" #include "apr_general.h" #include "apr_pools.h" #include "apr_errno.h" #include "apr_getopt.h" #include "apr_time.h" #define APR_WANT_STRFUNC #include "apr_want.h" #if APR_HAVE_STDIO_H #include <stdio.h> #endif #if APR_HAVE_UNISTD_H #include <unistd.h> #endif #include <stdlib.h> /* for atexit(), malloc() */ #include <string.h> #include "apr_dbm.h" static const char *progname; static int rflag; #define DERROR 0 #define DLOOK 1 #define DDELETE 3 #define DCAT 4 #define DBUILD 5 #define DPRESS 6 #define DCREAT 7 #define DNAME 8 #define DTRUNC 9 #define DAUTO 10 #define LINEMAX 8192 typedef struct { const char *sname; int scode; int flags; } cmd; static const cmd cmds[] = { { "fetch", DLOOK, APR_DBM_READONLY }, { "get", DLOOK, APR_DBM_READONLY }, { "look", DLOOK, APR_DBM_READONLY }, { "add", DBUILD, APR_DBM_READWRITE }, { "insert", DBUILD, APR_DBM_READWRITE }, { "store", DBUILD, APR_DBM_READWRITE }, { "delete", DDELETE, APR_DBM_READWRITE }, { "remove", DDELETE, APR_DBM_READWRITE }, { "dump", DCAT, APR_DBM_READONLY }, { "list", DCAT, APR_DBM_READONLY }, { "cat", DCAT, APR_DBM_READONLY }, { "build", DBUILD, APR_DBM_RWCREATE }, /** this one creates the DB */ { "creat", DCREAT, APR_DBM_RWCREATE }, { "trunc", DTRUNC, APR_DBM_RWTRUNC }, { "new", DCREAT, APR_DBM_RWCREATE }, { "names", DNAME, APR_DBM_READONLY }, #if 0 {"squash", DPRESS, APR_DBM_READWRITE, }, {"compact", DPRESS, APR_DBM_READWRITE, }, {"compress", DPRESS, APR_DBM_READWRITE, }, #endif { "auto", DAUTO, APR_DBM_RWCREATE }, }; #define CMD_SIZE (sizeof(cmds)/sizeof(cmd)) static void doit(const cmd *act, const char*type, const char *file, apr_pool_t *pool); static const cmd *parse_command(const char *str); static void prdatum(FILE *stream, apr_datum_t d); static void oops(apr_dbm_t *dbm, apr_status_t rv, const char *s1, const char *s2); static void show_usage(void); int main(int argc, const char * const * argv) { apr_pool_t *pool; const cmd *act; apr_getopt_t *os; char optch; const char *optarg; const char*dbtype; (void) apr_initialize(); apr_pool_create(&pool, NULL); atexit(apr_terminate); (void) apr_getopt_init(&os, pool, argc, argv); progname = argv[0]; dbtype = "default"; while (apr_getopt(os, "Rt:", &optch, &optarg) == APR_SUCCESS) { switch (optch) { case 'R': /* raw processing */ rflag++; break; case 't': dbtype = optarg; break; default: show_usage(); fputs("unknown option.",stderr); exit(-1); break; } } if (argc <= os->ind) { show_usage(); fputs("Note: If you have no clue what this program is, start with:\n", stderr); fputs(" ./testdbm auto foo\n", stderr); fputs(" where foo is the DBM prefix.\n", stderr); exit(-2); } if ((act = parse_command(argv[os->ind])) == NULL) { show_usage(); fprintf(stderr, "unrecognized command: %s\n", argv[os->ind]); exit(-3); } if (++os->ind >= argc) { show_usage(); fputs("please supply a DB file to use (may be created)\n", stderr); exit(-4); } doit(act, dbtype, argv[os->ind], pool); apr_pool_destroy(pool); return 0; } static void doit(const cmd *act, const char*type, const char *file, apr_pool_t *pool) { apr_status_t rv; apr_datum_t key; apr_datum_t val; apr_dbm_t *db; char *op; int n; char *line; const char *use1; const char *use2; #ifdef TIME long start; extern long time(); #endif rv = apr_dbm_open_ex(&db, type, file, act->flags, APR_OS_DEFAULT, pool); if (rv != APR_SUCCESS) oops(db, rv, "cannot open: %s", file); line = (char *) apr_palloc(pool,LINEMAX); switch (act->scode) { case DLOOK: while (fgets(line, LINEMAX, stdin) != NULL) { n = strlen(line) - 1; line[n] = 0; if (n == 0) break; key.dptr = line; key.dsize = n; rv = apr_dbm_fetch(db, key, &val); if (rv == APR_SUCCESS) { prdatum(stdout, val); putchar('\n'); continue; } prdatum(stderr, key); fprintf(stderr, ": not found.\n"); } break; case DDELETE: while (fgets(line, LINEMAX, stdin) != NULL) { n = strlen(line) - 1; line[n] = 0; if (n == 0) break; key.dptr = line; key.dsize = n; if (apr_dbm_delete(db, key) != APR_SUCCESS) { prdatum(stderr, key); fprintf(stderr, ": not found.\n"); } } break; case DCAT: rv = apr_dbm_firstkey(db, &key); if (rv != APR_SUCCESS) oops(db, rv, "could not fetch first key: %s", file); while (key.dptr != NULL) { prdatum(stdout, key); putchar('\t'); rv = apr_dbm_fetch(db, key, &val); if (rv != APR_SUCCESS) oops(db, rv, "apr_dbm_fetch", "failure"); prdatum(stdout, val); putchar('\n'); rv = apr_dbm_nextkey(db, &key); if (rv != APR_SUCCESS) oops(db, rv, "NextKey", "failure"); } break; case DBUILD: #ifdef TIME start = time(0); #endif while (fgets(line, LINEMAX, stdin) != NULL) { n = strlen(line) - 1; line[n] = 0; if (n == 0) break; key.dptr = line; if ((op = strchr(line, '\t')) != 0) { key.dsize = op - line; *op++ = 0; val.dptr = op; val.dsize = line + n - op; } else oops(NULL, APR_EGENERAL, "bad input: %s", line); rv = apr_dbm_store(db, key, val); if (rv != APR_SUCCESS) { prdatum(stderr, key); fprintf(stderr, ": "); oops(db, rv, "store: %s", "failed"); } } #ifdef TIME printf("done: %d seconds.\n", time(0) - start); #endif break; case DPRESS: break; case DCREAT: break; case DTRUNC: break; case DNAME: apr_dbm_get_usednames(pool, file, &use1, &use2); fprintf(stderr, "%s %s\n", use1, use2); break; case DAUTO: { int i; char *valdata = "0123456789"; fprintf(stderr, "Generating data: "); for (i = 0; i < 10; i++) { int j; char c, keydata[10]; for (j = 0, c = 'A' + (i % 16); j < 10; j++, c++) { keydata[j] = c; } key.dptr = keydata; key.dsize = 10; val.dptr = valdata; val.dsize = 10; rv = apr_dbm_store(db, key, val); if (rv != APR_SUCCESS) { prdatum(stderr, key); fprintf(stderr, ": "); oops(db, rv, "store: %s", "failed"); } } fputs("OK\n", stderr); fputs("Testing existence/retrieval: ", stderr); for (i = 0; i < 10; i++) { int j; char c, keydata[10]; for (j = 0, c = 'A' + (i % 16); j < 10; j++, c++) { keydata[j] = c; } key.dptr = keydata; key.dsize = 10; if (!apr_dbm_exists(db, key)) { prdatum(stderr, key); oops(db, 0, "exists: %s", "failed"); } rv = apr_dbm_fetch(db, key, &val); if (rv != APR_SUCCESS || val.dsize != 10 || (strncmp(val.dptr, valdata, 10) != 0) ) { prdatum(stderr, key); fprintf(stderr, ": "); oops(db, rv, "fetch: %s", "failed"); } } fputs("OK\n", stderr); } break; } apr_dbm_close(db); } static const cmd *parse_command(const char *str) { int i; for (i = 0; i < CMD_SIZE; i++) if (strcasecmp(cmds[i].sname, str) == 0) return &cmds[i]; return NULL; } static void prdatum(FILE *stream, apr_datum_t d) { int c; const char *p = d.dptr; int n = d.dsize; while (n--) { c = *p++ & 0377; if (c & 0200) { fprintf(stream, "M-"); c &= 0177; } if (c == 0177 || c < ' ') fprintf(stream, "^%c", (c == 0177) ? '?' : c + '@'); else putc(c, stream); } } static void oops(apr_dbm_t * dbm, apr_status_t rv, const char *s1, const char *s2) { char errbuf[200]; if (progname) { fprintf(stderr, "%s: ", progname); } fprintf(stderr, s1, s2); fprintf(stderr, "\n"); if (rv != APR_SUCCESS) { apr_strerror(rv, errbuf, sizeof(errbuf)); fprintf(stderr, "APR Error %d - %s\n", rv, errbuf); if (dbm) { apr_dbm_geterror(dbm, &rv, errbuf, sizeof(errbuf)); fprintf(stderr, "APR_DB Error %d - %s\n", rv, errbuf); } } exit(1); } static void show_usage(void) { int i; if (!progname) { progname = "testdbm"; } fprintf(stderr, "%s [-t DBM-type] [-R] [commands] dbm-file-path\n", progname); fputs("Available DBM-types:", stderr); #if APU_HAVE_GDBM fputs(" GDBM", stderr); #endif #if APU_HAVE_NDBM fputs(" NDBM", stderr); #endif #if APU_HAVE_SDBM fputs(" SDBM", stderr); #endif #if APU_HAVE_DB fputs(" DB", stderr); #endif fputs(" default\n", stderr); fputs("Available commands:\n", stderr); for (i = 0; i < CMD_SIZE; i++) { fprintf(stderr, "%-8s%c", cmds[i].sname, ((i + 1) % 6 == 0) ? '\n' : ' '); } fputs("\n", stderr); }
001-log4cxx
trunk/src/apr-util/test/testdbm.c
C
asf20
11,506
# -*- Makefile -*- !IF "$(OS)" == "Windows_NT" NULL= rmdir=rd /s /q !ELSE NULL=nul rmdir=deltree /y !ENDIF SILENT=@ # Default build and bind modes BUILD_MODE = release BIND_MODE = shared !IF "$(BUILD_MODE)" == "release" || "$(BUILD_MODE)" == "Release" !IF "$(BIND_MODE)" == "shared" # release shared APR_LIB_PFX = $(APR_SOURCE)\Release\lib APU_LIB_PFX = $(APU_SOURCE)\Release\lib API_LIB_PFX = $(API_SOURCE)\Release\lib CFG_CFLAGS = /MD /O2 CFG_DEFINES = /D "NDEBUG" CFG_OUTPUT = Release !ELSE !IF "$(BIND_MODE)" == "static" # release static APR_LIB_PFX = $(APR_SOURCE)\LibR\ # no line continuation APU_LIB_PFX = $(APU_SOURCE)\LibR\ # no line continuation API_LIB_PFX = $(API_SOURCE)\LibR\ # no line continuation CFG_CFLAGS = /MD /O2 CFG_DEFINES = /D "NDEBUG" /D "APR_DECLARE_STATIC" \ /D "APU_DECLARE_STATIC" /D "API_DECLARE_STATIC" CFG_API_LIB = $(API_LIB_PFX)apriconv-1.lib CFG_OUTPUT = LibR !ELSE !ERROR Unknown bind mode "$(BIND_MODE)" !ENDIF !ENDIF !ELSE !IF "$(BUILD_MODE)" == "debug" || "$(BUILD_MODE)" == "Debug" !IF "$(BIND_MODE)" == "shared" # debug shared APR_LIB_PFX = $(APR_SOURCE)\Debug\lib APU_LIB_PFX = $(APU_SOURCE)\Debug\lib API_LIB_PFX = $(API_SOURCE)\Debug\lib CFG_CFLAGS = /MDd /Zi /Od CFG_DEFINES = /D "_DEBUG" CFG_LDFLAGS = /DEBUG CFG_OUTPUT = Debug !ELSE !IF "$(BIND_MODE)" == "static" # debug static APR_LIB_PFX = $(APR_SOURCE)\LibD\ # no line continuation APU_LIB_PFX = $(APU_SOURCE)\LibD\ # no line continuation API_LIB_PFX = $(API_SOURCE)\LibD\ # no line continuation CFG_CFLAGS = /MDd /Zi /Od CFG_DEFINES = /D "_DEBUG" /D "APR_DECLARE_STATIC" \ /D "APU_DECLARE_STATIC" /D "API_DECLARE_STATIC" CFG_LDFLAGS = /DEBUG CFG_API_LIB = $(API_LIB_PFX)apriconv-1.lib CFG_OUTPUT = LibD !ELSE !ERROR Unknown bind mode "$(BIND_MODE)" !ENDIF !ENDIF !ELSE !ERROR Unknown build mode "$(BUILD_MODE)" !ENDIF !ENDIF APR_SOURCE = ..\..\apr APU_SOURCE = .. API_SOURCE = ..\..\apr-iconv OUTPUT_DIR = .\$(CFG_OUTPUT) INT_CFLAGS = /nologo $(CFG_CFLAGS) /Fp"$(OUTPUT_DIR)\iconv.pch" /YX"iconv.h" INT_INCLUDES = /I "$(APU_SOURCE)\include" /I "$(APR_SOURCE)\include" # /I "$(API_SOURCE)\include" INT_DEFINES = /D "WIN32" /D "_CONSOLE" /D "_MBCS" $(CFG_DEFINES) INT_LDFLAGS = /nologo /incremental:no /subsystem:console $(CFG_LDFLAGS) CFLAGS = /W3 ALL_CFLAGS = $(INT_CFLAGS) $(INT_INCLUDES) $(INT_DEFINES) $(CFLAGS) LDFLAGS = /WARN:0 ALL_LDFLAGS = $(INT_LDFLAGS) $(LDFLAGS) .c{$(OUTPUT_DIR)}.exe: -$(SILENT)if not exist "$(OUTPUT_DIR)\$(NULL)" mkdir "$(OUTPUT_DIR)" $(SILENT)echo Compiling and linking $@... $(SILENT)cl $(ALL_CFLAGS) /Fo"$*.obj" /Fd"$*" $< \ /link $(ALL_LDFLAGS) /out:$@ \ "$(APU_LIB_PFX)aprutil-1.lib" \ "$(APR_LIB_PFX)apr-1.lib" \ "$(CFG_API)" \ kernel32.lib advapi32.lib ws2_32.lib mswsock.lib ##!ALL_TARGETS = $(OUTPUT_DIR)\testdate.exe \ ##! $(OUTPUT_DIR)\testdbm.exe \ ##! $(OUTPUT_DIR)\testmd4.exe \ ##! $(OUTPUT_DIR)\testmd5.exe \ ##! $(OUTPUT_DIR)\testqueue.exe \ ##! $(OUTPUT_DIR)\testreslist.exe \ ##! $(OUTPUT_DIR)\testrmm.exe \ ##! $(OUTPUT_DIR)\teststrmatch.exe \ ##! $(OUTPUT_DIR)\testuri.exe \ ##! $(OUTPUT_DIR)\testuuid.exe \ ##! $(OUTPUT_DIR)\testxlate.exe \ ##! $(OUTPUT_DIR)\testxml.exe ALL_TARGETS = $(OUTPUT_DIR)\testxlate.exe \ $(OUTPUT_DIR)\testdbm.exe \ $(OUTPUT_DIR)\testqueue.exe \ $(OUTPUT_DIR)\testrmm.exe \ $(OUTPUT_DIR)\testmd4.exe \ $(OUTPUT_DIR)\testmd5.exe \ $(OUTPUT_DIR)\testxml.exe all: $(ALL_TARGETS) clean: -$(SILENT)if exist "$(OUTPUT_DIR)/$(NULL)" $(rmdir) $(OUTPUT_DIR)
001-log4cxx
trunk/src/apr-util/test/.svn/text-base/Makefile.win.svn-base
Makefile
asf20
3,545
/* Copyright 2000-2005 The Apache Software Foundation or its licensors, as * applicable. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef APR_TEST_INCLUDES #define APR_TEST_INCLUDES #include "abts.h" #include "testutil.h" const struct testlist { abts_suite *(*func)(abts_suite *suite); } alltests[] = { {teststrmatch}, {testuri}, {testuuid}, {testbuckets}, {testpass}, {testmd4}, {testmd5}, {testldap}, {testdbd} }; #endif /* APR_TEST_INCLUDES */
001-log4cxx
trunk/src/apr-util/test/abts_tests.h
C
asf20
1,013
/* Copyright 2000-2005 The Apache Software Foundation or its licensors, as * applicable. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <stdio.h> #include <stdlib.h> #include "apr_reslist.h" #include "apr_thread_proc.h" #if APR_HAVE_TIME_H #include <time.h> #endif /* APR_HAVE_TIME_H */ #if !APR_HAS_THREADS int main(void) { fprintf(stderr, "this program requires APR thread support\n"); return 0; } #else #define RESLIST_MIN 3 #define RESLIST_SMAX 10 #define RESLIST_HMAX 20 #define RESLIST_TTL APR_TIME_C(350000) /* 35 ms */ #define CONSUMER_THREADS 25 #define CONSUMER_ITERATIONS 250 #define CONSTRUCT_SLEEP_TIME APR_TIME_C(250000) /* 25 ms */ #define DESTRUCT_SLEEP_TIME APR_TIME_C(100000) /* 10 ms */ #define WORK_DELAY_SLEEP_TIME APR_TIME_C(150000) /* 15 ms */ typedef struct { apr_interval_time_t sleep_upon_construct; apr_interval_time_t sleep_upon_destruct; int c_count; int d_count; } my_parameters_t; typedef struct { int id; } my_resource_t; static apr_status_t my_constructor(void **resource, void *params, apr_pool_t *pool) { my_resource_t *res; my_parameters_t *my_params = params; /* Create some resource */ res = apr_palloc(pool, sizeof(*res)); res->id = my_params->c_count++; printf("++ constructing new resource [id:%d, #%d/%d]\n", res->id, my_params->c_count, my_params->d_count); /* Sleep for awhile, to simulate construction overhead. */ apr_sleep(my_params->sleep_upon_construct); /* Set the resource so it can be managed by the reslist */ *resource = res; return APR_SUCCESS; } static apr_status_t my_destructor(void *resource, void *params, apr_pool_t *pool) { my_resource_t *res = resource; my_parameters_t *my_params = params; printf("-- destructing old resource [id:%d, #%d/%d]\n", res->id, my_params->c_count, ++my_params->d_count); apr_sleep(my_params->sleep_upon_destruct); return APR_SUCCESS; } typedef struct { int tid; apr_reslist_t *reslist; apr_interval_time_t work_delay_sleep; } my_thread_info_t; static void * APR_THREAD_FUNC resource_consuming_thread(apr_thread_t *thd, void *data) { apr_status_t rv; my_thread_info_t *thread_info = data; apr_reslist_t *rl = thread_info->reslist; int i; for (i = 0; i < CONSUMER_ITERATIONS; i++) { my_resource_t *res; void *vp; rv = apr_reslist_acquire(rl, &vp); if (rv != APR_SUCCESS) { fprintf(stderr, "Failed to retrieve resource from reslist\n"); apr_thread_exit(thd, rv); return NULL; } res = vp; printf(" [tid:%d,iter:%d] using resource id:%d\n", thread_info->tid, i, res->id); apr_sleep(thread_info->work_delay_sleep); /* simulate a 5% chance of the resource being bad */ if ( drand48() < 0.95 ) { rv = apr_reslist_release(rl, res); if (rv != APR_SUCCESS) { fprintf(stderr, "Failed to return resource to reslist\n"); apr_thread_exit(thd, rv); return NULL; } } else { printf("invalidating resource id:%d\n", res->id) ; rv = apr_reslist_invalidate(rl, res); if (rv != APR_SUCCESS) { fprintf(stderr, "Failed to invalidate resource\n"); apr_thread_exit(thd, rv); return NULL; } } } return APR_SUCCESS; } static void test_timeout(apr_reslist_t *rl) { apr_status_t rv; my_resource_t *resources[RESLIST_HMAX]; my_resource_t *res; void *vp; int i; printf("Setting timeout to 1000us: "); apr_reslist_timeout_set(rl, 1000); fprintf(stdout, "OK\n"); /* deplete all possible resources from the resource list * so that the next call will block until timeout is reached * (since there are no other threads to make a resource * available) */ for (i = 0; i < RESLIST_HMAX; i++) { rv = apr_reslist_acquire(rl, (void**)&resources[i]); if (rv != APR_SUCCESS) { fprintf(stderr, "couldn't acquire resource: %d\n", rv); exit(1); } } /* next call will block until timeout is reached */ rv = apr_reslist_acquire(rl, &vp); if (!APR_STATUS_IS_TIMEUP(rv)) { fprintf(stderr, "apr_reslist_acquire()->%d instead of TIMEUP\n", rv); exit(1); } res = vp; /* release the resources; otherwise the destroy operation * will blow */ for (i = 0; i < RESLIST_HMAX; i++) { rv = apr_reslist_release(rl, &resources[i]); if (rv != APR_SUCCESS) { fprintf(stderr, "couldn't release resource: %d\n", rv); exit(1); } } } static apr_status_t test_reslist(apr_pool_t *parpool) { apr_status_t rv; apr_pool_t *pool; apr_reslist_t *rl; my_parameters_t *params; int i; apr_thread_t *my_threads[CONSUMER_THREADS]; my_thread_info_t my_thread_info[CONSUMER_THREADS]; srand48(time(0)) ; printf("Creating child pool......................."); rv = apr_pool_create(&pool, parpool); if (rv != APR_SUCCESS) { fprintf(stderr, "Error creating child pool\n"); return rv; } printf("OK\n"); /* Create some parameters that will be passed into each * constructor and destructor call. */ params = apr_pcalloc(pool, sizeof(*params)); params->sleep_upon_construct = CONSTRUCT_SLEEP_TIME; params->sleep_upon_destruct = DESTRUCT_SLEEP_TIME; /* We're going to want 10 blocks of data from our target rmm. */ printf("Creating resource list:\n" " min/smax/hmax: %d/%d/%d\n" " ttl: %" APR_TIME_T_FMT "\n", RESLIST_MIN, RESLIST_SMAX, RESLIST_HMAX, RESLIST_TTL); rv = apr_reslist_create(&rl, RESLIST_MIN, RESLIST_SMAX, RESLIST_HMAX, RESLIST_TTL, my_constructor, my_destructor, params, pool); if (rv != APR_SUCCESS) { fprintf(stderr, "Error allocating shared memory block\n"); return rv; } fprintf(stdout, "OK\n"); printf("Creating %d threads", CONSUMER_THREADS); for (i = 0; i < CONSUMER_THREADS; i++) { putchar('.'); my_thread_info[i].tid = i; my_thread_info[i].reslist = rl; my_thread_info[i].work_delay_sleep = WORK_DELAY_SLEEP_TIME; rv = apr_thread_create(&my_threads[i], NULL, resource_consuming_thread, &my_thread_info[i], pool); if (rv != APR_SUCCESS) { fprintf(stderr, "Failed to create thread %d\n", i); return rv; } } printf("\nDone!\n"); printf("Waiting for threads to finish"); for (i = 0; i < CONSUMER_THREADS; i++) { apr_status_t thread_rv; putchar('.'); apr_thread_join(&thread_rv, my_threads[i]); if (rv != APR_SUCCESS) { fprintf(stderr, "Failed to join thread %d\n", i); return rv; } } printf("\nDone!\n"); test_timeout(rl); printf("Destroying resource list................."); rv = apr_reslist_destroy(rl); if (rv != APR_SUCCESS) { printf("FAILED\n"); return rv; } printf("OK\n"); apr_pool_destroy(pool); return APR_SUCCESS; } int main(void) { apr_status_t rv; apr_pool_t *pool; char errmsg[200]; apr_initialize(); printf("APR Resource List Test\n"); printf("======================\n\n"); printf("Initializing the pool............................"); if (apr_pool_create(&pool, NULL) != APR_SUCCESS) { printf("could not initialize pool\n"); exit(-1); } printf("OK\n"); rv = test_reslist(pool); if (rv != APR_SUCCESS) { printf("Resource list test FAILED: [%d] %s\n", rv, apr_strerror(rv, errmsg, sizeof(errmsg))); exit(-2); } printf("Resource list test passed!\n"); return 0; } #endif /* APR_HAS_THREADS */
001-log4cxx
trunk/src/apr-util/test/testreslist.c
C
asf20
8,743
/* Copyright 2000-2005 The Apache Software Foundation or its licensors, as * applicable. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "apr_pools.h" #include "abts.h" #ifndef APR_TEST_UTIL #define APR_TEST_UTIL /* XXX FIXME */ #ifdef WIN32 #define EXTENSION ".exe" #elif NETWARE #define EXTENSION ".nlm" #else #define EXTENSION #endif #define STRING_MAX 8096 /* Some simple functions to make the test apps easier to write and * a bit more consistent... */ extern apr_pool_t *p; /* Assert that RV is an APR_SUCCESS value; else fail giving strerror * for RV and CONTEXT message. */ void apr_assert_success(abts_case* tc, const char *context, apr_status_t rv); void initialize(void); abts_suite *teststrmatch(abts_suite *suite); abts_suite *testuri(abts_suite *suite); abts_suite *testuuid(abts_suite *suite); abts_suite *testbuckets(abts_suite *suite); abts_suite *testpass(abts_suite *suite); abts_suite *testmd4(abts_suite *suite); abts_suite *testmd5(abts_suite *suite); abts_suite *testldap(abts_suite *suite); abts_suite *testdbd(abts_suite *suite); #endif /* APR_TEST_INCLUDES */
001-log4cxx
trunk/src/apr-util/test/testutil.h
C
asf20
1,623