code stringlengths 1 2.06M | language stringclasses 1 value |
|---|---|
/*
* 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"));
}
}
| C++ |
/*
* 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;
}
}
}
| C++ |
/*
* 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();
}
| C++ |
/*
* 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;
}
| C++ |
/*
* 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
| C++ |
/*
* 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);
}
| C++ |
/*
* 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 */ ) {
}
| C++ |
/*
* 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();
}
| C++ |
/*
* 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() {
}
| C++ |
/*
* 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;
}
| C++ |
/*
* 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);
}
}
| C++ |
/*
* 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));
}
}
| C++ |
/*
* 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&) {}
| C++ |
/*
* 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 /* ' ' */);
}
}
| C++ |
/*
* 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
}
| C++ |
/*
* 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
| C++ |
/*
* 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();
}
| C++ |
/*
* 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);
}
| C++ |
/*
* 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;
}
| C++ |
/*
* 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;
}
}
| C++ |
/*
* 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);
}
| C++ |
/*
* 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);
}
}
| C++ |
/*
* 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;
}
| C++ |
/*
* 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 */ ) {
}
| C++ |
/*
* 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();
}
}
| C++ |
/*
* 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;
}
| C++ |
/*
* 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() {
}
| C++ |
/*
* 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
}
| C++ |
/*
* 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;
}
| C++ |
/*
* 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() {}
| C++ |
/*
* 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);
}
}
| C++ |
/*
* 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;
}
| C++ |
/*
* 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
| C++ |
/*
* 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
| C++ |
/*
* 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("""));
break;
case 0x26:
buf.append(LOG4CXX_STR("&"));
break;
case 0x3C:
buf.append(LOG4CXX_STR("<"));
break;
case 0x3E:
buf.append(LOG4CXX_STR(">"));
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("]]>]]><![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);
}
| C++ |
/*
* 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;
}
| C++ |
/*
* 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&)
{
}
| C++ |
/*
* 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);
}
| C++ |
/*
* 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);
}
}
| C++ |
/*
* 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;
}
| C++ |
/*
* 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;
}
}
| C++ |
/*
* 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);
}
| C++ |
/*
* 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());
}
| C++ |
/*
* 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();
}
}
}
}
| C++ |
/*
* 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);
}
| C++ |
/*
* 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
}
| C++ |
/*
* 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);
}
}
| C++ |
/*
* 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;
}
| C++ |
/*
* 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 /* ')' */);
}
| C++ |
/*
* 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;
}
| C++ |
/*
* 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;
}
| C++ |
/*
* 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;
}
| C++ |
/*
* 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;
}
| C++ |
/*
* 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;
}
| C++ |
/*
* 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;
}
| C++ |
/*
* 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;
}
| C++ |
/*
* 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;
}
| C++ |
/*
Copyright (c) 1998, 1999, 2000 Thai Open Source Software Center Ltd
See the file COPYING for copying permission.
*/
#ifndef XmlParse_INCLUDED
#define XmlParse_INCLUDED 1
#include <stdlib.h>
#ifndef XMLPARSEAPI
# if defined(__declspec) && !defined(__CYGWIN__)
# define XMLPARSEAPI __declspec(dllimport)
# else
# define XMLPARSEAPI /* nothing */
# endif
#endif /* not defined XMLPARSEAPI */
#ifdef __cplusplus
extern "C" {
#endif
typedef void *XML_Parser;
/* Information is UTF-8 encoded. */
typedef char XML_Char;
typedef char XML_LChar;
enum XML_Content_Type {
XML_CTYPE_EMPTY = 1,
XML_CTYPE_ANY,
XML_CTYPE_MIXED,
XML_CTYPE_NAME,
XML_CTYPE_CHOICE,
XML_CTYPE_SEQ
};
enum XML_Content_Quant {
XML_CQUANT_NONE,
XML_CQUANT_OPT,
XML_CQUANT_REP,
XML_CQUANT_PLUS
};
/* If type == XML_CTYPE_EMPTY or XML_CTYPE_ANY, then quant will be
XML_CQUANT_NONE, and the other fields will be zero or NULL.
If type == XML_CTYPE_MIXED, then quant will be NONE or REP and
numchildren will contain number of elements that may be mixed in
and children point to an array of XML_Content cells that will be
all of XML_CTYPE_NAME type with no quantification.
If type == XML_CTYPE_NAME, then the name points to the name, and
the numchildren field will be zero and children will be NULL. The
quant fields indicates any quantifiers placed on the name.
CHOICE and SEQ will have name NULL, the number of children in
numchildren and children will point, recursively, to an array
of XML_Content cells.
The EMPTY, ANY, and MIXED types will only occur at top level.
*/
typedef struct XML_cp XML_Content;
struct XML_cp {
enum XML_Content_Type type;
enum XML_Content_Quant quant;
const XML_Char * name;
unsigned int numchildren;
XML_Content * children;
};
/* This is called for an element declaration. See above for
description of the model argument. It's the caller's responsibility
to free model when finished with it.
*/
typedef void (*XML_ElementDeclHandler) (void *userData,
const XML_Char *name,
XML_Content *model);
void XMLPARSEAPI
XML_SetElementDeclHandler(XML_Parser parser,
XML_ElementDeclHandler eldecl);
/*
The Attlist declaration handler is called for *each* attribute. So
a single Attlist declaration with multiple attributes declared will
generate multiple calls to this handler. The "default" parameter
may be NULL in the case of the "#IMPLIED" or "#REQUIRED" keyword.
The "isrequired" parameter will be true and the default value will
be NULL in the case of "#REQUIRED". If "isrequired" is true and
default is non-NULL, then this is a "#FIXED" default.
*/
typedef void (*XML_AttlistDeclHandler) (void *userData,
const XML_Char *elname,
const XML_Char *attname,
const XML_Char *att_type,
const XML_Char *dflt,
int isrequired);
void XMLPARSEAPI
XML_SetAttlistDeclHandler(XML_Parser parser,
XML_AttlistDeclHandler attdecl);
/* The XML declaration handler is called for *both* XML declarations and
text declarations. The way to distinguish is that the version parameter
will be null for text declarations. The encoding parameter may be null
for XML declarations. The standalone parameter will be -1, 0, or 1
indicating respectively that there was no standalone parameter in
the declaration, that it was given as no, or that it was given as yes.
*/
typedef void (*XML_XmlDeclHandler) (void *userData,
const XML_Char *version,
const XML_Char *encoding,
int standalone);
void XMLPARSEAPI
XML_SetXmlDeclHandler(XML_Parser parser,
XML_XmlDeclHandler xmldecl);
typedef struct {
void *(*malloc_fcn)(size_t size);
void *(*realloc_fcn)(void *ptr, size_t size);
void (*free_fcn)(void *ptr);
} XML_Memory_Handling_Suite;
/* Constructs a new parser; encoding is the encoding specified by the
external protocol or null if there is none specified. */
XML_Parser XMLPARSEAPI
XML_ParserCreate(const XML_Char *encoding);
/* Constructs a new parser and namespace processor. Element type
names and attribute names that belong to a namespace will be expanded;
unprefixed attribute names are never expanded; unprefixed element type
names are expanded only if there is a default namespace. The expanded
name is the concatenation of the namespace URI, the namespace
separator character, and the local part of the name. If the namespace
separator is '\0' then the namespace URI and the local part will be
concatenated without any separator. When a namespace is not declared,
the name and prefix will be passed through without expansion. */
XML_Parser XMLPARSEAPI
XML_ParserCreateNS(const XML_Char *encoding, XML_Char namespaceSeparator);
/* Constructs a new parser using the memory management suit referred to
by memsuite. If memsuite is NULL, then use the standard library memory
suite. If namespaceSeparator is non-NULL it creates a parser with
namespace processing as described above. The character pointed at
will serve as the namespace separator.
All further memory operations used for the created parser will come from
the given suite.
*/
XML_Parser XMLPARSEAPI
XML_ParserCreate_MM(const XML_Char *encoding,
const XML_Memory_Handling_Suite *memsuite,
const XML_Char *namespaceSeparator);
/* atts is array of name/value pairs, terminated by 0;
names and values are 0 terminated. */
typedef void (*XML_StartElementHandler)(void *userData,
const XML_Char *name,
const XML_Char **atts);
typedef void (*XML_EndElementHandler)(void *userData,
const XML_Char *name);
/* s is not 0 terminated. */
typedef void (*XML_CharacterDataHandler)(void *userData,
const XML_Char *s,
int len);
/* target and data are 0 terminated */
typedef void (*XML_ProcessingInstructionHandler)(void *userData,
const XML_Char *target,
const XML_Char *data);
/* data is 0 terminated */
typedef void (*XML_CommentHandler)(void *userData, const XML_Char *data);
typedef void (*XML_StartCdataSectionHandler)(void *userData);
typedef void (*XML_EndCdataSectionHandler)(void *userData);
/* This is called for any characters in the XML document for
which there is no applicable handler. This includes both
characters that are part of markup which is of a kind that is
not reported (comments, markup declarations), or characters
that are part of a construct which could be reported but
for which no handler has been supplied. The characters are passed
exactly as they were in the XML document except that
they will be encoded in UTF-8. Line boundaries are not normalized.
Note that a byte order mark character is not passed to the default handler.
There are no guarantees about how characters are divided between calls
to the default handler: for example, a comment might be split between
multiple calls. */
typedef void (*XML_DefaultHandler)(void *userData,
const XML_Char *s,
int len);
/* This is called for the start of the DOCTYPE declaration, before
any DTD or internal subset is parsed. */
typedef void (*XML_StartDoctypeDeclHandler)(void *userData,
const XML_Char *doctypeName,
const XML_Char *sysid,
const XML_Char *pubid,
int has_internal_subset
);
/* This is called for the start of the DOCTYPE declaration when the
closing > is encountered, but after processing any external subset. */
typedef void (*XML_EndDoctypeDeclHandler)(void *userData);
/* This is called for entity declarations. The is_parameter_entity
argument will be non-zero if the entity is a parameter entity, zero
otherwise.
For internal entities (<!ENTITY foo "bar">), value will
be non-null and systemId, publicID, and notationName will be null.
The value string is NOT null terminated; the length is provided in
the value_length argument. Since it is legal to have zero-length
values, do not use this argument to test for internal entities.
For external entities, value will be null and systemId will be non-null.
The publicId argument will be null unless a public identifier was
provided. The notationName argument will have a non-null value only
for unparsed entity declarations.
*/
typedef void (*XML_EntityDeclHandler) (void *userData,
const XML_Char *entityName,
int is_parameter_entity,
const XML_Char *value,
int value_length,
const XML_Char *base,
const XML_Char *systemId,
const XML_Char *publicId,
const XML_Char *notationName);
void XMLPARSEAPI
XML_SetEntityDeclHandler(XML_Parser parser,
XML_EntityDeclHandler handler);
/* OBSOLETE -- OBSOLETE -- OBSOLETE
This handler has been superceded by the EntityDeclHandler above.
It is provided here for backward compatibility.
This is called for a declaration of an unparsed (NDATA)
entity. The base argument is whatever was set by XML_SetBase.
The entityName, systemId and notationName arguments will never be null.
The other arguments may be. */
typedef void (*XML_UnparsedEntityDeclHandler)(void *userData,
const XML_Char *entityName,
const XML_Char *base,
const XML_Char *systemId,
const XML_Char *publicId,
const XML_Char *notationName);
/* This is called for a declaration of notation.
The base argument is whatever was set by XML_SetBase.
The notationName will never be null. The other arguments can be. */
typedef void (*XML_NotationDeclHandler)(void *userData,
const XML_Char *notationName,
const XML_Char *base,
const XML_Char *systemId,
const XML_Char *publicId);
/* When namespace processing is enabled, these are called once for
each namespace declaration. The call to the start and end element
handlers occur between the calls to the start and end namespace
declaration handlers. For an xmlns attribute, prefix will be null.
For an xmlns="" attribute, uri will be null. */
typedef void (*XML_StartNamespaceDeclHandler)(void *userData,
const XML_Char *prefix,
const XML_Char *uri);
typedef void (*XML_EndNamespaceDeclHandler)(void *userData,
const XML_Char *prefix);
/* This is called if the document is not standalone (it has an
external subset or a reference to a parameter entity, but does not
have standalone="yes"). If this handler returns 0, then processing
will not continue, and the parser will return a
XML_ERROR_NOT_STANDALONE error. */
typedef int (*XML_NotStandaloneHandler)(void *userData);
/* This is called for a reference to an external parsed general entity.
The referenced entity is not automatically parsed.
The application can parse it immediately or later using
XML_ExternalEntityParserCreate.
The parser argument is the parser parsing the entity containing the reference;
it can be passed as the parser argument to XML_ExternalEntityParserCreate.
The systemId argument is the system identifier as specified in the entity
declaration; it will not be null.
The base argument is the system identifier that should be used as the base for
resolving systemId if systemId was relative; this is set by XML_SetBase;
it may be null.
The publicId argument is the public identifier as specified in the entity
declaration, or null if none was specified; the whitespace in the public
identifier will have been normalized as required by the XML spec.
The context argument specifies the parsing context in the format
expected by the context argument to
XML_ExternalEntityParserCreate; context is valid only until the handler
returns, so if the referenced entity is to be parsed later, it must be copied.
The handler should return 0 if processing should not continue because of
a fatal error in the handling of the external entity.
In this case the calling parser will return an
XML_ERROR_EXTERNAL_ENTITY_HANDLING error.
Note that unlike other handlers the first argument is the parser, not
userData. */
typedef int (*XML_ExternalEntityRefHandler)(XML_Parser parser,
const XML_Char *context,
const XML_Char *base,
const XML_Char *systemId,
const XML_Char *publicId);
/* This structure is filled in by the XML_UnknownEncodingHandler
to provide information to the parser about encodings that are unknown
to the parser.
The map[b] member gives information about byte sequences
whose first byte is b.
If map[b] is c where c is >= 0, then b by itself encodes the Unicode scalar
value c.
If map[b] is -1, then the byte sequence is malformed.
If map[b] is -n, where n >= 2, then b is the first byte of an n-byte
sequence that encodes a single Unicode scalar value.
The data member will be passed as the first argument to the convert function.
The convert function is used to convert multibyte sequences;
s will point to a n-byte sequence where map[(unsigned char)*s] == -n.
The convert function must return the Unicode scalar value
represented by this byte sequence or -1 if the byte sequence is malformed.
The convert function may be null if the encoding is a single-byte encoding,
that is if map[b] >= -1 for all bytes b.
When the parser is finished with the encoding, then if release is not null,
it will call release passing it the data member;
once release has been called, the convert function will not be called again.
Expat places certain restrictions on the encodings that are supported
using this mechanism.
1. Every ASCII character that can appear in a well-formed XML document,
other than the characters
$@\^`{}~
must be represented by a single byte, and that byte must be the
same byte that represents that character in ASCII.
2. No character may require more than 4 bytes to encode.
3. All characters encoded must have Unicode scalar values <= 0xFFFF,
(ie characters that would be encoded by surrogates in UTF-16
are not allowed). Note that this restriction doesn't apply to
the built-in support for UTF-8 and UTF-16.
4. No Unicode character may be encoded by more than one distinct sequence
of bytes. */
typedef struct {
int map[256];
void *data;
int (*convert)(void *data, const char *s);
void (*release)(void *data);
} XML_Encoding;
/* This is called for an encoding that is unknown to the parser.
The encodingHandlerData argument is that which was passed as the
second argument to XML_SetUnknownEncodingHandler.
The name argument gives the name of the encoding as specified in
the encoding declaration.
If the callback can provide information about the encoding,
it must fill in the XML_Encoding structure, and return 1.
Otherwise it must return 0.
If info does not describe a suitable encoding,
then the parser will return an XML_UNKNOWN_ENCODING error. */
typedef int (*XML_UnknownEncodingHandler)(void *encodingHandlerData,
const XML_Char *name,
XML_Encoding *info);
void XMLPARSEAPI
XML_SetElementHandler(XML_Parser parser,
XML_StartElementHandler start,
XML_EndElementHandler end);
void XMLPARSEAPI
XML_SetStartElementHandler(XML_Parser, XML_StartElementHandler);
void XMLPARSEAPI
XML_SetEndElementHandler(XML_Parser, XML_EndElementHandler);
void XMLPARSEAPI
XML_SetCharacterDataHandler(XML_Parser parser,
XML_CharacterDataHandler handler);
void XMLPARSEAPI
XML_SetProcessingInstructionHandler(XML_Parser parser,
XML_ProcessingInstructionHandler handler);
void XMLPARSEAPI
XML_SetCommentHandler(XML_Parser parser,
XML_CommentHandler handler);
void XMLPARSEAPI
XML_SetCdataSectionHandler(XML_Parser parser,
XML_StartCdataSectionHandler start,
XML_EndCdataSectionHandler end);
void XMLPARSEAPI
XML_SetStartCdataSectionHandler(XML_Parser parser,
XML_StartCdataSectionHandler start);
void XMLPARSEAPI
XML_SetEndCdataSectionHandler(XML_Parser parser,
XML_EndCdataSectionHandler end);
/* This sets the default handler and also inhibits expansion of
internal entities. The entity reference will be passed to the default
handler. */
void XMLPARSEAPI
XML_SetDefaultHandler(XML_Parser parser,
XML_DefaultHandler handler);
/* This sets the default handler but does not inhibit expansion of
internal entities. The entity reference will not be passed to the
default handler. */
void XMLPARSEAPI
XML_SetDefaultHandlerExpand(XML_Parser parser,
XML_DefaultHandler handler);
void XMLPARSEAPI
XML_SetDoctypeDeclHandler(XML_Parser parser,
XML_StartDoctypeDeclHandler start,
XML_EndDoctypeDeclHandler end);
void XMLPARSEAPI
XML_SetStartDoctypeDeclHandler(XML_Parser parser,
XML_StartDoctypeDeclHandler start);
void XMLPARSEAPI
XML_SetEndDoctypeDeclHandler(XML_Parser parser,
XML_EndDoctypeDeclHandler end);
void XMLPARSEAPI
XML_SetUnparsedEntityDeclHandler(XML_Parser parser,
XML_UnparsedEntityDeclHandler handler);
void XMLPARSEAPI
XML_SetNotationDeclHandler(XML_Parser parser,
XML_NotationDeclHandler handler);
void XMLPARSEAPI
XML_SetNamespaceDeclHandler(XML_Parser parser,
XML_StartNamespaceDeclHandler start,
XML_EndNamespaceDeclHandler end);
void XMLPARSEAPI
XML_SetStartNamespaceDeclHandler(XML_Parser parser,
XML_StartNamespaceDeclHandler start);
void XMLPARSEAPI
XML_SetEndNamespaceDeclHandler(XML_Parser parser,
XML_EndNamespaceDeclHandler end);
void XMLPARSEAPI
XML_SetNotStandaloneHandler(XML_Parser parser,
XML_NotStandaloneHandler handler);
void XMLPARSEAPI
XML_SetExternalEntityRefHandler(XML_Parser parser,
XML_ExternalEntityRefHandler handler);
/* If a non-null value for arg is specified here, then it will be passed
as the first argument to the external entity ref handler instead
of the parser object. */
void XMLPARSEAPI
XML_SetExternalEntityRefHandlerArg(XML_Parser, void *arg);
void XMLPARSEAPI
XML_SetUnknownEncodingHandler(XML_Parser parser,
XML_UnknownEncodingHandler handler,
void *encodingHandlerData);
/* This can be called within a handler for a start element, end element,
processing instruction or character data. It causes the corresponding
markup to be passed to the default handler. */
void XMLPARSEAPI
XML_DefaultCurrent(XML_Parser parser);
/* If do_nst is non-zero, and namespace processing is in effect, and
a name has a prefix (i.e. an explicit namespace qualifier) then
that name is returned as a triplet in a single
string separated by the separator character specified when the parser
was created: URI + sep + local_name + sep + prefix.
If do_nst is zero, then namespace information is returned in the
default manner (URI + sep + local_name) whether or not the names
has a prefix.
*/
void XMLPARSEAPI
XML_SetReturnNSTriplet(XML_Parser parser, int do_nst);
/* This value is passed as the userData argument to callbacks. */
void XMLPARSEAPI
XML_SetUserData(XML_Parser parser, void *userData);
/* Returns the last value set by XML_SetUserData or null. */
#define XML_GetUserData(parser) (*(void **)(parser))
/* This is equivalent to supplying an encoding argument
to XML_ParserCreate. It must not be called after XML_Parse
or XML_ParseBuffer. */
int XMLPARSEAPI
XML_SetEncoding(XML_Parser parser, const XML_Char *encoding);
/* If this function is called, then the parser will be passed
as the first argument to callbacks instead of userData.
The userData will still be accessible using XML_GetUserData. */
void XMLPARSEAPI
XML_UseParserAsHandlerArg(XML_Parser parser);
/* Sets the base to be used for resolving relative URIs in system
identifiers in declarations. Resolving relative identifiers is left
to the application: this value will be passed through as the base
argument to the XML_ExternalEntityRefHandler, XML_NotationDeclHandler
and XML_UnparsedEntityDeclHandler. The base argument will be copied.
Returns zero if out of memory, non-zero otherwise. */
int XMLPARSEAPI
XML_SetBase(XML_Parser parser, const XML_Char *base);
const XML_Char XMLPARSEAPI *
XML_GetBase(XML_Parser parser);
/* Returns the number of the attribute/value pairs passed in last call
to the XML_StartElementHandler that were specified in the start-tag
rather than defaulted. Each attribute/value pair counts as 2; thus
this correspondds to an index into the atts array passed to the
XML_StartElementHandler. */
int XMLPARSEAPI
XML_GetSpecifiedAttributeCount(XML_Parser parser);
/* Returns the index of the ID attribute passed in the last call to
XML_StartElementHandler, or -1 if there is no ID attribute. Each
attribute/value pair counts as 2; thus this correspondds to an index
into the atts array passed to the XML_StartElementHandler. */
int XMLPARSEAPI
XML_GetIdAttributeIndex(XML_Parser parser);
/* Parses some input. Returns 0 if a fatal error is detected.
The last call to XML_Parse must have isFinal true;
len may be zero for this call (or any other). */
int XMLPARSEAPI
XML_Parse(XML_Parser parser, const char *s, int len, int isFinal);
void XMLPARSEAPI *
XML_GetBuffer(XML_Parser parser, int len);
int XMLPARSEAPI
XML_ParseBuffer(XML_Parser parser, int len, int isFinal);
/* Creates an XML_Parser object that can parse an external general
entity; context is a '\0'-terminated string specifying the parse
context; encoding is a '\0'-terminated string giving the name of the
externally specified encoding, or null if there is no externally
specified encoding. The context string consists of a sequence of
tokens separated by formfeeds (\f); a token consisting of a name
specifies that the general entity of the name is open; a token of the
form prefix=uri specifies the namespace for a particular prefix; a
token of the form =uri specifies the default namespace. This can be
called at any point after the first call to an
ExternalEntityRefHandler so longer as the parser has not yet been
freed. The new parser is completely independent and may safely be
used in a separate thread. The handlers and userData are initialized
from the parser argument. Returns 0 if out of memory. Otherwise
returns a new XML_Parser object. */
XML_Parser XMLPARSEAPI
XML_ExternalEntityParserCreate(XML_Parser parser,
const XML_Char *context,
const XML_Char *encoding);
enum XML_ParamEntityParsing {
XML_PARAM_ENTITY_PARSING_NEVER,
XML_PARAM_ENTITY_PARSING_UNLESS_STANDALONE,
XML_PARAM_ENTITY_PARSING_ALWAYS
};
/* Controls parsing of parameter entities (including the external DTD
subset). If parsing of parameter entities is enabled, then references
to external parameter entities (including the external DTD subset)
will be passed to the handler set with
XML_SetExternalEntityRefHandler. The context passed will be 0.
Unlike external general entities, external parameter entities can only
be parsed synchronously. If the external parameter entity is to be
parsed, it must be parsed during the call to the external entity ref
handler: the complete sequence of XML_ExternalEntityParserCreate,
XML_Parse/XML_ParseBuffer and XML_ParserFree calls must be made during
this call. After XML_ExternalEntityParserCreate has been called to
create the parser for the external parameter entity (context must be 0
for this call), it is illegal to make any calls on the old parser
until XML_ParserFree has been called on the newly created parser. If
the library has been compiled without support for parameter entity
parsing (ie without XML_DTD being defined), then
XML_SetParamEntityParsing will return 0 if parsing of parameter
entities is requested; otherwise it will return non-zero. */
int XMLPARSEAPI
XML_SetParamEntityParsing(XML_Parser parser,
enum XML_ParamEntityParsing parsing);
enum XML_Error {
XML_ERROR_NONE,
XML_ERROR_NO_MEMORY,
XML_ERROR_SYNTAX,
XML_ERROR_NO_ELEMENTS,
XML_ERROR_INVALID_TOKEN,
XML_ERROR_UNCLOSED_TOKEN,
XML_ERROR_PARTIAL_CHAR,
XML_ERROR_TAG_MISMATCH,
XML_ERROR_DUPLICATE_ATTRIBUTE,
XML_ERROR_JUNK_AFTER_DOC_ELEMENT,
XML_ERROR_PARAM_ENTITY_REF,
XML_ERROR_UNDEFINED_ENTITY,
XML_ERROR_RECURSIVE_ENTITY_REF,
XML_ERROR_ASYNC_ENTITY,
XML_ERROR_BAD_CHAR_REF,
XML_ERROR_BINARY_ENTITY_REF,
XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF,
XML_ERROR_MISPLACED_XML_PI,
XML_ERROR_UNKNOWN_ENCODING,
XML_ERROR_INCORRECT_ENCODING,
XML_ERROR_UNCLOSED_CDATA_SECTION,
XML_ERROR_EXTERNAL_ENTITY_HANDLING,
XML_ERROR_NOT_STANDALONE,
XML_ERROR_UNEXPECTED_STATE
};
/* If XML_Parse or XML_ParseBuffer have returned 0, then XML_GetErrorCode
returns information about the error. */
enum XML_Error XMLPARSEAPI
XML_GetErrorCode(XML_Parser parser);
/* These functions return information about the current parse location.
They may be called when XML_Parse or XML_ParseBuffer return 0;
in this case the location is the location of the character at which
the error was detected.
They may also be called from any other callback called to report
some parse event; in this the location is the location of the first
of the sequence of characters that generated the event. */
int XMLPARSEAPI XML_GetCurrentLineNumber(XML_Parser parser);
int XMLPARSEAPI XML_GetCurrentColumnNumber(XML_Parser parser);
long XMLPARSEAPI XML_GetCurrentByteIndex(XML_Parser parser);
/* Return the number of bytes in the current event.
Returns 0 if the event is in an internal entity. */
int XMLPARSEAPI
XML_GetCurrentByteCount(XML_Parser parser);
/* If XML_CONTEXT_BYTES is defined, returns the input buffer, sets
the integer pointed to by offset to the offset within this buffer
of the current parse position, and sets the integer pointed to by size
to the size of this buffer (the number of input bytes). Otherwise
returns a null pointer. Also returns a null pointer if a parse isn't
active.
NOTE: The character pointer returned should not be used outside
the handler that makes the call. */
const char XMLPARSEAPI *
XML_GetInputContext(XML_Parser parser,
int *offset,
int *size);
/* For backwards compatibility with previous versions. */
#define XML_GetErrorLineNumber XML_GetCurrentLineNumber
#define XML_GetErrorColumnNumber XML_GetCurrentColumnNumber
#define XML_GetErrorByteIndex XML_GetCurrentByteIndex
/* Frees memory used by the parser. */
void XMLPARSEAPI
XML_ParserFree(XML_Parser parser);
/* Returns a string describing the error. */
const XML_LChar XMLPARSEAPI *
XML_ErrorString(int code);
/* Return a string containing the version number of this expat */
const XML_LChar XMLPARSEAPI *
XML_ExpatVersion(void);
typedef struct {
int major;
int minor;
int micro;
} XML_Expat_Version;
/* Return an XML_Expat_Version structure containing numeric version
number information for this version of expat */
XML_Expat_Version XMLPARSEAPI
XML_ExpatVersionInfo(void);
#ifndef XML_MAJOR_VERSION
#define XML_MAJOR_VERSION 1
#endif
#ifndef XML_MINOR_VERSION
#define XML_MINOR_VERSION 95
#endif
#ifndef XML_MICRO_VERSION
#define XML_MICRO_VERSION 2
#endif
#ifdef __cplusplus
}
#endif
#endif /* not XmlParse_INCLUDED */
| C++ |
#ifndef FILE_HPP
#define FILE_HPP
#include "Shared.hpp"
#include <fstream>
namespace engine {
/// \brief Read/Write file opening mode
enum eReadWriteMode{
RWM_Write = 1, /// Read/Write, make a new file or overwrite an existant one
RWM_Open = 0, /// Read/Write, does not overwrite, file must exist
RWM_ReadOnly = -1, /// Read Only mode, file must exist
};
/// \brief Opening cursor position in file
enum eFilePos{
FP_Top,
FP_Bottom
};
/// \brief Class used for any file handling
class OOXAPI File{
public:
/// \brief Ctor, default, do nothing
File();
/// \brief Ctor, open the given file in given mode
/// \param pFilename : name of the file
/// \param pFp : file cursor position
/// \param pRwm : opening mode
File(const std::string &pFilename, eReadWriteMode pRwm = RWM_Open, eFilePos pFp = FP_Top);
virtual ~File();
/// \brief Open a file (in buffer)
/// \param pFilename : name of the file
/// \param pFp : file cursor position
/// \param pRwm : opening mode
void Open(const std::string &pFilename, eReadWriteMode pRwm = RWM_Open, eFilePos pFp = FP_Top);
/// \brief Close the opened file (buffer)
void Close();
/// \brief Flush the buffer in the file
void Flush();
/// \brief Returns the content of opened file in one string
std::string Read() const;
/// \brief Returns true if a file is opened
bool IsOpened() const;
/// \brief Returns the name of opened file
std::string Filename() const;
/// \brief Returns true if EoF is reached
bool End() const;
/// \brief Returns the current line in the opened file(and increments cursor afterwards)
std::string GetLine();
/// \brief Stream Op for in file writing
template<class T> File& operator<< (T &pMsg);
/// Static Methods
/// \brief Check if a file exists on drive
/// \param pFilename : path to the file
static bool Exists(const std::string &pFilename);
protected:
std::fstream mFile; /// File buffer
std::string mFileName; /// File name (with path)
};
template<class T>
inline File& File::operator<< (T &pMsg){
if(IsOpened())
mFile << pMsg;
return (*this);
}
}
#endif
| C++ |
#ifndef SPOINTER_HPP
#define SPOINTER_HPP
#include "SPointerPolicies.hpp"
#include "Debug/New.hpp"
namespace engine {
/// \brief Smart Pointer class used to limit and ease the use of real pointers
template <class T, template<class> class Ownership = RefCountPolicy>
class SPointer : public Ownership<T>{
protected:
T* Ptr;
public:
/// \brief Ctor, Null init
SPointer() : Ptr(NULL){
}
/// \brief Ctor, Copy of another SPointer
SPointer(const SPointer<T> &P) : Ownership<T>(P),
Ptr(Clone(P.Ptr)){
}
/// \brief Ctor, Pointer init
SPointer( T* obj ) : Ptr(obj){
}
/// \brief Dtor, release an instance of the stored pointer if it exists
~SPointer(){
Kill();
}
/// \brief Release an instance of the stored pointer if it exists
void Kill(){
Release(Ptr);
}
/// \brief Returns the content of stored pointer
T& operator*() const { return *Ptr; }
/// \brief Returns the stored pointer
T* operator->() const { return Ptr; }
/// \brief Returns the stored pointer
operator T*() const { return Ptr; }
/// \brief Returns the stored pointer
T* Get() { return Ptr; }
/// \brief Internally used function to swap two pointers and their policy
void Swap(SPointer &P){
Ownership<T>::Swap(P);
std::swap(Ptr, P.Ptr);
}
/// \brief Returns a copy of this SPointer and its policy
SPointer& Copy(){
Ptr = Clone(Ptr);
return *this;
}
/// \brief Copy operator, add a reference to policy
SPointer& operator=(const SPointer &P){
SPointer<T, Ownership>(P).Swap(*this);
return *this;
}
/// \brief Assign operator
SPointer& operator=(T* obj){
if(Ptr != obj)
SPointer<T, Ownership>(obj).Swap(*this);
return *this;
}
/// \brief Returns true if stored pointer is null
bool operator!() { return Ptr == NULL; }
};
#include "Debug/NewOff.hpp"
}
#endif
| C++ |
#ifndef SHARED
#define SHARED
#define ENGINE_MAJOR 0
#define ENGINE_MINOR 3
#define ENGINE_PATCH 0
/// SFML
#include "SFML/Graphics.hpp"
/// Platform
#if defined(_WIN32) || defined(WIN32)
# define OOXWIN32
# include <time.h>
#else
# define OOXLINUX
# include <sys/time.h>
#endif
/// DLL managment under WIN32
#ifdef OOXWIN32
# ifdef OOXEXPORTS
# define OOXAPI __declspec(dllexport)
# else
# define OOXAPI __declspec(dllimport)
# endif
# ifdef _MSC_VER
# pragma warning(disable : 4251)
# pragma warning(disable : 4661)
# endif
#else
# define OOXAPI
#endif
/// Open GL 3
#ifdef OOXWIN32
# define GLEW_STATIC 1
# include "GL/glew.h"
#else
# define GL3_PROTOTYPES 1
# include <GL3/gl3.h>
#endif
/// Anisotropic extension definition
#define GL_TEXTURE_MAX_ANISOTROPY_EXT 0x84FE
#define GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT 0x84FF
/// String (always used anyway)
#include <string>
/// End Of Line
#define eol "\n"
/// Types declaration
typedef char s8;
typedef unsigned char u8;
typedef short s16;
typedef unsigned short u16;
typedef int s32;
typedef unsigned int u32;
typedef long long s64;
typedef unsigned long long u64;
typedef float f32;
typedef double f64;
/// \brief Returns time in "HH:MM:SS" format
inline std::string GetTime(){
time_t tps = time(NULL);
tm* temps = localtime(&tps);
char ret[9];
strftime(ret, 9, "%H:%M:%S", temps);
return ret;
}
/// \brief Returns date in "Day DD MMM YYYY" format
inline std::string GetDate(){
time_t tps = time(NULL);
tm* temps = localtime(&tps);
char ret[16];
strftime(ret, 16, "%a %d %b %Y", temps);
return ret;
}
#endif
| C++ |
#ifndef KEYS_HPP
#define KEYS_HPP
#include "SFML/Window/Event.hpp"
namespace engine{
/// \brief Enumeration of the different mouse buttons
enum MouseButton{
LeftButton = sf::Mouse::Left,
RightButton = sf::Mouse::Right,
MiddleButton = sf::Mouse::Middle,
X1Button = sf::Mouse::XButton1,
X2Button = sf::Mouse::XButton2,
};
/// \brief Enumeration of the different Keyboard keys
enum Key{
A = sf::Key::A,
B = sf::Key::B,
C = sf::Key::C,
D = sf::Key::D,
E = sf::Key::E,
F = sf::Key::F,
G = sf::Key::G,
H = sf::Key::H,
I = sf::Key::I,
J = sf::Key::J,
K = sf::Key::K,
L = sf::Key::L,
M = sf::Key::M,
N = sf::Key::N,
O = sf::Key::O,
P = sf::Key::P,
Q = sf::Key::Q,
R = sf::Key::R,
S = sf::Key::S,
T = sf::Key::T,
U = sf::Key::U,
V = sf::Key::V,
X = sf::Key::X,
Y = sf::Key::Y,
Z = sf::Key::Z,
Num0 = sf::Key::Num0,
Num1 = sf::Key::Num1,
Num2 = sf::Key::Num2,
Num3 = sf::Key::Num3,
Num4 = sf::Key::Num4,
Num5 = sf::Key::Num5,
Num6 = sf::Key::Num6,
Num7 = sf::Key::Num7,
Num8 = sf::Key::Num8,
Num9 = sf::Key::Num9,
Escape = sf::Key::Escape,
LShift = sf::Key::LShift,
LControl = sf::Key::LControl,
LAlt = sf::Key::LAlt,
LSystem = sf::Key::LSystem,
RShift = sf::Key::RShift,
RAlt = sf::Key::RAlt,
RControl = sf::Key::RControl,
RSystem = sf::Key::RSystem,
Menu = sf::Key::Menu,
LBracket = sf::Key::LBracket,
RBracket = sf::Key::RBracket,
SemiColon = sf::Key::SemiColon,
Comma = sf::Key::Comma,
Period = sf::Key::Period,
Quote = sf::Key::Quote,
Slash = sf::Key::Slash,
BackSlash = sf::Key::BackSlash,
Tilde = sf::Key::Tilde,
Equal = sf::Key::Equal,
Dash = sf::Key::Dash,
Space = sf::Key::Space,
Return = sf::Key::Return,
Back = sf::Key::Back,
Tab = sf::Key::Tab,
PageUp = sf::Key::PageUp,
PageDown = sf::Key::PageDown,
End = sf::Key::End,
Home = sf::Key::Home,
Insert = sf::Key::Insert,
Delete = sf::Key::Delete,
Add = sf::Key::Add,
Subtract = sf::Key::Subtract,
Multiply = sf::Key::Multiply,
Divide = sf::Key::Divide,
Left = sf::Key::Left,
Right = sf::Key::Right,
Up = sf::Key::Up,
Down = sf::Key::Down,
Numpad0 = sf::Key::Numpad0,
Numpad1 = sf::Key::Numpad1,
Numpad2 = sf::Key::Numpad2,
Numpad3 = sf::Key::Numpad3,
Numpad4 = sf::Key::Numpad4,
Numpad5 = sf::Key::Numpad5,
Numpad6 = sf::Key::Numpad6,
Numpad7 = sf::Key::Numpad7,
Numpad8 = sf::Key::Numpad8,
Numpad9 = sf::Key::Numpad9,
F1 = sf::Key::F1,
F2 = sf::Key::F2,
F3 = sf::Key::F3,
F4 = sf::Key::F4,
F5 = sf::Key::F5,
F6 = sf::Key::F6,
F7 = sf::Key::F7,
F8 = sf::Key::F8,
F9 = sf::Key::F9,
F10 = sf::Key::F10,
F11 = sf::Key::F11,
F12 = sf::Key::F12,
Pause = sf::Key::Pause,
};
}
#endif
| C++ |
#include "Clock.hpp"
#ifdef OOXWIN32
# include <Windows.h>
#endif
namespace engine {
// ============================== //
f64 GetSystemTime(){
#if defined(OOXWIN32)
static LARGE_INTEGER Frequency;
static BOOL UseHighPerformanceTimer = QueryPerformanceFrequency(&Frequency);
if (UseHighPerformanceTimer)
{
// High performance counter available : use it
LARGE_INTEGER CurrentTime;
QueryPerformanceCounter(&CurrentTime);
return static_cast<double>(CurrentTime.QuadPart) / Frequency.QuadPart;
}
else
{
// High performance counter not available : use GetTickCount (less accurate)
return GetTickCount() * 0.001;
}
#else
timeval Time = {0, 0};
gettimeofday(&Time, NULL);
return Time.tv_sec + Time.tv_usec / 1000000.;
#endif
}
void Sleep(f32 pTime){
#if defined(OOXWIN32)
::Sleep(static_cast<DWORD>(pTime * 1000));
#else
usleep(static_cast<u32>(pTime * 1000000));
#endif
}
// ============================== //
Clock::Clock() : mPaused(false), mClockTime(0.0){
mLastFrameTime = GetSystemTime();
}
void Clock::Reset(){
mLastFrameTime = GetSystemTime();
mClockTime = 0.0;
}
void Clock::Pause(){
mPaused = true;
}
void Clock::Resume(){
mLastFrameTime = GetSystemTime();
mPaused = false;
}
f32 Clock::GetElapsedTime(){
if(!mPaused) {
mTempTime = GetSystemTime();
mClockTime += mTempTime - mLastFrameTime;
mLastFrameTime = mTempTime;
}
return static_cast<f32>(mClockTime);
}
}
| C++ |
#ifndef CLOCK_HPP
#define CLOCK_HPP
#include "Shared.hpp"
namespace engine {
/// \brief Returns system time, depending on platform
/// \return the UTC time, seconds only
f64 GetSystemTime();
/// \brief Make the current thread sleep
/// \param pTime : sleep time in seconds
void Sleep(f32 pTime);
/// \brief Clock is a small class used to manage time like with a timer
class OOXAPI Clock{
public:
/// \brief Ctor, zeroed clock
Clock();
/// \brief Reset the clock to zero
void Reset();
/// \brief Pause the clock
void Pause();
/// \brief Resume the clock if it has been paused
void Resume();
/// \brief Returns time elapsed since last Reset
f32 GetElapsedTime();
private:
f64 mLastFrameTime; /// Global seconds elapsed the previons frame
f64 mClockTime; /// Seconds since last clock reset
f64 mTempTime; /// Variable used in mClockTime calculation
bool mPaused; /// True if the clock is paused
};
}
#endif
| C++ |
template<typename T>
inline engine::String::String(const T &ppValue){
mString << ppValue;
}
template<typename T>
inline String& engine::String::operator +(const T &pValue){
mString << pValue;
return *this;
}
template<typename T>
inline String& engine::String::operator+=(const T &pValue){
return (*this + pValue);
}
inline std::ostream& operator<<(std::ostream& oss, const String &pStr){
return oss << pStr.str();
}
inline void engine::String::operator=(const std::string &pStr){
mString.str(pStr);
}
inline void engine::String::operator=(const String &pStr){
mString.str(pStr);
}
inline engine::String::operator std::string() const{
return mString.str();
}
inline bool engine::String::operator ==(const std::string &pStr) const{
return this->str() == pStr;
}
inline bool engine::String::operator !=(const std::string &pStr) const{
return !(*this == pStr);
}
inline std::string engine::String::str() const{
return mString.str();
}
inline std::ostringstream& engine::String::ostr(){
return mString;
}
inline size_t engine::String::size() const{
return mString.str().size();
}
inline bool engine::String::Empty() const{
return str().empty();
}
inline bool engine::String::IsCommentary() const{
return str().substr(0,2) == "//";
}
inline StringVector engine::StringUtils::SplitString(const std::string &pIn, const std::string &pSep, u32 pMaxSplit){
StringVector v;
// pre allocation pour performance
v.reserve(pMaxSplit ? pMaxSplit + 1 : 5); // 5 nbr max de mot le plus souvent
u32 splitNbr = 0;
// Parcourt de la chaine
size_t p1 = 0, p2;
do{
p2 = pIn.find_first_of(pSep, p1);
if(p2 == p1)
p1 = p2 + 1;
else if( p2 == std::string::npos || (pMaxSplit && splitNbr == pMaxSplit)){
v.push_back(pIn.substr(p1));
break;
}else{
v.push_back(pIn.substr(p1, p2 - p1));
p1 = p2 + 1;
}
p1 = pIn.find_first_not_of(pSep, p1);
++splitNbr;
} while(p2 != std::string::npos);
return v;
}
inline std::string engine::StringUtils::ToLower(const std::string &pStr){
std::string retStr(pStr.size(), ' ');
s32 (*pf)(s32) = std::tolower;
std::transform(pStr.begin(), pStr.end(), retStr.begin(), pf);
return retStr;
}
inline std::string engine::StringUtils::ToUpper(const std::string &pStr){
std::string retStr(pStr.size(), ' ');
s32 (*pf)(s32) = std::toupper;
std::transform(pStr.begin(), pStr.end(), retStr.begin(), pf);
return retStr;
}
inline std::string engine::StringUtils::GetExtension(const std::string &pFileName){
std::string::size_type Pos = pFileName.find_first_of(".");
if( Pos != std::string::npos)
return pFileName.substr( Pos+1, std::string::npos);
return "";
}
inline std::string engine::StringUtils::GetFileName(const std::string &pFileName){
std::string::size_type pos = pFileName.find_first_of(".");
if(pos != std::string::npos)
return pFileName.substr(0, pos);
return "";
}
inline bool engine::StringUtils::StartsWith(const std::string &pStr, const std::string &pStart, bool pLowerCase){
size_t strlen = pStr.length(), startlen = pStart.length();
if(strlen < startlen || startlen == 0)
return false;
std::string strstart = pStr.substr(0, startlen);
std::string str = pStr;
if(pLowerCase){
strstart = ToLower(strstart);
str = ToLower(str);
}
return strstart == str;
} | C++ |
#ifndef COLOR_HPP
#define COLOR_HPP
#include "Shared.hpp"
namespace engine {
/// \brief Color class with RGBA Components
class OOXAPI Color{
public:
/// \brief Ctor, color from RGBA
Color(f32 R = 0.f, f32 G = 0.f, f32 B = 0.f, f32 A = 1.f);
/// \brief Returns the RGB color components in a float array
void RGB(float pTab[]) const;
/// \brief Returns the RGBA color components in a float array
void RGBA(float pTab[]) const;
f32 R() const{ return r; }
f32 G() const{ return g; }
f32 B() const{ return b; }
f32 A() const{ return a; }
/// \brief Returns a pointer on r
operator f32*() { return &r; }
/// \brief Sets the RGB color components
void RGB(f32 pR, f32 pG, f32 pB);
/// \brief Sets the RGBA color components
void RGBA(f32 pR, f32 pG, f32 pB, f32 pA);
void R(f32 pR) { r = pR; }
void G(f32 pG) { g = pG; }
void B(f32 pB) { b = pB; }
void A(f32 pA) { a = pA; }
/// \brief Common Colors
static const Color Black;
static const Color White;
static const Color Red;
static const Color Green;
static const Color Blue;
static const Color Magenta;
static const Color Cyan;
static const Color Yellow;
static const Color Orange;
static const Color Grey;
private:
f32 r, g, b, a;
};
/// \brief SFML to 00xEngine conversion
Color To00xColor(const sf::Color &pColor);
/// \brief 00xEngine to SFML conversion
sf::Color ToSFMLColor(const Color &pColor);
}
#endif
| C++ |
#ifndef STRINGCONVERTER_HPP
#define STRINGCONVERTER_HPP
#include "Shared.hpp"
#include "Math/Vector2.hpp"
#include "Math/Vector3.hpp"
namespace engine {
class String;
class Color;
/// \brief String Converter (types -> String & String -> types)
class OOXAPI StringConverter{
public:
/// \brief STRING TO FLOAT
static f32 ToFloat(const std::string &pVal);
/// \brief STRING TO INT
static s32 ToInt(const std::string &pVal);
/// \brief STRING TO UNSIGNED
static u32 ToUnsigned(const std::string &pVal);
/// \brief STRING TO BOOL
static bool ToBool(const std::string &pVal);
/// \brief STRING to VECTOR2
static Vector2F ToVector2(const std::string &pVal);
/// \brief STRING to VECTOR3
static Vector3F ToVector3(const std::string &pVal);
/// \brief STRING to COLOR
static Color ToColor(const std::string &pVal);
/// \brief FLOAT to STRING
static String ToString(f32 pVal, u16 pPrecision = 6);
/// \brief DOUBLE to STRING
static String ToString(f64 pVal, u16 pPrecision = 6);
/// \brief LINT to STRING
static String ToString(s32 pVal);
/// \brief LUNSIGNED to STRING
static String ToString(u32 pVal);
/// \brief SHORT to STRING
static String ToString(s16 pVal);
/// \brief UNSIGNED to STRING
static String ToString(u16 pVal);
};
}
#endif
| C++ |
#include "StringConverter.hpp"
#include "String.hpp"
#include "Color.hpp"
#include "Debug/New.hpp"
namespace engine {
// STRING TO FLOAT
f32 StringConverter::ToFloat(const std::string &pVal){
std::istringstream str(pVal);
f32 ret = 0;
str >> ret;
return ret;
}
// STRING TO INT
s32 StringConverter::ToInt(const std::string &pVal){
std::istringstream str(pVal);
s32 ret = 0;
str >> ret;
return ret;
}
// STRING TO UNSIGNED
u32 StringConverter::ToUnsigned(const std::string &pVal){
std::istringstream str(pVal);
u32 ret = 0;
str >> ret;
return ret;
}
// STRING TO BOOL
bool StringConverter::ToBool(const std::string &pVal){
return StringUtils::StartsWith(pVal, "true") || StringUtils::StartsWith(pVal, "1") || StringUtils::StartsWith(pVal, "yes");
}
// STRING StringConverter::to VECTOR2
Vector2F StringConverter::ToVector2(const std::string &pVal){
Vector2F ret;
StringVector vec = StringUtils::SplitString(pVal);
if(vec.size() != 2)
ret = Vector2F::ZERO;
else
ret = Vector2F(ToFloat(vec[0]), ToFloat(vec[1]));
return ret;
}
// STRING StringConverter::to VECTOR3
Vector3F StringConverter::ToVector3(const std::string &pVal){
Vector3F ret;
StringVector vec = StringUtils::SplitString(pVal);
if(vec.size() != 3)
ret = Vector3F::ZERO;
else
ret = Vector3F(ToFloat(vec[0]), ToFloat(vec[1]), ToFloat(vec[2]));
return ret;
}
// STRING StringConverter::to COLOR
Color StringConverter::ToColor(const std::string &pVal){
Color ret;
StringVector vec = StringUtils::SplitString(pVal, ",");
if(vec[0].find_first_of(".")){
// Float Color
if(vec.size() == 4)
ret = Color(ToFloat(vec[0]),ToFloat(vec[1]),ToFloat(vec[2]),ToFloat(vec[3]));
else if(vec.size() == 3)
ret = Color(ToFloat(vec[0]),ToFloat(vec[1]),ToFloat(vec[2]), 1.f);
else
ret = Color::Black;
}else{
// Unsigned Color
if(vec.size() == 4)
ret = Color(ToFloat(vec[0]) / 255.f,ToFloat(vec[1]) / 255.f,ToFloat(vec[2]) / 255.f,ToFloat(vec[3]) / 255.f);
else if(vec.size() == 3)
ret = Color(ToFloat(vec[0]) / 255.f,ToFloat(vec[1]) / 255.f,ToFloat(vec[2]) / 255.f, 1.f);
else
ret = Color::Black;
}
return ret;
}
// FLOAT StringConverter::to STRING
String StringConverter::ToString(f32 pVal, u16 pPrecision){
std::ostringstream oss;
oss.precision(pPrecision);
oss << pVal;
return oss.str();
}
// DOUBLE StringConverter::to STRING
String StringConverter::ToString(f64 pVal, u16 pPrecision){
std::ostringstream oss;
oss.precision(pPrecision);
oss << pVal;
return oss.str();
}
// LINT StringConverter::to STRING
String StringConverter::ToString(s32 pVal){
std::ostringstream oss;
oss << pVal;
return oss.str();
}
// LUNSIGNED StringConverter::to STRING
String StringConverter::ToString(u32 pVal){
std::ostringstream oss;
oss << pVal;
return oss.str();
}
// SHORT StringConverter::to STRING
String StringConverter::ToString(s16 pVal){
std::ostringstream oss;
oss << pVal;
return oss.str();
}
// UNSIGNED StringConverter::to STRING
String StringConverter::ToString(u16 pVal){
std::ostringstream oss;
oss << pVal;
return oss.str();
}
}
| C++ |
#include "Core/Entity.hpp"
namespace engine{
void Entity::MakeCube(const std::string &pMeshName, Shader &pShader){
Vector3F position[] = { Vector3F(-1.f,-1.f,-1.f), Vector3F(-1.f,-1.f,1.f), Vector3F(1.f,-1.f,1.f), Vector3F(1.f,-1.f,-1.f),
Vector3F(-1.f,1.f,-1.f), Vector3F(-1.f,1.f,1.f), Vector3F(1.f,1.f,1.f), Vector3F(1.f,1.f,-1.f),
Vector3F(-1.f,-1.f,-1.f), Vector3F(-1.f,1.f,-1.f), Vector3F(1.f,1.f,-1.f), Vector3F(1.f,-1.f,-1.f),
Vector3F(-1.f,-1.f,1.f), Vector3F(-1.f,1.f,1.f), Vector3F(1.f,1.f,1.f), Vector3F(1.f,-1.f,1.f),
Vector3F(-1.f,-1.f,-1.f), Vector3F(-1.f,-1.f,1.f), Vector3F(-1.f,1.f,1.f), Vector3F(-1.f,1.f,-1.f),
Vector3F(1.f,-1.f,-1.f), Vector3F(1.f,-1.f,1.f), Vector3F(1.f,1.f,1.f), Vector3F(1.f,1.f,-1.f)
};
Index indices[] = { 0, 2, 1, 0, 3, 2,
4, 5, 6, 4, 6, 7,
8, 9, 10, 8, 10, 11,
12, 15, 14, 12, 14, 13,
16, 17, 18, 16, 18, 19,
20, 23, 22, 20, 22, 21
};
Vector2F texcoords[] = {Vector2F(1.f, 1.f), Vector2F(1.f, 0.f), Vector2F(0.f, 0.f), Vector2F(0.f, 1.f),
Vector2F(1.f, 1.F), Vector2F(1.f, 0.f), Vector2F(0.f, 0.f), Vector2F(0.f, 1.f),
Vector2F(1.f, 1.F), Vector2F(1.f, 0.f), Vector2F(0.f, 0.f), Vector2F(0.f, 1.f),
Vector2F(1.f, 1.F), Vector2F(1.f, 0.f), Vector2F(0.f, 0.f), Vector2F(0.f, 1.f),
Vector2F(1.f, 1.F), Vector2F(1.f, 0.f), Vector2F(0.f, 0.f), Vector2F(0.f, 1.f),
Vector2F(1.f, 1.F), Vector2F(1.f, 0.f), Vector2F(0.f, 0.f), Vector2F(0.f, 1.f)
};
Vector3F normals[] = { Vector3F::NEGUNIT_Y, Vector3F::NEGUNIT_Y, Vector3F::NEGUNIT_Y, Vector3F::NEGUNIT_Y,
Vector3F::UNIT_Y, Vector3F::UNIT_Y, Vector3F::UNIT_Y, Vector3F::UNIT_Y,
Vector3F::NEGUNIT_Z, Vector3F::NEGUNIT_Z, Vector3F::NEGUNIT_Z, Vector3F::NEGUNIT_Z,
Vector3F::UNIT_Z, Vector3F::UNIT_Z, Vector3F::UNIT_Z, Vector3F::UNIT_Z,
Vector3F::NEGUNIT_X, Vector3F::NEGUNIT_X, Vector3F::NEGUNIT_X, Vector3F::NEGUNIT_X,
Vector3F::UNIT_X, Vector3F::UNIT_X, Vector3F::UNIT_X, Vector3F::UNIT_X
};
CreateVAO(pMeshName, pShader, position, sizeof(position), indices, sizeof(indices));
switch(mType){
case ET_MESH:
Make(normals,texcoords);break;
case ET_OBJECT:
Make(normals);break;
case ET_DEBUGOBJECT:
Make(texcoords);break;
}
}
// :[
void Entity::MakeSphere(const std::string &pMeshName, Shader &pShader, s32 pSlices){
std::vector<Vector3F> vertices;
std::vector<Vector2F> texcoords;
std::vector<Vector3F> normals;
std::vector<Index> indices;
Vector3F v;
f32 angleStep = 2.f * Math::Pi / (f32)pSlices;
int midP = pSlices;
for(int i = 0; i < pSlices; ++i)
for(int j = 0; j < pSlices; ++j){
v.x = Math::Sin(angleStep * (f32)i) * Math::Sin(angleStep * (f32)j);
v.y = Math::Cos(angleStep * (f32)i);
v.z = Math::Sin(angleStep * (f32)i) * Math::Cos(angleStep * (f32)j);
vertices.push_back(v);
normals.push_back(v);
texcoords.push_back(Vector2F((f32)j / (f32)pSlices, (1.f - (f32)i) / (f32)(pSlices - 1)));
}
for(int i = 0; i < pSlices; ++i)
for(int j = 0; j < pSlices; ++j){
indices.push_back( i * (pSlices + 1) + j);
indices.push_back((i+1) * (pSlices + 1) + j);
indices.push_back((i+1) * (pSlices + 1) + (j + 1));
indices.push_back( i * (pSlices + 1) + j);
indices.push_back((i+1) * (pSlices + 1) + (j + 1));
indices.push_back( i * (pSlices + 1) + (j + 1));
}
CreateVAO(pMeshName, pShader, &vertices[0], vertices.size() * sizeof(Vector3F), &indices[0], indices.size() * sizeof(Index));
Make(&normals[0]);
}
} | C++ |
#ifndef STRING_HPP
#define STRING_HPP
#include <sstream>
#include <vector>
#include <algorithm>
#include <cctype>
#include "StringConverter.hpp"
namespace engine {
/// \brief Ease of use class for string managment, allowing String creation from multiple types
class OOXAPI String{
public:
/// \brief Default Ctor
String(){ mString << "";}
/// \brief Copy Ctor
String(const String &s){ mString << s.str(); }
/// \brief Ctor from any data type
template<typename T> String(const T& ppValue);
/// \brief Operators allowing concatenation of different data types
template<typename T> String& operator+(const T &ppValue);
template<typename T> String& operator+=(const T &ppValue);
/// \brief Stream operator (maybe useless with above one)
friend std::ostream& operator<<(std::ostream& oss, const String &pStr);
/// \brief Cast operator in std::string
operator std::string() const;
/// \brief Explicit Cast operator in std::string
std::string str() const;
/// \brief Comparison operators
bool operator==(const std::string &pStr) const;
bool operator !=(const std::string &pStr) const;
/// \brief Affectation operators
void operator=(const std::string &pStr);
void operator=(const String &pStr);
/// \brief Returns the oss for string operations
std::ostringstream& ostr();
/// \brief Returns the String length
size_t size() const;
/// \brief Returns true if the String is empty
bool Empty() const;
/// \brief Returns true if the String is a commentary (begins with "//")
bool IsCommentary() const;
protected:
std::ostringstream mString;
};
/// \brief Vector of strings
typedef std::vector<std::string> StringVector;
/// \brief String utility functions
class OOXAPI StringUtils{
public:
/// \brief Splits a string according to different separators
/// \param pIn : input string to be splitted
/// \param pSep : different char separators
/// \param pMaxSplit : max splits operation. 0 means infinite
static StringVector SplitString(const std::string &pIn, const std::string &pSep = "\t\n ", u32 pMaxSplit = 0);
/// \brief Returns the lower case input string
static std::string ToLower(const std::string &pStr);
/// \brief Returns the upper case input string
static std::string ToUpper(const std::string &pStr);
/// \brief Returns only the extension of a complete file name
static std::string GetExtension(const std::string &pFileName);
/// \brief Returns only the file name without its extension
static std::string GetFileName(const std::string &pFileName);
/// \brief Check if a string begins by another
/// \param pStr : string to check
/// \param pStart : substring used for comparison
/// \param pLowerCase : true for a case insensitive comparison
static bool StartsWith(const std::string &pStr, const std::string &pStart, bool pLowerCase = true);
};
#include "String.inl"
}
#endif
| C++ |
#ifndef SPOINTERPOLICIES_HPP
#define SPOINTERPOLICIES_HPP
#include <cstdlib>
#include "Debug/New.hpp"
namespace engine {
/// \brief Reference counting policy
template<class T>
class RefCountPolicy{
public:
RefCountPolicy() : mCounter(new int(1)) {}
/// \brief Add a reference
T* Clone(T* pPtr){
++*mCounter;
return pPtr;
}
/// \brief Substract a reference, and delete pointer if needed
void Release(T* pPtr){
if(--*mCounter == 0){
delete mCounter;
delete pPtr;
}
}
/// \brief Swap two Refcount policies
void Swap(RefCountPolicy &pRefCount){
std::swap(pRefCount.mCounter, mCounter);
}
private:
int* mCounter;
};
/// \brief Resource-Type counting policy
template<class T>
class ResourceTypePolicy{
public:
/// \brief Add a reference to resource
T* Clone(T* pPtr){
if(pPtr)
pPtr->AddRef();
return pPtr;
}
/// \brief Release a reference to resource
static void Release(T* pPtr){
if(pPtr)
pPtr->Release();
}
/// \brief Swap. Do nothing
void Swap(ResourceTypePolicy &p){
}
};
#include "Debug/NewOff.hpp"
}
#endif
| C++ |
#include <sstream>
#include "File.hpp"
#include "Debug/Exceptions.hpp"
#include "Debug/New.hpp"
namespace engine {
File::File() : mFileName(""){
}
File::File(const std::string &pFilename, eReadWriteMode pRwm, eFilePos pFp) {
Open(pFilename, pRwm, pFp);
}
File::~File(){
Close();
}
void File::Open(const std::string &pFilename, eReadWriteMode pRwm, eFilePos pFp){
std::ios_base::openmode mode;
switch(pRwm){
case RWM_Write:
mode = std::fstream::in | std::fstream::out | std::fstream::trunc; break;
case RWM_Open :
mode = std::fstream::in | std::fstream::out; break;
case RWM_ReadOnly :
mode = std::fstream::in; break;
default: throw LoadingFailed(pFilename, "ReadWriteMode is invalid!");
}
switch(pFp){
case FP_Top:
break;
case FP_Bottom:
mode |= std::fstream::ate; break;
default:
throw LoadingFailed(pFilename, "File Positionment value is invalid!");
}
mFileName = pFilename;
mFile.open(pFilename.c_str(), mode);
}
void File::Close(){
if(IsOpened())
mFile.close();
}
void File::Flush(){
if(IsOpened())
mFile.flush();
}
bool File::IsOpened() const{
return mFile.is_open();
}
bool File::Exists(const std::string &pFilename){
std::ifstream readFile(pFilename.c_str());
return readFile.is_open();
}
std::string File::Filename() const{
return mFileName;
}
bool File::End() const{
return mFile.eof();
}
std::string File::GetLine(){
std::string line;
getline(mFile, line);
return line;
}
std::string File::Read() const{
if(mFile){
std::stringstream buffer;
buffer << mFile.rdbuf();
std::string ret(buffer.str());
ret.push_back('\0');
return ret;
}else
throw Exception("Tried to read an inexistant file : "+mFileName);
}
/*
void File::GoTo(FilePos pos){
if(mFile.is_open())
switch(pos){
case BEG: mFile.seekg(0, ios::beg); break;
case END: mFile.seekg(0, ios::end); break;
case NEXT: JumpLine(); break;
default:break;
}
}
s
string File::GetUntil(string s, char c){
size_t pos = s.find_first_of(c);
if(pos >= 10000){
pos = 0;
ErrLog << "File : in " << s << ", " << c << " is not present!" << eol;
}
return s.substr(0,pos);
}
*/
}
| C++ |
#include "Color.hpp"
namespace engine {
const Color Color::Black(0.f,0.f,0.f,1.f);
const Color Color::White(1.f,1.f,1.f,1.f);
const Color Color::Red(1.f,0.f,0.f,1.f);
const Color Color::Green(0.f,1.f,0.f,1.f);
const Color Color::Blue(0.f,0.f,1.f,1.f);
const Color Color::Magenta(1.f,0.f,1.f,1.f);
const Color Color::Cyan(0.f,1.f,1.f,1.f);
const Color Color::Yellow(1.f,1.f,0.f,1.f);
const Color Color::Orange(1.f,0.5f,0.f,1.f);
const Color Color::Grey(0.5f,0.5f,0.5f,1.f);
Color::Color(f32 R, f32 G, f32 B, f32 A) : r(R), g(G), b(B), a(A){
}
void Color::RGB(float pTab[]) const{
pTab[0] = r;
pTab[1] = g;
pTab[2] = b;
}
void Color::RGBA(float pTab[]) const{
pTab[0] = r;
pTab[1] = g;
pTab[2] = b;
pTab[3] = a;
}
void Color::RGB(f32 pR, f32 pG, f32 pB){
r = pR;
g = pG;
b = pB;
}
void Color::RGBA(f32 pR, f32 pG, f32 pB, f32 pA){
r = pR;
g = pG;
b = pB;
a = pA;
}
Color To00xColor(const sf::Color &pColor){
return Color(pColor.r / 255.f, pColor.g / 255.f, pColor.b / 255.f, pColor.a / 255.f);
}
sf::Color ToSFMLColor(const Color &pColor){
return sf::Color(static_cast<u8>(pColor.R() * 255),
static_cast<u8>(pColor.G() * 255),
static_cast<u8>(pColor.B() * 255),
static_cast<u8>(pColor.A() * 255));
}
}
| C++ |
#ifndef SINGLETON_HPP
#define SINGLETON_HPP
#include "Debug/New.hpp"
namespace engine{
/// \brief Classic Singleton class to store an object pointer in its only instance
template<class T>
class Singleton{
private:
/// \brief Pointer on object stored by singleton
static T *mSingleton;
/// \brief Copy Ctor, forbidden
Singleton(Singleton &){}
/// \brief Copy Op, forbidden
void operator=(Singleton &){}
protected:
/// \brief Default Ctor/Dtor, forbidden
Singleton(){}
~Singleton(){}
public:
/// \brief Returns a pointer on stored object
static T* Get(){
if(mSingleton == 0)
mSingleton = new T;
return (static_cast<T*> (mSingleton));
}
/// \brief Returns the reference of stored object
static T& Call(){
if(mSingleton == 0)
mSingleton = new T;
return *mSingleton;
}
/// \brief Destroy the stored object
static void Kill(){
if(mSingleton != 0){
delete mSingleton;
mSingleton = 0;
}
}
};
/// Initialisation
template<class T> T *Singleton<T>::mSingleton = 0;
}
#include "Debug/NewOff.hpp"
#endif
| C++ |
// CORE
#include "Core/Camera.hpp"
#include "Core/Entity.hpp"
#include "Core/Enums.hpp"
#include "Core/Frustum.hpp"
#include "Core/Image.hpp"
#include "Core/Input.hpp"
#include "Core/Resource.hpp"
#include "Core/ResourceManager.hpp"
#include "Core/Settings.hpp"
#include "Core/Window.hpp"
// DEBUG
#include "Debug/Exceptions.hpp"
#include "Debug/Logger.hpp"
#include "Debug/MemoryManager.hpp"
// MATH
#include "Math/AABB.hpp"
#include "Math/Mathlib.hpp"
#include "Math/Matrix4.hpp"
#include "Math/Quaternion.hpp"
#include "Math/Rectangle.hpp"
#include "Math/Vector2.hpp"
#include "Math/Vector3.hpp"
// RENDERER
#include "Renderer/Light.hpp"
#include "Renderer/Renderer.hpp"
#include "Renderer/Shader.hpp"
#include "Renderer/Text.hpp"
#include "Renderer/Texture.hpp"
#include "Renderer/VAO.hpp"
#include "Renderer/VBO.hpp"
// UTILS
#include "Utils/Clock.hpp"
#include "Utils/File.hpp"
#include "Utils/Keys.hpp"
#include "Utils/SPointer.hpp"
#include "Utils/Shared.hpp"
#include "Utils/Singleton.hpp"
#include "Utils/String.hpp"
#include "Utils/StringConverter.hpp"
| C++ |
#ifndef TEXT_HPP
#define TEXT_HPP
#include "Math/Vector2.hpp"
#include "Utils/Color.hpp"
namespace engine {
/// \brief Wrapper class for SFML Text
class OOXAPI Text{
public:
Text();
Text( const Vector2I &pPosition,
const std::string &pText,
const Color &pColor = Color::Black,
const sf::Font &pFont = sf::Font::GetDefaultFont(),
u16 pSize = 15,
bool pBold = false,
bool pItalic = false);
/// \brief Add this text to the renderer text drawlist
void Draw();
/// \brief Change the text string
void SetText(const std::string &pText);
/// \brief Change the text position
void SetPosition(const Vector2I &pPos);
void SetPosition(s16 x, s16 y);
/// \brief Change the text font
void SetFont(const std::string &pFontName);
/// \brief Change the text color
void SetColor(const Color &pColor);
/// \brief Change the text size
void SetSize(u16 pSize);
/// \brief Make the text bold or not
void SetBold(bool pVal);
/// \brief Make the text Italic or not
void SetItalic(bool pVal);
/// Getters
Vector2I GetPosition() const { return To00xVector2I(mText.GetPosition()); }
Color GetColor() const { return To00xColor(mText.GetColor()); }
u16 GetSize() const { return mText.GetCharacterSize(); }
std::string GetText() const { return mText.GetString(); }
const sf::Text& GetSFMLText() const { return mText; }
private:
sf::Text mText; /// SFML text used to render text
/// Text Style, keep record for changes
bool mBold;
bool mItalic;
/// Internal function called after a SetBold/Italic function
void ChangeTextStyle();
};
}
#endif
| C++ |
#ifndef RENDERER_HPP
#define RENDER_HPP
#include <map>
#include "Text.hpp"
#include "Texture.hpp"
#include "Math/Matrix4.hpp"
#include "Utils/Singleton.hpp"
#include "Core/Enums.hpp"
namespace engine {
class Color;
class Shader;
class Entity;
class Object;
class Mesh;
class DebugObject;
class Window;
class Camera;
struct RendererSpecs{
/// Max and User Wanted Anisotropy Levels
u32 mMaximumAnisotropy;
u32 mWantedAnisotropy;
/// Max and User Wanted Anti-Aliasing Levels
s16 mMaximumMultiSamples;
s16 mWantedMultiSamples;
/// BackFace Culling Face
u32 mCullingFace;
/// Field of View
f32 mFOV;
/// Near & Far plane
f32 mNearPlane;
f32 mFarPlane;
/// Ambient Color
Color mAmbientColor;
/// Wireframe mode
bool mWireframe;
bool mWireframeChange;
/// Vertical Synchronisation
bool mVsync;
};
class OOXAPI Renderer : public Singleton<Renderer>{
friend class Singleton<Renderer>;
public:
/// \brief Initialize the Renderer from Window
/// \param pWindow : Window used to Render
void Init(Window &pWindow);
/// \brief Function called before rendering every frame
/// \param pColor : Window background color
void BeginScene(const Color &pColor) const;
/// \brief Function called right after rendering every frame
void EndScene();
/// \brief Returns a pointer on the associated window
const Window* GetWindow() { return mWindow; }
/// \brief Returns the renderer specifications
const RendererSpecs& GetSpecifications() const { return mSpecs; }
// Functions used to render a drawable object with the renderer
/// \brief Add a Mesh to the next frame drawing list
void DrawMesh(Mesh* pEntity);
/// \brief Add an Object to the next frame drawing list
void DrawObject(Object* pEntity);
/// \brief Add a DebugObject to the next frame drawing list
void DrawDebugObject(DebugObject* pEntity);
/// \brief Add a Text to the next frame drawing list
void DrawText(Text* pText);
/// \brief Render the drawable objects of the current frame
void Render();
/// \brief Change the Field of View
void SetFOV(f32 pFov);
/// \brief Change the Wireframe Mode
void WireframeMode(bool pVal);
/// \brief Resize the Window with the associated window new Width and Height
void Resize();
/// Matrix
/// \brief Change the current 2D Projection Matrix
void Set2DProjectionMatrix(const Matrix4 &pProj) { m2DProjectionMatrix = pProj; }
/// \brief Change the current 3D Projection Matrix
void Set3DProjectionMatrix(const Matrix4 &pProj) { m3DProjectionMatrix = pProj; }
/// \brief Change the current 3D View Matrix. Changes also the ViewProj and Normal Matrices accordingly
void Set3DViewMatrix(const Matrix4 &pView){
m3DViewMatrix = pView;
m3DViewProjMatrix = m3DViewMatrix * m3DProjectionMatrix;
m3DNormalMatrix = m3DViewMatrix.Inverse();
m3DNormalMatrix = m3DNormalMatrix.Transpose();
}
/// Getters
const Matrix4& Get2DProjectionMatrix() const { return m2DProjectionMatrix; }
const Matrix4& Get3DProjectionMatrix() const { return m3DProjectionMatrix; }
const Matrix4& Get3DViewProjMatrix() const { return m3DViewProjMatrix; }
const Matrix4& Get3DNormalMatrix() const { return m3DNormalMatrix; }
const Matrix4& Get3DViewMatrix() const { return m3DViewMatrix; }
/// Camera
/// \brief Set current camera from pointer
void SetCamera(Camera* pCamera) { mCamera = pCamera; }
/// \brief Returns a pointer on the current camera
const Camera* GetCamera() const { return mCamera; }
private:
/// Private Ctor/Dtor (Singleton)
Renderer();
~Renderer();
/// Window
Window* mWindow;
u32 mWindowWidth, mWindowHeight;
/// Camera
Camera* mCamera;
/// Specifications
RendererSpecs mSpecs;
/// Vector containing Objects to be drawn next frame
typedef std::vector<Object*> ObjectMap;
ObjectMap mObjectMap;
ObjectMap::iterator mObjectMapIt;
/// Vector containing Meshes to be drawn next frame
typedef std::vector<Mesh*> MeshMap;
MeshMap mMeshMap;
MeshMap::iterator mMeshMapIt;
/// Vector containing DebugObjects to be drawn next frame
typedef std::vector<DebugObject*> DebugObjectMap;
DebugObjectMap mDebugObjectMap;
DebugObjectMap::iterator mDebugObjectMapIt;
/// Number of drawed entities every frame
Text mEntityNumberText;
u16 mEntityNumber, mLastFrameEntityNumber;
/// Vector containing Objects to be drawn next frame
typedef std::vector<Text*> TextMap;
TextMap mTextMap;
TextMap::iterator mTextMapIt;
/// Matrices used by the renderer
Matrix4 m3DViewMatrix, m3DProjectionMatrix, m3DViewProjMatrix, m3DNormalMatrix;
Matrix4 m2DProjectionMatrix;
/// FUNCTIONS
/// Specific drawable object rendering functions
/// \brief Text Rendering
void RenderTexts();
/// \brief Objects Rendering
void RenderObjects();
/// \brief Meshes Rendering
void RenderMeshes();
/// \brief DebugObject Rendering
void RenderDebugObjects();
};
}
#endif
| C++ |
#include "VBO.hpp"
#include "Utils/Color.hpp"
#include "Utils/String.hpp"
#include "Debug/Exceptions.hpp"
#include "Debug/New.hpp"
namespace engine {
GLenum GetUsage(eBufferUsage usage){
GLenum ret;
switch(usage){
case BU_Static: ret = GL_STATIC_DRAW; break;
case BU_Stream: ret = GL_STREAM_DRAW; break;
case BU_Dynamic: ret = GL_DYNAMIC_DRAW; break;
}
return ret;
}
VBO::VBO() : mVbo(0), mType(BT_VERTEX), mUsage(BU_Static){
}
VBO::~VBO(){
if(mVbo)
Destroy();
}
void VBO::Destroy(){
glDeleteBuffers(1, &mVbo);
}
void VBO::Generate(const Index* pIndices, u32 pSize, eBufferUsage usage){
// On élimine les buffers contenus précédement
if(mVbo)
Destroy();
// On génère le bufer
glGenBuffers(1, &mVbo);
// On Lock le Buffer en mémoire et on le remplit
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mVbo);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, pSize, pIndices, GetUsage(usage));
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
// On change le type en IBO et l'usage
mType = BT_INDEX;
mUsage = usage;
}
void VBO::Generate(const Vector3F* pVector, u32 pSize, eBufferUsage usage){
// On élimine les buffers contenus précédement
if(mVbo)
Destroy();
// On génère le bufer
glGenBuffers(1, &mVbo);
// On Lock le Buffer en mémoire et on le remplit
glBindBuffer(GL_ARRAY_BUFFER, mVbo);
glBufferData(GL_ARRAY_BUFFER, pSize, pVector, GetUsage(usage));
glBindBuffer(GL_ARRAY_BUFFER, 0);
// changement possible de l'usage
mUsage = usage;
}
void VBO::Generate(const Vector2F* pVector, u32 pSize, eBufferUsage usage){
// On élimine les buffers contenus précédement
if(mVbo)
Destroy();
// On génère le bufer
glGenBuffers(1, &mVbo);
// On Lock le Buffer en mémoire et on le remplit
glBindBuffer(GL_ARRAY_BUFFER, mVbo);
glBufferData(GL_ARRAY_BUFFER, pSize, pVector, GetUsage(usage));
glBindBuffer(GL_ARRAY_BUFFER, 0);
// changement possible de l'usage
mUsage = usage;
}
void VBO::Update(const Vector3F* pVector, u32 pSize){
// Check si le buffer est dynamic
//if(mUsage != BU_Dynamic)
// throw Exception("VBO : Tried to Update a static buffer.");
glBindBuffer(GL_ARRAY_BUFFER, mVbo);
glBufferData(GL_ARRAY_BUFFER, 0, NULL, GetUsage(mUsage));
glBufferData(GL_ARRAY_BUFFER, pSize, pVector, GetUsage(mUsage));
glBindBuffer(GL_ARRAY_BUFFER, 0);
}
void VBO::Update(const Vector2F* pVector, u32 pSize){
// Check si le buffer est dynamic
//if(mUsage != BU_Dynamic)
// throw Exception("VBO : Tried to Update a static buffer.");
glBindBuffer(GL_ARRAY_BUFFER, mVbo);
glBufferData(GL_ARRAY_BUFFER, 0, NULL, GetUsage(mUsage));
glBufferData(GL_ARRAY_BUFFER, pSize, pVector, GetUsage(mUsage));
glBindBuffer(GL_ARRAY_BUFFER, 0);
}
void VBO::Update(const Index* pVector, u32 pSize){
// Check si le buffer est dynamic
//if(mUsage != BU_Dynamic)
// throw Exception("VBO : Tried to Update a static buffer.");
glBindBuffer(GL_ARRAY_BUFFER, mVbo);
glBufferData(GL_ARRAY_BUFFER, 0, NULL, GetUsage(mUsage));
glBufferData(GL_ARRAY_BUFFER, pSize, pVector, GetUsage(mUsage));
glBindBuffer(GL_ARRAY_BUFFER, 0);
}
}
| C++ |
#ifndef TEXTURE_HPP
#define TEXTURE_HPP
#include "Core/Image.hpp"
#include "Math/Rectangle.hpp"
namespace engine {
/// \brief Wrapper class for OpenGL Texture, load from Image only
class OOXAPI Texture{
public:
Texture();
~Texture();
/// \brief Load the OpenGL Texture from an Image
/// \param pImage : Image to use
/// \param pSubRect : SubRect optionnel (partie d'une image)
void LoadFromImage(const Image &pImage, const Rectangle &pSubRect = Rectangle(0,0,0,0));
/// \brief Bind the texture to OpenGL Render State
void Bind() const;
/// \brief Unbind the texture
void UnBind() const;
/// \brief Destroy the OpenGL Texture
void Destroy();
private:
GLuint mTexture; /// Texture ID
};
}
#endif
| C++ |
#ifndef SHADER_HPP
#define SHADER_HPP
#include "Core/Resource.hpp"
#include "Utils/SPointer.hpp"
#include "Utils/Shared.hpp"
#include "Math/Vector2.hpp"
#include "Math/Vector3.hpp"
namespace engine {
class Color;
class Matrix4;
/// \brief Wrapper class for GLSL Shader Program, with Vertex/Fragment/Geometry shader loading and compilation
class OOXAPI Shader : public IResource{
public:
Shader();
~Shader();
/// \brief Destroy the program
void Destroy();
/// \brief Compile the shader from sources
/// \param pVSName : Vertex Shader source file name
/// \param pFSName : Fragment Shader source file name
/// \param pGSName : Geometry Shader source file name
void Compile(const std::string &pVSName, const std::string &pFSName, const std::string &pGSName = "");
/// \brief Bind the shader to the OpenGL State
void Bind() const;
/// \brief Unbind the Shader
void UnBind() const;
/// \brief Returns the Shader ID
GLuint GetProgram() { return mProgram; }
/// Send/Access functions for sending uniform variables
/// \brief Matrix 4x4
/// \param pVarName : Variable name in shader source
/// \param pMatrix : matrix to send
void SendMatrix4(const std::string &pVarName, const Matrix4 &pMatrix);
/// \brief Vector 3
/// \param pVarName : Variable name in shader source
/// \param pVector : vector to send
void SendVector3(const std::string &pVarName, const Vector3F &pVector);
/// \brief Vector 2
/// \param pVarName : Variable name in shader source
/// \param pVector : vector to send
void SendVector2(const std::string &pVarName, const Vector2F &pVector);
/// \brief Color
/// \param pVarName : Variable name in shader source
/// \param pColor : color to send
void SendColor(const std::string &pVarName, const Color &pColor);
/// \brief Float
/// \param pVarName : Variable name in shader source
/// \param pVar : float to send
void SendFloat(const std::string &pVarName, f32 pVar);
private:
/// \brief Private method used by Compile to load a Vertex Shader from source
void LoadVertexShader(const std::string &pFilename);
/// \brief Private method used by Compile to load a Fragment Shader from source
void LoadFragmentShader(const std::string &pFilename);
/// \brief Private method used by Compile to load a Geometry Shader from source
void LoadGeometryShader(const std::string &pFilename);
GLuint mProgram; /// Program ID
GLuint mVShader; /// Vertex Shader ID
GLuint mFShader; /// Fragment Shader ID
GLuint mGShader; /// Geometry Shader ID
};
typedef SPointer<Shader, ResourceTypePolicy> ShaderPtr;
}
#endif
| C++ |
#include "Shader.hpp"
#include "Core/ResourceManager.hpp"
//#include "Core/DataManager.hpp"
#include "Math/Matrix4.hpp"
#include "Utils/Color.hpp"
#include "Utils/File.hpp"
#include "Utils/String.hpp"
#include "Debug/Exceptions.hpp"
#include "Debug/New.hpp"
#include <iostream>
namespace engine {
Shader::Shader() : mProgram(0), mVShader(0), mFShader(0), mGShader(0){
}
Shader::~Shader(){
Destroy();
}
void Shader::Destroy(){
if(mProgram)
glDeleteProgram(mProgram);
}
void Shader::LoadVertexShader(const std::string &pFilename){
// Creation des shaders
mVShader = glCreateShader(GL_VERTEX_SHADER);
// Récupération de la source
std::string filePath = ResourceManager::Call().FindFile(pFilename, "Shader");
if(filePath == "0")
throw Exception(String("Vertex Shader file \"")+pFilename+"\" does not exist. Double check file path!");
File vFile(filePath);
std::string vSourceStr = vFile.Read();
const char* vSource = vSourceStr.c_str();
glShaderSource(mVShader, 1, &vSource, NULL);
// Compilation
glCompileShader(mVShader);
// Vérification
GLint error;
glGetShaderiv(mVShader, GL_COMPILE_STATUS, &error);
if(error != GL_TRUE){
char log[1024];
glGetShaderInfoLog(mVShader, 1024, NULL, log);
glDeleteShader(mVShader);
if(mFShader)
glDeleteShader(mFShader);
if(mGShader)
glDeleteShader(mGShader);
throw Exception(String("Vertex Shader Compilation Error (\"")+pFilename+"\") :\n"+log);
}
}
void Shader::LoadFragmentShader(const std::string &pFilename){
// Creation des shaders
mFShader = glCreateShader(GL_FRAGMENT_SHADER);
// Récupération de la source
std::string filePath = ResourceManager::Call().FindFile(pFilename, "Shader");
if(filePath == "0")
throw Exception(String("Fragment Shader file \"")+pFilename+"\" does not exist. Double check file path!");
File fFile(filePath);
std::string fSourceStr = fFile.Read();
const char* fSource = fSourceStr.c_str();
glShaderSource(mFShader, 1, &fSource, NULL);
// Compilation
glCompileShader(mFShader);
// Vérification
GLint error;
glGetShaderiv(mFShader, GL_COMPILE_STATUS, &error);
if(error != GL_TRUE){
char log[1024];
glGetShaderInfoLog(mFShader, 1024, NULL, log);
if(mVShader)
glDeleteShader(mVShader);
glDeleteShader(mFShader);
if(mGShader)
glDeleteShader(mGShader);
throw Exception(String("Fragment Shader Compilation Error (\"")+pFilename+"\") :\n"+log);
}
}
void Shader::LoadGeometryShader(const std::string &pFilename){
// Creation des shaders
mGShader = glCreateShader(GL_GEOMETRY_SHADER);
// Récupération de la source
std::string filePath = ResourceManager::Call().FindFile(pFilename, "Shader");
if(filePath == "0")
throw Exception(String("Geometry Shader file \"")+pFilename+"\" does not exist. Double check file path!");
File gFile(filePath);
std::string gSourceStr = gFile.Read();
const char* gSource = gSourceStr.c_str();
glShaderSource(mGShader, 1, &gSource, NULL);
// Compilation
glCompileShader(mGShader);
// Vérification
GLint error;
glGetShaderiv(mGShader, GL_COMPILE_STATUS, &error);
if(error != GL_TRUE){
char log[1024];
glGetShaderInfoLog(mGShader, 1024, NULL, log);
if(mVShader)
glDeleteShader(mVShader);
if(mFShader)
glDeleteShader(mFShader);
glDeleteShader(mGShader);
throw Exception(String("Geometry Shader Compilation Error (\"")+pFilename+"\") :\n"+log);
}
}
void Shader::Compile(const std::string &pVSName, const std::string &pFSName, const std::string &pGSName){
std::string all = String(pVSName)+pFSName+pGSName;
Shader* tmp = ResourceManager::Call().Get<Shader>(all);
if(tmp != 0){
//Shader existe deja, on copie ses identifiants dans celui ci
mProgram = tmp->mProgram;
}else{
//Shader n'existe pas, on le cree
// Ajout du shader au ResourceManager
ResourceManager::Call().Add(all, this);
// Chargement des fichiers shaders
LoadVertexShader(pVSName);
LoadFragmentShader(pFSName);
if(!pGSName.empty())
LoadGeometryShader(pGSName);
// Creation du shader mProgram
mProgram = glCreateProgram();
// Linkage des deux shaders précédemment créés
glAttachShader(mProgram, mVShader);
glAttachShader(mProgram, mFShader);
if(mGShader)
glAttachShader(mProgram, mGShader);
// Linkage du mProgramme a OGL
glLinkProgram(mProgram);
GLint error;
glGetProgramiv(mProgram, GL_LINK_STATUS, &error);
if(!error){
char log[1024];
glGetProgramInfoLog(mProgram, 1024, NULL, log);
if(mVShader)
glDeleteShader(mVShader);
if(mFShader)
glDeleteShader(mFShader);
if(mGShader)
glDeleteShader(mGShader);
throw Exception(String("Shader Link Error :\n")+log);
}
// Destruction des Shaders. ils sont maintenant dans le program
glDeleteShader(mVShader);
glDeleteShader(mFShader);
if(mGShader)
glDeleteShader(mGShader);
// Attribution des texCoords
glUseProgram(mProgram);
glUniform1i(glGetUniformLocation(mProgram, "tex"), 0);
glBindFragDataLocation(mProgram, 0, "finalColor");
glUseProgram(0);
}
}
void Shader::Bind() const{
glUseProgram(mProgram);
}
void Shader::UnBind() const{
glUseProgram(0);
}
void Shader::SendMatrix4(const std::string &pVarName, const Matrix4 &pMatrix){
glUniformMatrix4fv(glGetUniformLocation(mProgram, pVarName.c_str()), 1, GL_FALSE, pMatrix);
#ifdef _DEBUG
GLenum error = GL_NO_ERROR;
if((error = glGetError()) != GL_NO_ERROR){
throw Exception(String("OpenGL Error: \"")+GetGLErrorStr(error)+"\" in function \"SendMatrix4\"\n\tDoes \""+pVarName+"\" exists or has the right type?");
}
#endif
}
void Shader::SendVector3(const std::string &pVarName, const Vector3F &pVector){
float toSend[3];
pVector.XYZ(toSend);
glUniform3fv(glGetUniformLocation(mProgram, pVarName.c_str()), 1, toSend);
#ifdef _DEBUG
GLenum error = GL_NO_ERROR;
if((error = glGetError()) != GL_NO_ERROR){
throw Exception(String("OpenGL Error: \"")+GetGLErrorStr(error)+"\" in function \"SendVector3\"\n\tDoes \""+pVarName+"\" exists or has the right type?");
}
#endif
}
void Shader::SendVector2(const std::string &pVarName, const Vector2F &pVector){
float toSend[2];
pVector.XY(toSend);
glUniform2fv(glGetUniformLocation(mProgram, pVarName.c_str()), 1, toSend);
#ifdef _DEBUG
GLenum error = GL_NO_ERROR;
if((error = glGetError()) != GL_NO_ERROR){
throw Exception(String("OpenGL Error: \"")+GetGLErrorStr(error)+"\" in function \"SendVector2\"\n\tDoes \""+pVarName+"\" exists or has the right type?");
}
#endif
}
void Shader::SendColor(const std::string &pVarName, const Color &pColor){
float toSend[4];
pColor.RGBA(toSend);
glUniform4fv(glGetUniformLocation(mProgram, pVarName.c_str()), 1, toSend);
#ifdef _DEBUG
GLenum error = GL_NO_ERROR;
if((error = glGetError()) != GL_NO_ERROR){
throw Exception(String("OpenGL Error: \"")+GetGLErrorStr(error)+"\" in function \"SendColor\"\n\tDoes \""+pVarName+"\" exists or has the right type?");
}
#endif
}
void Shader::SendFloat(const std::string &pVarName, f32 pVar){
glUniform1f(glGetUniformLocation(mProgram, pVarName.c_str()), pVar);
#ifdef _DEBUG
GLenum error = GL_NO_ERROR;
if((error = glGetError()) != GL_NO_ERROR){
throw Exception(String("OpenGL Error: \"")+GetGLErrorStr(error)+"\" in function \"SendFloat\"\n\tDoes \""+pVarName+"\" exists or has the right type?");
}
#endif
}
}
| C++ |
#ifndef VAO_HPP
#define VAO_HPP
#include "VBO.hpp"
#include "Core/Resource.hpp"
#include "Utils/SPointer.hpp"
namespace engine {
class Shader;
class Color;
class VAO;
typedef SPointer<VAO, ResourceTypePolicy> VAOPtr;
/// \brief Interface Wrapper Class for OpenGL VAO
/// - Use it as it is for only Vertice Position/Indices
/// - Use one of the inherited class (ColorVAO, ColorMesh, TexMesh) for advanced uses
class OOXAPI VAO : public IResource{
public:
VAO();
~VAO();
/// \brief Generate the VAO and its included VBO from Vertices/Indices arrays
/// \param pShader : pointer on the Shader used to draw the VAO
/// \param pVertices : Array of Positions (Vector3F)
/// \param pVerticeSize : Size of associated arrays
/// \param pIndices : Array of Indices (Index)
/// \param pIndiceSize : Size of associated arrays
/// \param pBu : VBO Usage
void Generate(Shader* pShader, const Vector3F* pVertices, u32 pVerticeSize, const Index* pIndices, u32 pIndiceSize, eBufferUsage pBu = BU_Static);
/// \brief Update an already dynamically created VAO with new vertices/indices data
/// \param pVertices : Array of Positions (Vector3F)
/// \param pVerticeSize : Size of associated arrays
/// \param pIndices : Array of Indices (Index)
/// \param pIndiceSize : Size of associated arrays
void Update(const Vector3F* pVertices, u32 pVerticeSize, const Index* pIndices, u32 pIndiceSize);
/// \brief Copy a VAO
void CopyVAO(const VAOPtr& pVao);
/// \brief Destroy the VAO and associated VBO
void Destroy();
/// \brief Bind the VAO to OpenGL Render State
void Bind() const;
/// \brief Unbind the VAO
void UnBind() const;
/// Getters
const GLuint GetVAO() const { return mVao; }
const VBO GetVertices() const { return mVbo; }
const VBO GetIndices() const { return mIbo; }
const u32 GetVertexCount() const { return mVCount; }
const u32 GetIndexCount() const { return mICount; }
/// Setters
void SetVAO(GLuint pVao) { mVao = pVao; }
void SetVertices(VBO pVbo) { mVbo = pVbo; }
void SetIndices(VBO pIbo) { mIbo = pIbo; }
void SetVertexCount(u32 pVc) { mVCount = pVc; }
void SetIndexCount(u32 pIc) { mICount = pIc; }
/// \brief Returns if the VAO possesses indices
bool HasIndices() const { return mHasIndices; }
protected:
GLuint mVao; /// VAO ID
VBO mVbo; /// Vertice Position VBO
VBO mIbo; /// Indice VBO
u32 mVCount; /// Vertices number
u32 mICount; /// Indices number
bool mHasIndices; /// True if VAO possesses indices
};
/// \brief VAO with additionnals VBOs used for Texture Coordinates and Normals
class OOXAPI TextureMesh : public VAO{
public:
/// \brief Generate the Normal VBO with given data
/// \param pNormals : Vector3F Array for normal coordinates
/// \param pSize : size of the above array
/// \param pShader : shader used for VAO rendering
/// \param pBu : VBO Usage Flag
void GenerateNormals(const Vector3F* pNormals, u32 pSize, Shader* pShader, eBufferUsage pBu = BU_Static);
/// \brief Generate the TexCoords VBO with given data
/// \param pTexCoords : Vector2F Array for texture coordinates
/// \param pSize : size of the above array
/// \param pShader : shader used for VAO rendering
/// \param pBu : VBO Usage Flag
void GenerateTexCoords(const Vector2F* pTexCoords, u32 pSize, Shader* pShader, eBufferUsage pBu = BU_Static);
/// \brief Update an already dynamically created Normal VBO with new data
/// \param pNormals : Array of Vector3F for normal coordinates
/// \param pSize : Size of above array
void UpdateNormals(const Vector3F* pNormals, u32 pSize);
/// \brief Update an already dynamically created Texcoords VBO with new data
/// \param pTexCoords : Array of Vector2F for texture coordinates
/// \param pSize : Size of above array
void UpdateTexCoords(const Vector2F* pTexCoords, u32 pSize);
private:
VBO mNormals;
VBO mTexCoords;
};
typedef SPointer<TextureMesh, ResourceTypePolicy> TexMeshPtr;
/// \brief VAO with an additionnal VBO used for Normals
class OOXAPI ColorMesh : public VAO{
public:
/// \brief Generate the Normal VBO with given data
/// \param pNormals : Vector3F Array for normal coordinates
/// \param pSize : size of the above array
/// \param pShader : shader used for VAO rendering
/// \param pBu : VBO Usage Flag
void GenerateNormals(const Vector3F* pNormals, u32 pSize, Shader* pShader, eBufferUsage pBu = BU_Static);
/// \brief Update an already dynamically created Normal VBO with new data
/// \param pNormals : Array of Vector3F for normal coordinates
/// \param pSize : Size of above array
void UpdateNormals(const Vector3F* pNormals, u32 pSize);
private:
VBO mNormals;
};
typedef SPointer<ColorMesh, ResourceTypePolicy> ColorMeshPtr;
/// \brief VAO with an additionnal VBO used for Texture Coordinates
class OOXAPI ColorVAO : public VAO{
public:
/// \brief Generate the TexCoords VBO with given data
/// \param pTexCoords : Vector2F Array for texture coordinates
/// \param pSize : size of the above array
/// \param pShader : shader used for VAO rendering
/// \param pBu : VBO Usage Flag
void GenerateTexCoords(const Vector2F* pTexCoords, u32 pSize, Shader* pShader, eBufferUsage pBu = BU_Static);
/// \brief Update an already dynamically created Texcoords VBO with new data
/// \param pTexCoords : Array of Vector2F for texture coordinates
/// \param pSize : Size of above array
void UpdateTexCoords(const Vector2F* pTexCoords, u32 pSize);
private:
VBO mTexCoords;
};
typedef SPointer<ColorVAO, ResourceTypePolicy> ColorVAOPtr;
}
#endif
| C++ |
#ifndef LIGHT_HPP
#define LIGHT_HPP
#include "Utils/Color.hpp"
#include "Math/Vector3.hpp"
namespace engine{
/// \brief Light type. Used with shaders
enum LightType{
LTPoint,
LTDirectionnal,
LTSpot
};
/// \brief Light class containing only informations used by shaders
class Light{
public:
/// \brief Empty Ctor, initialize with default Light
Light() : mType(LTPoint),
mAmbient(Color::Black),
mDiffuse(Color::White),
mSpecular(Color::Black),
mPosition(Vector3F::ZERO),
mDirection(Vector3F::NEGUNIT_Y),
mRange(5),
mFalloff(0),
mAttenuation0(0.f),
mAttenuation1(1.f),
mAttenuation2(0.5f),
mTheta(0),
mPhi(0)
{
}
/// \brief Light Update
void Update();
/// \brief Enable or Disable the Light
void Enable(bool pVal) { mIsOn = pVal; }
/// \brief Setters
void SetPosition(const Vector3F &pPos) { mPosition = pPos; }
void SetDirection(const Vector3F &pDir) { mDirection = pDir; }
void SetRange(f32 pRange) { mRange = pRange; }
void SetFalloff(f32 pFalloff) { mFalloff = pFalloff; }
void SetAttenuationConstant(f32 pAtt) { mAttenuation0 = pAtt; }
void SetAttenuationLinear(f32 pAtt) { mAttenuation1 = pAtt; }
void SetAttenuationQuadratic(f32 pAtt) { mAttenuation2 = pAtt; }
void SetTheta(f32 pTheta) { mTheta = pTheta; }
void SetPhi(f32 pPhi) { mPhi = pPhi; }
void SetAmbient(Color pColor) { mAmbient = pColor; }
void SetDiffuse(Color pColor) { mDiffuse = pColor; }
void SetSpecular(Color pColor) { mSpecular = pColor; }
void SetType(LightType pType) { mType = pType; }
/// \brief Getters
f32 GetRange() const{ return mRange; }
f32 GetFalloff() const{ return mFalloff; }
f32 GetAttenuationConstant() const{ return mAttenuation0; }
f32 GetAttenuationLinear() const{ return mAttenuation1; }
f32 GetAttenuationQuadratic() const{ return mAttenuation2; }
f32 GetTheta() const{ return mTheta; }
f32 GetPhi() const{ return mPhi; }
LightType GetType() const{ return mType; }
Color GetAmbient() const{ return mAmbient; }
Color GetDiffuse() const{ return mDiffuse; }
Color GetSpecular() const{ return mSpecular; }
Vector3F GetPosition() const{ return mPosition; }
Vector3F GetDirection() const{ return mDirection; }
private:
bool mIsOn;
LightType mType;
Color mAmbient, mDiffuse, mSpecular;
Vector3F mPosition, mDirection;
f32 mRange, mFalloff;
f32 mAttenuation0, mAttenuation1, mAttenuation2;
f32 mTheta, mPhi;
};
}
#endif | C++ |
#include "Text.hpp"
#include "Renderer.hpp"
#include "Debug/Logger.hpp"
#include "Debug/New.hpp"
namespace engine {
Text::Text() : mBold(false), mItalic(false){
}
Text::Text( const Vector2I &pPosition, const std::string &pText, const Color &pColor, const sf::Font &pFont, u16 pSize, bool pBold, bool pItalic){
mText.SetPosition(ToSFMLVector2f(pPosition));
mText.SetString(pText);
mText.SetColor(ToSFMLColor(pColor));
mText.SetFont(pFont);
mText.SetCharacterSize(pSize);
mBold = pBold;
mItalic = pItalic;
ChangeTextStyle();
}
void Text::SetText(const std::string &pText){
mText.SetString(pText);
}
void Text::SetColor(const Color &pColor){
mText.SetColor(ToSFMLColor(pColor));
}
void Text::SetFont(const std::string &pFont){
sf::Font font;
if(!font.LoadFromFile(pFont))
OmniLog << "Text : Font loading error, \"" << pFont << "\" does not exist, not changing anything" << eol;
else
mText.SetFont(font);
}
void Text::SetPosition(const Vector2I &pPos){
mText.SetPosition(ToSFMLVector2f(pPos));
}
void Text::SetPosition(s16 x, s16 y){
mText.SetPosition(x,y);
}
void Text::SetSize(u16 pSize){
mText.SetCharacterSize(pSize);
}
void Text::SetBold(bool pVal){
mBold = pVal;
ChangeTextStyle();
}
void Text::SetItalic(bool pVal){
mItalic = pVal;
ChangeTextStyle();
}
void Text::ChangeTextStyle(){
static u8 style;
style = 0;
style += mBold ? 1 : 0;
style += mItalic ? 2 : 0;
mText.SetStyle(style);
}
void Text::Draw(){
Renderer::Call().DrawText(this);
}
}
| C++ |
#ifndef VBO_HPP
#define VBO_HPP
#include "Utils/Shared.hpp"
#include "Math/Vector3.hpp"
#include "Math/Vector2.hpp"
namespace engine{
class Color;
/// \brief Differents types of Buffer
enum eBufferType{
BT_VERTEX,
BT_INDEX,
BT_NORMALS
};
/// \brief Usage Flag for VBO creation
enum eBufferUsage{
BU_Static,
BU_Stream,
BU_Dynamic
};
/// \brief Return GL Usage Flag from eBufferUsage
GLenum GetUsage(eBufferUsage);
/// \brief OLD. Erase?
struct Vertex{
Vector3F position;
Vector3F color;
Vector2F texcoord;
};
/// \brief Just for usage
typedef u32 Index;
/// \brief Wrapper class for OpenGL VBO
class OOXAPI VBO{
public:
VBO();
~VBO();
/// \brief Generate Buffer from Indices (u32)
/// \param pIndices : Index array to place in the buffer
/// \param pSize : Size of this array
/// \param pUsage : Usage Flag for vbo creation
void Generate(const Index* pIndices, u32 pSize, eBufferUsage pUsage = BU_Static);
/// \brief Generate Buffer from 3D Float Vector
/// \param pVector : Vector array to place in the buffer
/// \param pSize : Size of this array
/// \param pUsage : Usage Flag for vbo creation
void Generate(const Vector3F* pVector, u32 pSize, eBufferUsage pUsage = BU_Static);
/// \brief Generate Buffer from 2D Float Vector
/// \param pVector : Vector array to place in the buffer
/// \param pSize : Size of this array
/// \param pUsage : Usage Flag for vbo creation
void Generate(const Vector2F* pVector, u32 pSize, eBufferUsage pUsage = BU_Static);
/// \brief Update an already dynamically created 3D Float Vector VBO with new Data
/// \param pVector : Vector array to place in the buffer
/// \param pSize : Size of this array
void Update(const Vector3F* pVector, u32 pSize);
/// \brief Update an already dynamically created 2D Float Vector VBO with new Data
/// \param pVector : Vector array to place in the buffer
/// \param pSize : Size of this array
void Update(const Vector2F* pVector, u32 pSize);
/// \brief Update an already dynamically created Index VBO with new Data
/// \param pVector : Index array to place in the buffer
/// \param pSize : Size of this array
void Update(const Index* pVector, u32 pSize);
/// \brief Destroy the VBO in OpenGL Memory
void Destroy();
/// \brief Returns the OGL Buffer
GLuint GetBuffer() { return mVbo; }
private:
GLuint mVbo; /// Buffer ID
eBufferType mType; /// Buffer Type
eBufferUsage mUsage; /// Usage Flag
};
}
#endif
| C++ |
#include "VAO.hpp"
#include "Shader.hpp"
#include "Utils/Color.hpp"
#include "Utils/String.hpp"
#include "Debug/Exceptions.hpp"
namespace engine {
VAO::VAO() : mVao(0), mVCount(0), mICount(0), mHasIndices(false){
}
VAO::~VAO(){
if(mIbo.GetBuffer())
mIbo.Destroy();
if(mVbo.GetBuffer())
mVbo.Destroy();
if(mVao)
Destroy();
}
void VAO::CopyVAO(const VAOPtr& pVao){
mHasIndices = pVao->HasIndices();
mVao = pVao->GetVAO();
mVbo = pVao->GetVertices();
mIbo = pVao->GetIndices();
mICount = pVao->GetIndexCount();
mVCount = pVao->GetVertexCount();
}
void VAO::Destroy(){
glDeleteVertexArrays(1, &mVao);
}
void VAO::Bind() const{
glBindVertexArray(mVao);
}
void VAO::UnBind() const{
glBindVertexArray(0);
}
void VAO::Generate(Shader* pShader, const Vector3F* pVertices, u32 pVerticeSize, const Index* pIndices, u32 pIndiceSize, eBufferUsage bu){
// On s'assure que le tableau est remplit
//Assert(pVertices != NULL);
// On regarde s'il existe deja un VAO ici
if(mVao)
Destroy();
// On génère le VAO
glGenVertexArrays(1, &mVao);
// On génère le VBO
mVbo.Generate(pVertices, pVerticeSize, bu);
mVCount = pVerticeSize / sizeof(Vector3F);
// On fait de même avec l'IBO s'il existe
// if(pIndices){
mIbo.Generate(pIndices, pIndiceSize, bu);
mICount = pIndiceSize / sizeof(Index);
mHasIndices = true;
// }
// On bascule notre VAO comme VAO courant
glBindVertexArray(mVao);
// De meme avec le VertexBuffer
glBindBuffer(GL_ARRAY_BUFFER, mVbo.GetBuffer());
// On met le tableau de vertices dans le VAO
GLint loc = glGetAttribLocation(pShader->GetProgram(), "inVertex");
glVertexAttribPointer(loc, 3, GL_FLOAT, GL_FALSE, 0, 0);
#ifdef _DEBUG
GLenum error = GL_NO_ERROR;
if((error = glGetError()) != GL_NO_ERROR){
throw Exception(String("OpenGL Error: \"")+GetGLErrorStr(error)+"\" in function \"VAO::Generate\"\n\tDoes \"inVertex\" exists or is used?");
}
#endif
glEnableVertexAttribArray(loc);
// Si on a des indices, on active notre IBO
if(mHasIndices)
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mIbo.GetBuffer());
// On dé-lie notre VAO
glBindVertexArray(0);
}
void VAO::Update(const Vector3F* pVertices, u32 pVerticeSize, const Index* pIndices, u32 pIndiceSize){
mVCount = pVerticeSize / sizeof(Vector3F);
mICount = pIndiceSize / sizeof(Index);
mVbo.Update(pVertices, pVerticeSize);
mIbo.Update(pIndices, pIndiceSize);
}
// ################################################################### //
// COLORMESH
void ColorMesh::GenerateNormals(const Vector3F* pNormals, u32 pSize, Shader* shader, eBufferUsage bu){
glBindVertexArray(mVao);
mNormals.Generate(pNormals, pSize, bu);
glBindBuffer(GL_ARRAY_BUFFER, mNormals.GetBuffer());
GLint loc = glGetAttribLocation(shader->GetProgram(), "inNormal");
glVertexAttribPointer(loc, 3, GL_FLOAT, GL_FALSE, 0, 0);
#ifdef _DEBUG
GLenum error = GL_NO_ERROR;
if((error = glGetError()) != GL_NO_ERROR){
throw Exception(String("OpenGL Error: \"")+GetGLErrorStr(error)+"\" in function \"ColorMesh::GenerateNormals\"\n\tDoes \"inNormal\" exists or is used?");
}
#endif
glEnableVertexAttribArray(loc);
glBindVertexArray(0);
}
void ColorMesh::UpdateNormals(const Vector3F* pNormals, u32 pSize){
mNormals.Update(pNormals, pSize);
}
// ################################################################### //
// COLORVAO
void ColorVAO::GenerateTexCoords(const Vector2F* pTexCoords, u32 pSize, Shader* shader, eBufferUsage bu){
glBindVertexArray(mVao);
mTexCoords.Generate(pTexCoords, pSize, bu);
glBindBuffer(GL_ARRAY_BUFFER, mTexCoords.GetBuffer());
GLint loc = glGetAttribLocation(shader->GetProgram(), "inTexcoord");
glVertexAttribPointer(loc, 2, GL_FLOAT, GL_FALSE, 0, 0);
#ifdef _DEBUG
GLenum error = GL_NO_ERROR;
if((error = glGetError()) != GL_NO_ERROR){
throw Exception(String("OpenGL Error: \"")+GetGLErrorStr(error)+"\" in function \"ColorVAO::GenerateNormals\"\n\tDoes \"inTexcoord\" exists or is used?");
}
#endif
glEnableVertexAttribArray(loc);
glBindVertexArray(0);
}
void ColorVAO::UpdateTexCoords(const Vector2F* pTexCoords, u32 pSize){
mTexCoords.Update(pTexCoords, pSize);
}
// ################################################################### //
// TEXMESH
void TextureMesh::GenerateTexCoords(const Vector2F* pTexCoords, u32 pSize, Shader* shader, eBufferUsage bu){
glBindVertexArray(mVao);
mTexCoords.Generate(pTexCoords, pSize, bu);
glBindBuffer(GL_ARRAY_BUFFER, mTexCoords.GetBuffer());
GLint loc = glGetAttribLocation(shader->GetProgram(), "inTexcoord");
glVertexAttribPointer(loc, 2, GL_FLOAT, GL_FALSE, 0, 0);
#ifdef _DEBUG
GLenum error = GL_NO_ERROR;
if((error = glGetError()) != GL_NO_ERROR){
throw Exception(String("OpenGL Error: \"")+GetGLErrorStr(error)+"\" in function \"TexMesh::GenerateNormals\"\n\tDoes \"inTexcoord\" exists or is used?");
}
#endif
glEnableVertexAttribArray(loc);
glBindVertexArray(0);
}
void TextureMesh::UpdateTexCoords(const Vector2F* pTexCoords, u32 pSize){
mTexCoords.Update(pTexCoords, pSize);
}
void TextureMesh::GenerateNormals(const Vector3F* pNormals, u32 pSize, Shader* shader, eBufferUsage bu){
glBindVertexArray(mVao);
mNormals.Generate(pNormals, pSize, bu);
glBindBuffer(GL_ARRAY_BUFFER, mNormals.GetBuffer());
GLint loc = glGetAttribLocation(shader->GetProgram(), "inNormal");
glVertexAttribPointer(loc, 3, GL_FLOAT, GL_FALSE, 0, 0);
#ifdef _DEBUG
GLenum error = GL_NO_ERROR;
if((error = glGetError()) != GL_NO_ERROR){
throw Exception(String("OpenGL Error: \"")+GetGLErrorStr(error)+"\" in function \"TexMesh::GenerateNormals\"\n\tDoes \"inNormal\" exists or is used?");
}
#endif
glEnableVertexAttribArray(loc);
glBindVertexArray(0);
}
void TextureMesh::UpdateNormals(const Vector3F* pNormals, u32 pSize){
mNormals.Update(pNormals, pSize);
}
}
| C++ |
#include "Renderer.hpp"
#include "Shader.hpp"
#include "Texture.hpp"
#include "Core/Camera.hpp"
#include "Core/Entity.hpp"
#include "Core/Window.hpp"
#include "Core/Settings.hpp"
#include "Utils/Color.hpp"
#include "Utils/String.hpp"
#include "Debug/Debug.hpp"
namespace engine{
Renderer::Renderer() : mEntityNumber(0), mLastFrameEntityNumber(0), mWindow(0), mCamera(0){
}
Renderer::~Renderer(){
}
void Renderer::Init(Window &pWindow){
mWindow = &pWindow;
mWindowWidth = mWindow->GetWidth();
mWindowHeight = mWindow->GetHeight();
// Initialisation de GLEW sous Windows
#ifdef OOXWIN32
glewExperimental = GL_TRUE;
glewInit();
if(!glewIsSupported("GL_VERSION_3_3"))
throw Exception("GLEW : OpenGL Version 3.3 is not supported");
#endif
// Wireframe
mSpecs.mWireframe = false;
mSpecs.mWireframeChange = false;
// Ambient Color
mSpecs.mAmbientColor = Settings::Call().GetSettingColor("AmbientColor");
// FOV
mSpecs.mFOV = Settings::Call().GetSettingFloat("FOV");
// Near et Far plane
mSpecs.mNearPlane = Settings::Call().GetSettingFloat("NearPlane");
mSpecs.mFarPlane = Settings::Call().GetSettingFloat("FarPlane");
m3DProjectionMatrix.PerspectiveFOV(mSpecs.mFOV, (f32)mWindowWidth / (f32)mWindowHeight, mSpecs.mNearPlane, mSpecs.mFarPlane);
m2DProjectionMatrix.OrthoOffCenter(0,0,(f32)mWindowWidth,(f32)mWindowHeight);
// VSync
mSpecs.mVsync = Settings::Call().GetSettingBool("VSync");
mWindow->GetWindow().SetFramerateLimit(mSpecs.mVsync ? 60 : 0);
// Activation du Z-Depth
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LESS);
// Activation du BackFace Culling
mSpecs.mCullingFace= (Settings::Call().GetSettingStr("CullFace") == "CCW" ? GL_CCW : GL_CW);
glFrontFace(mSpecs.mCullingFace);
glEnable(GL_CULL_FACE);
// Niveau d'anisotropy maximum
f32 maxAniso;
glGetFloatv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &maxAniso);
mSpecs.mMaximumAnisotropy = (u32)maxAniso;
// Niveau d'anisotropy demandé
mSpecs.mWantedAnisotropy = Settings::Call().GetSettingInt("Anisotropy");
if(mSpecs.mWantedAnisotropy > mSpecs.mMaximumAnisotropy){
OmniLog << "Wanted Anisotropic Filtering Level is too high (" << mSpecs.mWantedAnisotropy << ")." << eol;
mSpecs.mWantedAnisotropy = mSpecs.mMaximumAnisotropy;
}
// Entity Number drawn text
mEntityNumberText.SetText(String("Entities : ")+mEntityNumber);
mEntityNumberText.SetPosition(10,34);
mEntityNumberText.SetColor(Color::White);
mEntityNumberText.SetSize(12);
}
void Renderer::SetFOV(f32 pFov){
if(pFov >= 44.f){
mSpecs.mFOV = pFov;
m3DProjectionMatrix.PerspectiveFOV(mSpecs.mFOV, (f32)mWindowWidth / (f32)mWindowHeight, mSpecs.mNearPlane, mSpecs.mFarPlane);
m3DViewProjMatrix = m3DViewMatrix * m3DProjectionMatrix;
}
}
void Renderer::WireframeMode(bool pVal){
mSpecs.mWireframe = pVal;
mSpecs.mWireframeChange = true;
}
void Renderer::Resize(){
mWindowWidth = mWindow->GetWidth();
mWindowHeight = mWindow->GetHeight();
m2DProjectionMatrix.OrthoOffCenter(0, 0, (f32)mWindowWidth, (f32)mWindowHeight);
m3DProjectionMatrix.PerspectiveFOV(mSpecs.mFOV, (f32)mWindowWidth / (f32)mWindowHeight, mSpecs.mNearPlane, mSpecs.mFarPlane);
m3DViewProjMatrix = m3DViewMatrix * m3DProjectionMatrix;
}
void Renderer::BeginScene(const Color &pColor) const{
glClearColor(pColor.R(), pColor.G(), pColor.B(), pColor.A());
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
}
void Renderer::EndScene(){
mWindow->GetWindow().Display();
}
void Renderer::DrawText(Text* pText){
mTextMap.push_back(pText);
}
void Renderer::DrawMesh(Mesh* pEntity){
mMeshMap.push_back(pEntity);
}
void Renderer::DrawObject(Object* pEntity){
mObjectMap.push_back(pEntity);
}
void Renderer::DrawDebugObject(DebugObject* pEntity){
mDebugObjectMap.push_back(pEntity);
}
void Renderer::Render(){
mEntityNumber = 0;
if(mSpecs.mWireframeChange){
mSpecs.mWireframeChange = false;
if(mSpecs.mWireframe)
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
else
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
}
if(!mMeshMap.empty())
RenderMeshes();
if(!mObjectMap.empty())
RenderObjects();
if(!mDebugObjectMap.empty())
RenderDebugObjects();
RenderTexts();
}
void Renderer::RenderTexts(){
// Disable GL Depth and Culling for 2D text drawing
glDisable(GL_DEPTH_TEST);
glDisable(GL_CULL_FACE);
for(mTextMapIt = mTextMap.begin(); mTextMapIt != mTextMap.end(); ++mTextMapIt){
mWindow->GetWindow().Draw((*mTextMapIt)->GetSFMLText());
}
// Draw the entity number on screen if debug active
#ifdef _DEBUG
if(mEntityNumber != mLastFrameEntityNumber){
mEntityNumberText.SetText(String("Entities : ")+mEntityNumber);
mLastFrameEntityNumber = mEntityNumber;
}
mWindow->GetWindow().Draw(mEntityNumberText.GetSFMLText());
#endif
glEnable(GL_CULL_FACE);
glEnable(GL_DEPTH_TEST);
mTextMap.clear();
}
void Renderer::RenderMeshes(){
static Shader* currentShader;
static Mesh* currentMesh;
currentShader = 0;
currentMesh = 0;
// Using Textures
glActiveTexture(GL_TEXTURE0);
for(mMeshMapIt = mMeshMap.begin(); mMeshMapIt != mMeshMap.end(); ++mMeshMapIt){
// Get the current mesh
currentMesh = (*mMeshMapIt);
// If the mesh possess a different shader, change it
if(currentMesh->GetShader() != currentShader){
currentShader = currentMesh->GetShader();
currentShader->Bind();
}
// Send the Mesh Matrices to the Shader
currentShader->SendMatrix4("ModelViewProjMatrix", currentMesh->GetModelMatrix() * m3DViewProjMatrix );
currentShader->SendMatrix4("ModelViewMatrix", currentMesh->GetModelMatrix() * m3DViewMatrix);
currentShader->SendMatrix4("ViewMatrix", m3DViewMatrix);
currentShader->SendMatrix4("NormalMatrix", m3DNormalMatrix);
// Send the Mesh Material to the Shader
currentShader->SendColor("Ka", currentMesh->GetMaterial().mAmbient);
currentShader->SendColor("Kd", currentMesh->GetMaterial().mDiffuse);
currentShader->SendColor("Ks", currentMesh->GetMaterial().mSpecular);
currentShader->SendFloat("shininess", currentMesh->GetMaterial().mShininess);
// Bind texture
currentMesh->GetTexture().Bind();
// Draw the mesh
currentMesh->GetMesh()->Bind();
glDrawElements(GL_TRIANGLES, currentMesh->GetMesh()->GetIndexCount(), GL_UNSIGNED_INT, 0);
currentMesh->GetMesh()->UnBind();
// Unbind texture
currentMesh->GetTexture().UnBind();
}
currentShader->UnBind();
// Add Mesh number to total
mEntityNumber += mMeshMap.size();
// Clear the vector for next frame
mMeshMap.clear();
}
void Renderer::RenderObjects(){
static Shader* currentShader;
static Object* currentObject;
currentShader = 0;
currentObject = 0;
for(mObjectMapIt = mObjectMap.begin(); mObjectMapIt != mObjectMap.end(); ++mObjectMapIt){
// Get the current Object
currentObject = (*mObjectMapIt);
// If the object possess a different shader, change it
if(currentObject->GetShader() != currentShader){
currentShader = currentObject->GetShader();
currentShader->Bind();
}
// Send the Object Matrices to the Shader
currentShader->SendMatrix4("ModelViewProjMatrix", currentObject->GetModelMatrix() * m3DViewProjMatrix );
currentShader->SendMatrix4("ModelViewMatrix", currentObject->GetModelMatrix() * m3DViewMatrix);
currentShader->SendMatrix4("ViewMatrix", m3DViewMatrix);
currentShader->SendMatrix4("NormalMatrix", m3DNormalMatrix);
// Send the Object Material to the Shader
currentShader->SendColor("Ka", currentObject->GetMaterial().mAmbient);
currentShader->SendColor("Kd", currentObject->GetMaterial().mDiffuse);
currentShader->SendColor("Ks", currentObject->GetMaterial().mSpecular);
currentShader->SendFloat("shininess", currentObject->GetMaterial().mShininess);
// Draw the Object
currentObject->GetMesh()->Bind();
glDrawElements(GL_TRIANGLES, currentObject->GetMesh()->GetIndexCount(), GL_UNSIGNED_INT, 0);
currentObject->GetMesh()->UnBind();
}
currentShader->UnBind();
// Add Object number to total
mEntityNumber += mObjectMap.size();
// Clear the vector for next frame
mObjectMap.clear();
}
void Renderer::RenderDebugObjects(){
static Shader* currentShader;
static DebugObject* currentObject;
currentShader = 0;
currentObject = 0;
// Using Texture
glActiveTexture(GL_TEXTURE0);
for(mDebugObjectMapIt = mDebugObjectMap.begin(); mDebugObjectMapIt != mDebugObjectMap.end(); ++mDebugObjectMapIt){
// Get the current Object
currentObject = (*mDebugObjectMapIt);
// If the object possess a different shader, change it
if(currentObject->GetShader() != currentShader){
currentShader = currentObject->GetShader();
currentShader->Bind();
}
// Send the Object matrices to the shader
currentShader->SendMatrix4("ModelViewProjMatrix", currentObject->GetModelMatrix() * m3DViewProjMatrix );
currentShader->SendMatrix4("ModelViewMatrix", currentObject->GetModelMatrix() * m3DViewMatrix);
currentShader->SendMatrix4("ViewMatrix", m3DViewMatrix);
currentShader->SendMatrix4("NormalMatrix", m3DNormalMatrix);
// Send the Object material to the shader
currentShader->SendColor("Ka", currentObject->GetMaterial().mAmbient);
currentShader->SendColor("Kd", currentObject->GetMaterial().mDiffuse);
currentShader->SendColor("Ks", currentObject->GetMaterial().mSpecular);
currentShader->SendFloat("shininess", currentObject->GetMaterial().mShininess);
// Bind Texture
currentObject->GetTexture().Bind();
// Draw the Object
currentObject->GetMesh()->Bind();
glDrawElements(GL_TRIANGLES, currentObject->GetMesh()->GetIndexCount(), GL_UNSIGNED_INT, 0);
currentObject->GetMesh()->UnBind();
// Unbind texture
currentObject->GetTexture().UnBind();
}
currentShader->UnBind();
// Add DebugObject number to total
mEntityNumber += mDebugObjectMap.size();
// Clear the vector for next frame
mDebugObjectMap.clear();
}
}
| C++ |
#include "Texture.hpp"
#include "Renderer.hpp"
#include "Debug/Debug.hpp"
namespace engine {
Texture::Texture() : mTexture(0){
}
Texture::~Texture(){
Destroy();
}
void Texture::Destroy(){
if(mTexture)
glDeleteTextures(1, &mTexture);
}
void Texture::LoadFromImage(const Image &pImage, const Rectangle &pSubRect){
// Generation de Binding de la texture a OGL
glGenTextures(1, &mTexture);
glBindTexture(GL_TEXTURE_2D, mTexture);
// Utilisation de linear interpolation pour les min/mag filters
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, (f32)Renderer::Call().GetSpecifications().mWantedAnisotropy);
// creation depuis l'image
// Reconnaissance du rectangle envoye et creation de la texture OGL
if(pSubRect.Width() == 0 && pSubRect.Height() == 0)
glTexImage2D(GL_TEXTURE_2D, 0, pImage.GetBytesPerPixel(), pImage.GetSize().x, pImage.GetSize().y, 0, pImage.GetFormat(), GL_UNSIGNED_BYTE, pImage.GetData());
else
glTexSubImage2D(GL_TEXTURE_2D, 0, pSubRect.Origin.x, pSubRect.Origin.y, pSubRect.Width(), pSubRect.Height(), pImage.GetFormat(), GL_UNSIGNED_BYTE, pImage.GetData());
// glHint(GL_GENERATE_MIPMAP_HINT, GL_NICEST);
glGenerateMipmap(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, 0);
#ifdef _DEBUG
BaseLog << "DEBUG : Texture created from image \"" << pImage.GetName() << "\"."/* RAJOUTER LE RECTANGLE UTILISED*/ << eol;
#endif
}
void Texture::Bind() const{
glBindTexture(GL_TEXTURE_2D, mTexture);
}
void Texture::UnBind() const{
glBindTexture(GL_TEXTURE_2D, 0);
}
}
| C++ |
#include "Light.hpp"
namespace engine{
void Update(){
}
} | C++ |
#ifndef RECTANGLE_HPP
#define RECTANGLE_HPP
#include "Vector2.hpp"
namespace engine {
// Three possible results of an Intersection
enum IntersectionResult{
INTR_In,
INTR_Out,
INTR_Intersect
};
class OOXAPI Rectangle{
public:
// Ctor from 4 boundaries
Rectangle(s32 top, s32 left, s32 width, s32 height);
// Ctor from Top-Left and Bottom-Right Vectors
Rectangle(const Vector2I &topLeft = Vector2I(0,0), const Vector2I &size = Vector2I(0,0));
// Initialize the rectangle from 4 boundaries
void Set(s32 top, s32 left, s32 width, s32 height);
// Getters
s32 Left() const;
s32 Top() const;
s32 Right() const;
s32 Bottom() const;
s32 Width() const;
s32 Height() const;
// Returns the rectangle size (End - Origin)
Vector2I Size() const;
// Returns the intersection type between a point and this rectangle
IntersectionResult Intersects(const Vector2I &Point) const;
// Returns the intersection type between another and this rectangle
IntersectionResult Intersects(const Rectangle &Rect) const;
bool operator==(const Rectangle &Rect) const;
bool operator!=(const Rectangle &Rect) const;
friend std::istream& operator>> (std::istream &iss, Rectangle &Rect);
friend std::ostream& operator<< (std::ostream &oss, const Rectangle &Rect);
// Data
Vector2I Origin;
Vector2I End;
};
}
#endif
| C++ |
#include "Matrix4.hpp"
#include "Quaternion.hpp"
namespace engine {
}
| C++ |
#ifndef VECTOR2_HPP
#define VECTOR2_HPP
#include "Mathlib.hpp"
namespace engine {
template<typename T>
class Vector2{
public:
Vector2(T x = 0, T y = 0);
// Sets vector components
void Set(T x, T y);
// Returns the vector components in an array
void XY(T pTab[]) const;
// Returns the vector length
T Norme() const;
// Returns the Squared Length (intern use for Norme())
T NormeSq() const;
// Normalize the vector
void Normalize();
// Returns the negate of the vector
Vector2<T> operator- () const;
// Binary operators
Vector2<T> operator+ (const Vector2<T> &V) const;
Vector2<T> operator- (const Vector2<T> &V) const;
Vector2<T>& operator+= (const Vector2<T> &V) const;
Vector2<T>& operator -= (const Vector2<T> &V) const;
Vector2<T> operator*(T t) const;
Vector2<T> operator/(T t) const;
Vector2<T>& operator*= (T t) const;
Vector2<T>& operator /= (T t) const;
// Comparison operators
bool operator==(const Vector2<T> &V) const;
bool operator!=(const Vector2<T> &V) const;
// Returns a pointer on x
operator T*();
// Common Zero Vector
static const OOXAPI Vector2 ZERO;
// Donnees
T x;
T y;
};
// Result of multiplication between a vector and a T
template<class T> Vector2<T> operator* (const Vector2<T> &V, T t);
// Result of division between a vector and a T
template<class T> Vector2<T> operator/ (const Vector2<T> &V, T t);
// Result of multiplication between a T and a vector
template<class T> Vector2<T> operator* (T t, const Vector2<T> &V);
// Dot product between two vector2
template<class T> T Dot(const Vector2<T> &U, const Vector2<T> &V);
// Stream ops
template<class T> std::istream& operator >>(std::istream& iss, Vector2<T> &V);
template<class T> std::ostream& operator <<(std::ostream& oss, const Vector2<T> &V);
typedef Vector2<s32> Vector2I;
typedef Vector2<f32> Vector2F;
// Conversion between SFML and 00xEngine
template<class T> Vector2F To00xVector2F(const sf::Vector2<T> &pVec);
template<class T> Vector2I To00xVector2I(const sf::Vector2<T> &pVec);
template<class T> sf::Vector2f ToSFMLVector2f(const Vector2<T> &pVec);
template<class T> sf::Vector2i ToSFMLVector2i(const Vector2<T> &pVec);
#include "Vector2.inl"
}
#endif
| C++ |
template<class T>
inline engine::Vector2<T>::Vector2(T X, T Y) : x(X), y(Y){
}
template<class T>
inline void engine::Vector2<T>::Set(T X, T Y){
x = X;
y = Y;
}
template<class T>
inline void engine::Vector2<T>::XY(T pTab[]) const{
pTab[0] = x;
pTab[1] = y;
}
template<class T>
inline T engine::Vector2<T>::Norme() const{
return Math::Sqrt(NormeSq());
}
template<class T>
inline T engine::Vector2<T>::NormeSq() const{
return x * x + y * y;
}
template<class T>
inline void engine::Vector2<T>::Normalize(){
T Norme = Norme();
if(Math::Abs(Norme) > Math::Epsilon){
x /= Norme;
y /= Norme;
}
}
template<class T>
inline Vector2<T> engine::Vector2<T>::operator-() const{
return Vector2<T>(-x, -y);
}
template<class T>
inline Vector2<T> engine::Vector2<T>::operator+(const Vector2<T> &V) const{
return Vector2<T>(x + V.x, y + V.y);
}
template<class T>
inline Vector2<T> engine::Vector2<T>::operator-(const Vector2<T> &V) const{
return Vector2<T>(x - V.x, y - V.y);
}
template<class T>
inline Vector2<T>& engine::Vector2<T>::operator+=(const Vector2<T> &V) const{
x += V.x;
y += V.y;
return *this;
}
template<class T>
inline Vector2<T>& engine::Vector2<T>::operator-=(const Vector2<T> &V) const{
x -= V.x;
y -= V.y;
return *this;
}
template<class T>
inline Vector2<T> engine::Vector2<T>::operator*(T t) const{
return Vector2<T>(x*t, y*t);
}
template<class T>
inline Vector2<T> engine::Vector2<T>::operator/(T t) const{
return Vector2<T>(x/t, y/t);
}
template<class T>
inline Vector2<T>& engine::Vector2<T>::operator*=(T t) const{
x *= t;
y *= t;
return *this;
}
template<class T>
inline Vector2<T>& engine::Vector2<T>::operator/=(T t) const{
x /= t;
y /= t;
return *this;
}
template<class T>
inline bool engine::Vector2<T>::operator==(const Vector2<T> &V) const{
return ( (Math::Abs(float(x - V.x)) <= Math::Epsilon) &&
(Math::Abs(float(y - V.y)) <= Math::Epsilon) );
}
template<class T>
inline bool engine::Vector2<T>::operator!=(const Vector2<T> &V) const{
return !(*this == V);
}
template<class T>
inline engine::Vector2<T>::operator T*(){
return &x;
}
template<class T>
Vector2<T> operator* (const Vector2<T> &V, T t){
return Vector2<T>(V.x * t, V.y * t);
}
template<class T>
Vector2<T> operator/ (const Vector2<T> &V, T t){
return Vector2<T>(V.x / t, V.y / t);
}
template<class T>
Vector2<T> operator* (T t, const Vector2<T> &V){
return V * t;
}
template<class T>
T Dot(const Vector2<T> &U, const Vector2<T> &V){
return U.x * V.x + U.y * V.y;
}
template<class T>
std::istream& operator >>(std::istream& iss, Vector2<T> &V){
return iss >> V.x >> V.y;
}
template<class T>
std::ostream& operator <<(std::ostream& oss, const Vector2<T> &V){
return oss << V.x << " " << V.y;
}
template<class T>
Vector2F To00xVector2F(const sf::Vector2<T> &pVec){
return Vector2F(static_cast<f32>(pVec.x), static_cast<f32>(pVec.y));
}
template<class T>
Vector2I To00xVector2I(const sf::Vector2<T> &pVec){
return Vector2I(static_cast<s32>(pVec.x), static_cast<s32>(pVec.y));
}
template<class T>
sf::Vector2f ToSFMLVector2f(const Vector2<T> &pVec){
return sf::Vector2f(static_cast<f32>(pVec.x), static_cast<f32>(pVec.y));
}
template<class T>
sf::Vector2i ToSFMLVector2i(const Vector2<T> &pVec){
return sf::Vector2f(static_cast<s32>(pVec.x), static_cast<s32>(pVec.y));
}
| C++ |
template<class T>
inline engine::Vector3<T>::Vector3(T X, T Y, T Z) : x(X), y(Y), z(Z){
}
template<class T>
inline void engine::Vector3<T>::Set(T X, T Y, T Z){
x = X;
y = Y;
z = Z;
}
template<class T>
inline void engine::Vector3<T>::XYZ(T pTab[]) const{
pTab[0] = x;
pTab[1] = y;
pTab[2] = z;
}
template<class T>
inline T engine::Vector3<T>::Norme() const{
return Math::Sqrt(NormeSq());
}
template<class T>
inline T engine::Vector3<T>::NormeSq() const{
return x * x + y * y + z * z;
}
template<class T>
inline void engine::Vector3<T>::Normalize(){
T norme = Norme();
// on s'assure que norme != 0
if(Math::Abs(norme) > Math::Epsilon){ // Eviter le == non precis des floating points
x /= norme;
y /= norme;
z /= norme;
}
}
template<class T>
inline void engine::Vector3<T>::ScaleFrom(const Vector3<T> &pCenter, f32 pScaleFactor){
Vector3<T> axis = (*this) - pCenter;
(*this) += axis * pScaleFactor;
}
template<class T>
inline Vector3<T> engine::Vector3<T>::operator-() const{
return Vector3<T>(-x, -y, -z);
}
template<class T>
inline Vector3<T> engine::Vector3<T>::operator+(const Vector3<T> &V) const{
return Vector3<T>(x + V.x, y + V.y, z + V.z);
}
template<class T>
inline Vector3<T> engine::Vector3<T>::operator-(const Vector3<T> &V) const{
return Vector3<T>(x - V.x, y - V.y, z - V.z);
}
template<class T>
inline Vector3<T>& engine::Vector3<T>::operator+=(const Vector3<T> &V) {
x += V.x;
y += V.y;
z += V.z;
return *this;
}
template<class T>
inline Vector3<T>& engine::Vector3<T>::operator-=(const Vector3<T> &V) {
x -= V.x;
y -= V.y;
z -= V.z;
return *this;
}
template<class T>
inline Vector3<T> engine::Vector3<T>::operator*(T t) const{
return Vector3<T>(x * t, y * t, z * t);
}
template<class T>
inline Vector3<T> engine::Vector3<T>::operator/(T t) const{
return Vector3<T>(x/t, y/t, z/t);
}
template<class T>
inline Vector3<T>& engine::Vector3<T>::operator*=(T t){
x *= t;
y *= t;
z *= t;
return *this;
}
template<class T>
inline Vector3<T>& engine::Vector3<T>::operator/=(T t){
x /= t;
y /= t;
z /= t;
return *this;
}
template<class T>
inline bool engine::Vector3<T>::operator==(const Vector3<T> &V) const{
return ( (Math::Abs(x - V.x) <= Math::Epsilon) &&
(Math::Abs(y - V.y) <= Math::Epsilon) &&
(Math::Abs(z - V.z) <= Math::Epsilon) );
}
template<class T>
inline bool engine::Vector3<T>::operator!=(const Vector3<T> &V) const{
return !(*this == V);
}
template<class T>
inline engine::Vector3<T>::operator T*(){
return &x;
}
template<class T>
Vector3<T> operator* (const Vector3<T> &V, T t){
return Vector3<T>(V.x * t, V.y * t, V.z * t);
}
template<class T>
Vector3<T> operator/ (const Vector3<T> &V, T t){
return Vector3<T>(V.x / t, V.y / t, V.z / t);
}
template<class T>
Vector3<T> operator* (T t, const Vector3<T> &V){
return V * t;
}
template<class T>
T Dot(const Vector3<T> &U, const Vector3<T> &V){
return U.x * V.x + U.y * V.y + U.z * V.z;
}
template<class T>
Vector3<T> Cross(const Vector3<T> &U, const Vector3<T> &V){
return Vector3<T>( (U.y * V.z) - (V.y * U.z), (U.z * V.x) - (V.z * U.x), (U.x * V.y) - (V.x * U.y) );
}
template<class T>
std::istream& operator >>(std::istream& iss, Vector3<T> &V){
return iss >> V.x >> V.y >> V.z;
}
template<class T>
std::ostream& operator <<(std::ostream& oss, const Vector3<T> &V){
return oss << V.x << " " << V.y << " " << V.z;
}
| C++ |
inline engine::Matrix4::Matrix4(f32 m11, f32 m12, f32 m13, f32 m14,
f32 m21, f32 m22, f32 m23, f32 m24,
f32 m31, f32 m32, f32 m33, f32 m34,
f32 m41, f32 m42, f32 m43, f32 m44) :
a11(m11), a12(m12), a13(m13), a14(m14),
a21(m21), a22(m22), a23(m23), a24(m24),
a31(m31), a32(m32), a33(m33), a34(m34),
a41(m41), a42(m42), a43(m43), a44(m44) {
};
inline void engine::Matrix4::Identity(){
a11 = 1.0f; a12 = 0.0f; a13 = 0.0f; a14 = 0.0f;
a21 = 0.0f; a22 = 1.0f; a23 = 0.0f; a24 = 0.0f;
a31 = 0.0f; a32 = 0.0f; a33 = 1.0f; a34 = 0.0f;
a41 = 0.0f; a42 = 0.0f; a43 = 0.0f; a44 = 1.0f;
}
inline void engine::Matrix4::ToFloat(f32* tab) const{
tab[0] = a11; tab[1] = a12; tab[2] = a13; tab[3] = a14;
tab[4] = a21; tab[5] = a22; tab[6] = a23; tab[7] = a24;
tab[8] = a31; tab[9] = a32; tab[10] = a33; tab[11] = a34;
tab[12] = a41; tab[13] = a42; tab[14] = a43; tab[15] = a44;
}
inline f32 engine::Matrix4::Det() const{
f32 A = a22 * (a33 * a44 - a43 * a34) - a23 * (a32 * a44 - a34 * a42) + a24 * (a32 * a43 - a33 * a42);
f32 B = a21 * (a33 * a44 - a43 * a34) - a23 * (a31 * a44 - a34 * a41) + a24* (a31 * a43 - a33 * a41);
f32 C = a21 * (a32 * a44 - a34 * a42) - a22 * (a31 * a44 - a34 * a41) + a24 * (a31 * a42 - a32 * a41);
f32 D = a21 * (a32 * a43 - a33 * a42) - a22 * (a31 * a43 - a33 * a41) + a23 * (a31 * a42 - a32 * a41);
return a11 * A - a12 * B + a13 * C - a14 * D; // LaPlace en prenant la premiere Colonne, en trouvant ses cofactors(A..D)
}
inline Matrix4 engine::Matrix4::Transpose() const{
return Matrix4(a11, a21, a31, a41,
a12, a22, a32, a42,
a13, a23, a33, a43,
a14, a24, a34, a44);
}
inline Matrix4 engine::Matrix4::Inverse() const{
f32 det = Det();
Matrix4 inverse;
if(Math::Abs(det) > Math::Epsilon){
inverse.a11 = (a22 * (a33 * a44 - a43 * a34) - a23 * (a32 * a44 - a34 * a42) + a24 * (a32 * a43 - a33 * a42)) / det;
inverse.a21 = -(a21 * (a33 * a44 - a43 * a34) - a23 * (a31 * a44 - a34 * a41) + a24* (a31 * a43 - a33 * a41)) / det;
inverse.a31 = (a21 * (a32 * a44 - a34 * a42) - a22 * (a31 * a44 - a34 * a41) + a24 * (a31 * a42 - a32 * a41)) / det;
inverse.a41 = -(a21 * (a32 * a43 - a33 * a42) - a22 * (a31 * a43 - a33 * a41) + a23 * (a31 * a42 - a32 * a41)) / det;
inverse.a12 = -(a12 * (a33 * a44 - a34 * a43) - a13 * (a32 * a44 - a34 * a42) + a14 * (a32 * a43 - a33 * a42)) / det;
inverse.a22 = (a11 * (a33 * a44 - a34 * a43) - a13 * (a31 * a44 - a34 * a41) + a14 * (a31 * a43 - a33 * a41)) / det;
inverse.a32 = -(a11 * (a32 * a44 - a34 * a42) - a12 * (a31 * a44 - a34 * a41) + a14 * (a31 * a42 - a32 * a41)) / det;
inverse.a42 = (a11 * (a32 * a43 - a33 * a42) - a12 * (a31 * a43 - a33 * a41) + a13 * (a31 * a42 - a32 * a41)) / det;
inverse.a13 = (a12 * (a23 * a44 - a24 * a43) - a13 * (a22 * a44 - a24 * a42) + a14 * (a22 * a43 - a23 * a42)) / det;
inverse.a23 = -(a11 * (a23 * a44 - a24 * a43) - a13 * (a21 * a44 - a24 * a41) + a14 * (a21 * a43 - a23 * a41)) / det;
inverse.a33 = (a11 * (a22 * a44 - a24 * a42) - a12 * (a21 * a44 - a24 * a41) + a14 * (a21 * a42 - a22 * a41)) / det;
inverse.a43 = -(a11 * (a22 * a43 - a23 * a42) - a12 * (a21 * a43 - a23 * a41) + a13 * (a21 * a42 - a22 * a41)) / det;
inverse.a14 = -(a12 * (a23 * a34 - a24 * a33) - a13 * (a22 * a34 - a24 * a32) + a14 * (a22 * a33 - a23 * a32)) / det;
inverse.a24 = (a11 * (a23 * a34 - a24 * a33) - a13 * (a21 * a34 - a24 * a31) + a14 * (a21 * a33 - a23 * a31)) / det;
inverse.a34 = -(a11 * (a22 * a34 - a24 * a32) - a12 * (a21 * a34 - a24 * a31) + a14 * (a21 * a32 - a22 * a31)) / det;
inverse.a44 = (a11 * (a22 * a33 - a23 * a32) - a12 * (a21 * a33 - a23 * a31) + a13 * (a21 * a32 - a22 * a31)) / det;
}
return inverse;
}
inline void engine::Matrix4::SetTranslation(f32 x, f32 y, f32 z){
a41 = x;
a42 = y;
a43 = z;
}
inline void engine::Matrix4::SetTranslation(const Vector3F &V){
a41 = V.x;
a42 = V.y;
a43 = V.z;
}
inline void engine::Matrix4::SetScale(f32 x, f32 y, f32 z){
a11 = x;
a22 = y;
a33 = z;
}
inline void engine::Matrix4::SetScale(const Vector3F &V){
a11 = V.x;
a22 = V.y;
a33 = V.z;
}
inline void engine::Matrix4::SetScale(f32 xyz){
SetScale(xyz, xyz, xyz);
}
inline void engine::Matrix4::SetRotationX(f32 Angle){
f32 Sin = std::sin(Angle);
f32 Cos = std::cos(Angle);
a11= 1.f;a12= 0.f; a13= 0.f;
a21= 0.f;a22= Cos; a23= -Sin;
a31= 0.f;a32= Sin; a33= Cos;
}
inline void engine::Matrix4::SetRotationY(f32 Angle){
f32 Sin =std::sin(Angle);
f32 Cos = std::cos(Angle);
a11= Cos;a12= 0.f; a13= Sin;
a21= 0.f;a22= 1.f; a23= 0.f;
a31= -Sin;a32= 0.f; a33= Cos;
}
inline void engine::Matrix4::SetRotationZ(f32 Angle){
f32 Sin = std::sin(Angle);
f32 Cos = std::cos(Angle);
a11= Cos;a12= -Sin; a13= 0.f;
a21= Sin;a22= Cos; a23= 0.f;
a31= 0.f;a32= 0.f; a33= 1.f;
}
inline void engine::Matrix4::SetRotationX(f32 Angle, const Vector3F &Axis){
Matrix4 Tr1, Tr2, Rot;
Tr1.SetTranslation(Axis.x, Axis.y, Axis.z);
Tr2.SetTranslation(-Axis.x, -Axis.y, -Axis.z);
Rot.SetRotationX(Angle);
*this = Tr1 * Rot * Tr2;
}
inline void engine::Matrix4::SetRotationY(f32 Angle, const Vector3F &Axis){
Matrix4 Tr1, Tr2, Rot;
Tr1.SetTranslation(Axis.x, Axis.y, Axis.z);
Tr2.SetTranslation(-Axis.x, -Axis.y, -Axis.z);
Rot.SetRotationY(Angle);
*this = Tr1 * Rot * Tr2;
}
inline void engine::Matrix4::SetRotationZ(f32 Angle, const Vector3F &Axis){
Matrix4 Tr1, Tr2, Rot;
Tr1.SetTranslation(Axis.x, Axis.y, Axis.z);
Tr2.SetTranslation(-Axis.x, -Axis.y, -Axis.z);
Rot.SetRotationZ(Angle);
*this = Tr1 * Rot * Tr2;
}
inline void engine::Matrix4::Translate(const Vector3F &pVector){
a41 += pVector.x;
a42 += pVector.y;
a43 += pVector.z;
}
inline void engine::Matrix4::Scale(const Vector3F &pVector){
a11 *= pVector.x;
a22 *= pVector.y;
a33 *= pVector.z;
}
inline void engine::Matrix4::Scale(f32 pFactor){
a11 *= pFactor;
a22 *= pFactor;
a33 *= pFactor;
}
inline Vector3F engine::Matrix4::GetTranslation()const{
return Vector3F(a14, a24, a34);
}
inline Vector3F engine::Matrix4::GetScale() const{
return Vector3F(Math::Sqrt(a11*a11+a12*a12+a13*a13), Math::Sqrt(a21*a21+a22*a22+a23*a23), Math::Sqrt(a31*a31+a32*a32+a33*a33));
}
inline Vector3F engine::Matrix4::Transform(const Vector3F &V, f32 w) const{
return Vector3F(a11 * V.x + a12 * V.y + a13 * V.z + a14 * w,
a21 * V.x + a22 * V.y + a23 * V.z + a24 * w,
a31 * V.x + a31 * V.y + a33 * V.z + a34 * w);
}
inline void engine::Matrix4::WorldMatrix(const Vector3F &Translation, const Vector3F &Rotation){
Matrix4 Temp;
Matrix4 Rot;
SetTranslation(Translation);
if(Rotation.x || Rotation.y ||Rotation.z){
Temp.SetRotationX(Rotation.x);
Rot *= Temp;
Temp.SetRotationY(Rotation.y);
Rot *= Temp;
Temp.SetRotationZ(Rotation.z);
Rot *= Temp;
(*this) = Rot * (*this);
}
}
inline Matrix4 engine::Matrix4::operator -() const
{
return Matrix4(-a11, -a12, -a13, -a14,
-a21, -a22, -a23, -a24,
-a31, -a32, -a33, -a34,
-a41, -a42, -a43, -a44);
}
inline Matrix4 engine::Matrix4::operator +(const Matrix4& m) const
{
return Matrix4(a11 + m.a11, a12 + m.a12, a13 + m.a13, a14 + m.a14,
a21 + m.a21, a22 + m.a22, a23 + m.a23, a24 + m.a24,
a31 + m.a31, a32 + m.a32, a33 + m.a33, a34 + m.a34,
a41 + m.a41, a42 + m.a42, a43 + m.a43, a44 + m.a44);
}
inline Matrix4 engine::Matrix4::operator -(const Matrix4& m) const
{
return Matrix4(a11 - m.a11, a12 - m.a12, a13 - m.a13, a14 - m.a14,
a21 - m.a21, a22 - m.a22, a23 - m.a23, a24 - m.a24,
a31 - m.a31, a32 - m.a32, a33 - m.a33, a34 - m.a34,
a41 - m.a41, a42 - m.a42, a43 - m.a43, a44 - m.a44);
}
inline const Matrix4& engine::Matrix4::operator +=(const Matrix4& m)
{
a11 += m.a11; a12 += m.a12; a13 += m.a13; a14 += m.a14;
a21 += m.a21; a22 += m.a22; a23 += m.a23; a24 += m.a24;
a31 += m.a31; a32 += m.a32; a33 += m.a33; a34 += m.a34;
a41 += m.a41; a42 += m.a42; a43 += m.a43; a44 += m.a44;
return *this;
}
inline const Matrix4& engine::Matrix4::operator -=(const Matrix4& m)
{
a11 -= m.a11; a12 -= m.a12; a13 -= m.a13; a14 -= m.a14;
a21 -= m.a21; a22 -= m.a22; a23 -= m.a23; a24 -= m.a24;
a31 -= m.a31; a32 -= m.a32; a33 -= m.a33; a34 -= m.a34;
a41 -= m.a41; a42 -= m.a42; a43 -= m.a43; a44 -= m.a44;
return *this;
}
inline Matrix4 engine::Matrix4::operator*(const Matrix4 &m) const{
return Matrix4(a11 * m.a11 + a12 * m.a21 + a13 * m.a31 + a14 * m.a41,
a11 * m.a12 + a12 * m.a22 + a13 * m.a32 + a14 * m.a42,
a11 * m.a13 + a12 * m.a23 + a13 * m.a33 + a14 * m.a43,
a11 * m.a14 + a12 * m.a24 + a13 * m.a34 + a14 * m.a44,
a21 * m.a11 + a22 * m.a21 + a23 * m.a31 + a24 * m.a41,
a21 * m.a12 + a22 * m.a22 + a23 * m.a32 + a24 * m.a42,
a21 * m.a13 + a22 * m.a23 + a23 * m.a33 + a24 * m.a43,
a21 * m.a14 + a22 * m.a24 + a23 * m.a34 + a24 * m.a44,
a31 * m.a11 + a32 * m.a21 + a33 * m.a31 + a34 * m.a41,
a31 * m.a12 + a32 * m.a22 + a33 * m.a32 + a34 * m.a42,
a31 * m.a13 + a32 * m.a23 + a33 * m.a33 + a34 * m.a43,
a31 * m.a14 + a32 * m.a24 + a33 * m.a34 + a34 * m.a44,
a41 * m.a11 + a42 * m.a21 + a43 * m.a31 + a44 * m.a41,
a41 * m.a12 + a42 * m.a22 + a43 * m.a32 + a44 * m.a42,
a41 * m.a13 + a42 * m.a23 + a43 * m.a33 + a44 * m.a43,
a41 * m.a14 + a42 * m.a24 + a43 * m.a34 + a44 * m.a44);
}
inline const Matrix4& engine::Matrix4::operator *=(const Matrix4& m)
{
*this = *this * m;
return *this;
}
inline const Matrix4& engine::Matrix4::operator *=(f32 t)
{
a11 *= t; a12 *= t; a13 *= t; a14 *= t;
a21 *= t; a22 *= t; a23 *= t; a24 *= t;
a31 *= t; a32 *= t; a33 *= t; a34 *= t;
a41 *= t; a42 *= t; a43 *= t; a44 *= t;
return *this;
}
inline const Matrix4& engine::Matrix4::operator /=(f32 t)
{
a11 /= t; a12 /= t; a13 /= t; a14 /= t;
a21 /= t; a22 /= t; a23 /= t; a24 /= t;
a31 /= t; a32 /= t; a33 /= t; a34 /= t;
a41 /= t; a42 /= t; a43 /= t; a44 /= t;
return *this;
}
inline bool engine::Matrix4::operator ==(const Matrix4& m) const
{
return (Math::IsEqual(a11, m.a11) && Math::IsEqual(a12, m.a12) &&
Math::IsEqual(a13, m.a13) && Math::IsEqual(a14, m.a14) &&
Math::IsEqual(a21, m.a21) && Math::IsEqual(a22, m.a22) &&
Math::IsEqual(a23, m.a23) && Math::IsEqual(a24, m.a24) &&
Math::IsEqual(a31, m.a31) && Math::IsEqual(a32, m.a32) &&
Math::IsEqual(a33, m.a33) && Math::IsEqual(a34, m.a34) &&
Math::IsEqual(a41, m.a41) && Math::IsEqual(a42, m.a42) &&
Math::IsEqual(a43, m.a43) && Math::IsEqual(a44, m.a44));
}
inline bool engine::Matrix4::operator !=(const Matrix4& m) const
{
return !(*this == m);
}
inline f32& engine::Matrix4::operator ()(std::size_t i, std::size_t j)
{
return operator f32*()[i * 4 + j];
}
inline const f32& engine::Matrix4::operator ()(std::size_t i, std::size_t j) const
{
return operator const f32*()[i * 4 + j];
}
inline engine::Matrix4::operator const f32*() const
{
return &a11;
}
inline engine::Matrix4::operator f32*()
{
return &a11;
}
inline engine::Matrix4 operator *(const Matrix4& m, f32 t)
{
return Matrix4(m.a11 * t, m.a12 * t, m.a13 * t, m.a14 * t,
m.a21 * t, m.a22 * t, m.a23 * t, m.a24 * t,
m.a31 * t, m.a32 * t, m.a33 * t, m.a34 * t,
m.a41 * t, m.a42 * t, m.a43 * t, m.a44 * t);
}
inline engine::Matrix4 operator *(f32 t, const Matrix4& m)
{
return m * t;
}
inline engine::Matrix4 operator /(const Matrix4& m, f32 t)
{
return Matrix4(m.a11 / t, m.a12 / t, m.a13 / t, m.a14 / t,
m.a21 / t, m.a22 / t, m.a23 / t, m.a24 / t,
m.a31 / t, m.a32 / t, m.a33 / t, m.a34 / t,
m.a41 / t, m.a42 / t, m.a43 / t, m.a44 / t);
}
inline std::istream& operator >>(std::istream& iss, Matrix4 &m){
iss >> m.a11 >> m.a12 >> m.a13 >> m.a14;
iss >> m.a21 >> m.a22 >> m.a23 >> m.a24;
iss >> m.a31 >> m.a32 >> m.a33 >> m.a34;
iss >> m.a41 >> m.a42 >> m.a43 >> m.a44;
return iss;
}
inline std::ostream& operator <<(std::ostream& oss, const Matrix4 &m){
oss << m.a11 << " " << m.a12 << " " << m.a13 << " " << m.a14 << std::endl;
oss << m.a21 << " " << m.a22 << " " << m.a23 << " " << m.a24 << std::endl;
oss << m.a31 << " " << m.a32 << " " << m.a33 << " " << m.a34 << std::endl;
oss << m.a41 << " " << m.a42 << " " << m.a43 << " " << m.a44 << std::endl;
return oss;
}
inline void engine::Matrix4::OrthoOffCenter(f32 Left, f32 Top, f32 Right, f32 Bottom){
a11 = 2 / (Right - Left); a12 = 0.f; a13 = 0.f; a14 = 0.f;
a21 = 0.f; a22 = 2 / (Top - Bottom); a23 = 0.f; a24 = 0.f;
a31 = 0.f; a32 = 0.f; a33 = 1.f; a34 = 0.f;
a41 = (1+Right)/(1-Right); a42 = (Top + Bottom) / (Bottom - Top); a43 = 0.f; a44 = 1.f;
}
inline void engine::Matrix4::PerspectiveFOV(f32 FOV, f32 Ratio, f32 Near, f32 Far){
f32 height = 1.f / Math::Tan(FOV/ 2.f);
f32 width = height / Ratio;
f32 NearFarCoeff = Far / (Near - Far);
a11 = width; a12 = 0.f; a13 = 0.f; a14 = 0.f;
a21 = 0.f; a22 = height; a23 = 0.f; a24 = 0.f;
a31 = 0.f; a32 = 0.f; a33 = NearFarCoeff; a34 = -1.f;
a41 = 0.f; a42 = 0.f; a43 = Near * NearFarCoeff; a44 = 0.f;
}
inline void engine::Matrix4::LookAt(const Vector3F &From, const Vector3F &To, const Vector3F &Up){
Vector3F zaxis = From - To;
zaxis.Normalize();
Vector3F xaxis = Cross(Up, zaxis);
xaxis.Normalize();
Vector3F yaxis = Cross(zaxis, xaxis);
a11 = xaxis.x; a12 = yaxis.x; a13 = zaxis.x; a14 = 0.f;
a21 = xaxis.y; a22 = yaxis.y; a23 = zaxis.y; a24 = 0.f;
a31 = xaxis.z; a32 = yaxis.z; a33 = zaxis.z; a34 = 0.f;
a41 = -Dot(xaxis, From); a42 = -Dot(yaxis, From); a43 = -Dot(zaxis, From); a44 = 1.0f;
}
| C++ |
#include "Mathlib.hpp"
#include "Quaternion.hpp"
#include "Matrix4.hpp"
#include "Vector2.hpp"
#include "Vector3.hpp"
namespace engine {
// Mathlib.hpp
const float Math::Pi = 3.14159265f;
const float Math::HalfPi = 1.570796325f;
const float Math::Epsilon = std::numeric_limits<float>::epsilon();
// Vector2.hpp
template<> const Vector2I Vector2I::ZERO = Vector2I(0,0);
template<> const Vector2F Vector2F::ZERO = Vector2F(0.f, 0.f);
// Vector3.hpp
template<> const Vector3I Vector3I::ZERO = Vector3I(0,0,0);
template<> const Vector3F Vector3F::ZERO = Vector3F(0.f,0.f,0.f);
template<> const Vector3F Vector3F::UNIT_Z = Vector3F(0.f,0.f,1.f);
template<> const Vector3F Vector3F::UNIT_X = Vector3F(1.f,0.f,0.f);
template<> const Vector3F Vector3F::UNIT_Y = Vector3F(0.f,1.f,0.f);
template<> const Vector3F Vector3F::NEGUNIT_Z = Vector3F(0.f,0.f,-1.f);
template<> const Vector3F Vector3F::NEGUNIT_X = Vector3F(-1.f,0.f,0.f);
template<> const Vector3F Vector3F::NEGUNIT_Y = Vector3F(0.f,-1.f,0.f);
// Matrix4.hpp
const Matrix4 Matrix4::IDENTITY = Matrix4();
void Matrix4::SetOrientation(const Quaternion &pQuat){
Matrix4 tempMat = pQuat.ToMatrix();
tempMat.SetTranslation(this->GetTranslation());
*this = tempMat;
}
void Matrix4::Rotate(const Quaternion &pQuat){
Quaternion oldOrient, newOrient;
oldOrient.FromMatrix(*this);
newOrient = oldOrient * pQuat;
this->SetOrientation(newOrient);
}
}
| C++ |
#include "Rectangle.hpp"
namespace engine {
Rectangle::Rectangle(s32 top, s32 left, s32 width, s32 height) : Origin(Vector2I(left, top)), End(Vector2I(left + width, top + height)){
}
Rectangle::Rectangle(const Vector2I &topLeft, const Vector2I &size) : Origin(topLeft), End(topLeft + size){
}
void Rectangle::Set(s32 top, s32 left, s32 width, s32 height){
Origin = Vector2I(left, top);
End = Vector2I(left + width, top + height);
}
s32 Rectangle::Left() const{
return Origin.x;
}
s32 Rectangle::Top() const{
return Origin.y;
}
s32 Rectangle::Right() const{
return End.x;
}
s32 Rectangle::Bottom() const{
return End.y;
}
s32 Rectangle::Width() const{
return End.x - Origin.x;
}
s32 Rectangle::Height() const{
return End.y - Origin.y;
}
Vector2I Rectangle::Size() const{
return End - Origin;
}
IntersectionResult Rectangle::Intersects(const Vector2I &Point) const{
if(Point.x >= Origin.x && Point.x <= End.x && Point.y >= Origin.y && Point.y <= End.y)
return INTR_In;
else
return INTR_Out;
}
IntersectionResult Rectangle::Intersects(const Rectangle &Rect) const{
// Creation du rectangle d'Intersection
Vector2I newRectOrigin(Math::Max(Origin.x, Rect.Origin.x), Math::Max(Origin.y, Rect.Origin.y));
Vector2I newRectEnd(Math::Min(End.x, Rect.End.x), Math::Min(End.y, Rect.End.y));
Rectangle newRect(newRectOrigin, newRectEnd);
if(newRectOrigin.x > newRectEnd.x || newRectOrigin.y > newRectEnd.y) // Si le rectangle d'Intersection est a l'exterieur d'un des deux rectangles
return INTR_Out;
else if(newRect == *this || newRect == Rect) // Si le rectangle d'Intersection est contenu dans un des deux rectangles
return INTR_In;
else // Sinon, une partie seulement est contenue, Intersection simple
return INTR_Intersect;
}
bool Rectangle::operator== (const Rectangle &Rect) const{
return ( Origin == Rect.Origin ) && ( End == Rect.End );
}
bool Rectangle::operator!= (const Rectangle &Rect) const{
return !(*this == Rect);
}
std::istream& operator>>(std::istream& iss, Rectangle& Rect){
return iss >> Rect.Origin >> Rect.End;
}
std::ostream& operator<<(std::ostream& oss, const Rectangle& Rect){
return oss << Rect.Origin << " " << Rect.End;
}
}
| C++ |
#ifndef AABB_HPP
#define AABB_HPP
#include "Vector3.hpp"
namespace engine {
struct Vertex;
class Quaternion;
/// \brief Axis-Aligned Bounding Box Class
class OOXAPI AABB{
/// For BSphere computation
friend class BSphere;
public:
/// \brief Ctor from already known bounding box
AABB(Vector3F pOrigin = Vector3F::ZERO, Vector3F pEnd = Vector3F::ZERO);
/// \brief Initialize the AABB from a vertices array
/// \param pVertices : vertice array
/// \param pSize : element number in above array
void Init(Vector3F* pVertices, u32 pSize);
/// \brief Sets the AABB origin position
void SetOrigin(const Vector3F &pOrigin) { mOrigin = pOrigin; }
/// \brief Sets the AABB end position
void SetEnd(const Vector3F &pEnd) { mEnd = pEnd; }
/// \brief Scales the AABB with factors depending on axis
void Scale(const Vector3F &pScaleFactor);
/// \brief Moves the AABB with a Vector
void Translate(const Vector3F &pTrans);
/// \brief Rotate the AABB with a Quaternion
void Rotate(const Quaternion &pOrient);
/// \brief Returns the 8 positions of the AABB
void GetVertices(Vector3F pTab[8]) const;
protected:
Vector3F mOrigin;
Vector3F mEnd;
};
/// \brief Bounding Sphere class
class BSphere{
public:
/// \brief Ctor from an Origin point and a Radius
BSphere(Vector3F pOrigin = Vector3F::ZERO, f32 mRadius = 1.f);
/// \brief Initialize the BSphere from a vertices array
/// \param pVertices : vertices array
/// \param pSize : element number in above array
void Init(Vertex* pVertices, u32 pSize);
/// \brief Initialize the BSphere from an AABB
void Init(const AABB &pAABB);
/// \brief Sets the BSphere radius
void SetRadius(f32 pValue) { mRadius = pValue; }
/// \brief Sets the BSphere Origin point
void SetOrigin(const Vector3F &pOrigin) { mOrigin = pOrigin; }
/// \brief Moves the BSphere with a Vector3
void Translate(const Vector3F &pTrans){ mOrigin += pTrans; }
/// \brief Scales the BSPhere
void Scale(f32 pScaleFactor) { mRadius *= pScaleFactor; }
/// \brief Returns the BSphere radius
f32 GetRadius() const { return mRadius; }
/// \brief Returns the BSphere origin point
const Vector3F& GetOrigin() const { return mOrigin; }
private:
f32 mRadius;
Vector3F mOrigin;
};
}
#endif
| C++ |
#ifndef MATHLIB_HPP
#define MATHLIB_HPP
#include <cmath>
#include <iostream>
#include <limits>
#include "Utils/Shared.hpp"
namespace engine {
class OOXAPI Math{
public:
/// Fonctions
static f32 ToDeg(f32 radian);
static f32 ToRad(f32 degree);
static f32 Cos(f32 value);
static f32 Sin(f32 value);
static f32 Tan(f32 value);
static f32 ACos(f32 value);
static f32 ASin(f32 value);
static f32 ATan(f32 value);
static f32 ATan2(f32 Y, f32 X);
static f32 Sqrt(f32 value);
static f32 InvSqrt(f32 value);
static f32 Ceil(f32 value);
static f32 Floor(f32 value);
static f32 Abs(f32 value);
static f32 Pow(f32 value, u32 exp);
static f32 Exp(f32 value);
static int Sign(int value);
static int Sign(f32 value);
template<typename T> static T Max(T a, T b);
template<typename T> static T Min(T a, T b);
/// \brief Random between min and max
static f32 Rand(u32 min = 0, u32 max = 1, u32 seed = 0);
/// \brief Not a Number check
static bool IsNaN(double x);
/// \brief Quasi-equality between to floats
static bool IsEqual(f32 x, f32 y);
/// \brief Power of 2
static bool IsPowOf2(u32 value);
/// \brief Clamp a value between to other
/// \param val : value to clamp
/// \param min : lower bound
/// \param max : upper bound
static f32 Clamp(f32 val, f32 min, f32 max);
/// Constants
static const f32 Epsilon; /// Constant used to compare two floats
static const f32 Pi;
static const f32 HalfPi;
};
#include "Mathlib.inl"
}
#endif
| C++ |
#ifndef MATRIX4_HPP
#define MATRIX4_HPP
#include "Vector2.hpp"
#include "Vector3.hpp"
namespace engine {
class Quaternion;
class Matrix4{
public:
/// \brief Ctor, Identity matrix
Matrix4(f32 m11 = 1.f, f32 m12 = 0.f, f32 m13 = 0.f, f32 m14 = 0.f,
f32 m21 = 0.f, f32 m22 = 1.f, f32 m23 = 0.f, f32 m24 = 0.f,
f32 m31 = 0.f, f32 m32 = 0.f, f32 m33 = 1.f, f32 m34 = 0.f,
f32 m41 = 0.f, f32 m42 = 0.f, f32 m43 = 0.f, f32 m44 = 1.f);
/// \brief Make the matrix an identity matrix
void Identity();
/// \brief Fill a float array with matrix data
void ToFloat(f32* tab) const;
/// \brief Returns the matrix determinant
f32 Det() const;
/// \brief Returns the matrix Inverse
Matrix4 Inverse() const;
/// \brief Returns the matrix Transpose
Matrix4 Transpose() const;
/// \brief Create a Translation matrix
void SetTranslation(f32 x, f32 y, f32 z);
void SetTranslation(const Vector3F &V);
/// \brief Create a matrix from axis-dependant scale components
void SetScale(f32 x, f32 y, f32 z);
void SetScale(const Vector3F &V);
/// \brief Create a matrix from scale component
void SetScale(f32 xyz);
/// \brief Create a Rotation matrix from angle centered on (0,0,0)
void SetRotationX(f32 Angle);
void SetRotationY(f32 Angle);
void SetRotationZ(f32 Angle);
/// \brief Create a Rotation matrix from Axis-Angle constraints
void SetRotationX(f32 Angle, const Vector3F &Axis);
void SetRotationY(f32 Angle, const Vector3F &Axis);
void SetRotationZ(f32 Angle, const Vector3F &Axis);
/// \brief Sets the rotation component of the matrix
void SetOrientation(const Quaternion &pQuat);
/// \brief Add a Rotation component to the matrix
void Rotate(const Quaternion &pQuat);
/// \brief Add a translation component to the matrix
void Translate(const Vector3F &pVector);
/// \brief Scales the matrix from axis dependant factors
void Scale(const Vector3F &pVector);
/// \brief Scales the matrix on all axis by the same factor
void Scale(f32 pFactor);
/// \brief Returns the Translation component
Vector3F GetTranslation() const;
/// \brief Returns the Scale component
Vector3F GetScale() const;
/// \brief Transform a Vector3 by multiplying it with the matrix
Vector3F Transform(const Vector3F &V, f32 w = 0.f) const;
/// \brief Construct a matrix from Translation and Rotation components
void WorldMatrix(const Vector3F &Translation, const Vector3F &Rotation);
/// \brief Construct a 2D Orthogonal matrix
/// params : Boundaries of orthogonal zone. Generally the window bounds
void OrthoOffCenter(f32 Left, f32 Top, f32 Right, f32 Bottom);
/// \brief Construct a Perspective Projection Matrix
/// \param FOV : Vertical Field of view
/// \param Ratio : Width/Height ratio
/// \param Near : Near plane
/// \param Far : Far plane
void PerspectiveFOV(f32 FOV, f32 Ratio, f32 Near, f32 Far);
/// \brief Construct a LookAt Matrix
/// \param From : Position of eye
/// \param To : Position pointed by eye
/// \param Up : Up Vector, UNIT_Y in the engine
void LookAt(const Vector3F &From, const Vector3F &To, const Vector3F &Up = Vector3F::UNIT_Y);
/// Operations
/// \brief Returns the negate matrix
Matrix4 operator -() const;
/// \brief Matrix addition/substraction functions
Matrix4 operator +(const Matrix4& m) const;
Matrix4 operator -(const Matrix4& m) const;
const Matrix4& operator +=(const Matrix4& m);
const Matrix4& operator -=(const Matrix4& m);
/// \brief Matrix multiplication functions
Matrix4 operator *(const Matrix4& m) const;
const Matrix4& operator *=(const Matrix4& m);
/// \brief Multiplies matrix data with a float
const Matrix4& operator *=(f32 t);
/// \brief Divides matrix data with a float
const Matrix4& operator /=(f32 t);
/// \brief Comparison operators
bool operator ==(const Matrix4& m) const;
bool operator !=(const Matrix4& m) const;
/// \brief Data access operators
f32& operator ()(std::size_t i, std::size_t j);
const f32& operator ()(std::size_t i, std::size_t j) const;
/// \brief Returns a pointer on a11 (for floats arrays)
operator f32*();
operator const f32*() const;
/// Constant Identity matrix
static const OOXAPI Matrix4 IDENTITY;
// Data
f32 a11, a12, a13, a14; // 1st row
f32 a21, a22, a23, a24; // 2nd row
f32 a31, a32, a33, a34; // 3rd row
f32 a41, a42, a43, a44; // 4th row
};
Matrix4 operator*(const Matrix4 &m, f32 t);
Matrix4 operator/(const Matrix4 &m, f32 t);
Matrix4 operator*(f32 t, const Matrix4 &m);
std::istream& operator >>(std::istream& iss, Matrix4 &m);
std::ostream& operator <<(std::ostream& oss, const Matrix4 &m);
#include "Matrix4.inl"
}
#endif
| C++ |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.