code
stringlengths 1
2.01M
| repo_name
stringlengths 3
62
| path
stringlengths 1
267
| language
stringclasses 231
values | license
stringclasses 13
values | size
int64 1
2.01M
|
|---|---|---|---|---|---|
#ifndef _TINY_LOG_BASE_H
#define _TINY_LOG_BASE_H
#ifdef __GNUC__
#define TLAPI
#define C_TLAPI extern "C"
#else
#ifdef BUILD_AS_DLL
#define TLAPI __declspec(dllexport)
#define C_TLAPI extern "C" __declspec(dllexport)
#else
#define TLAPI __declspec(dllimport)
#define C_TLAPI extern "C" __declspec(dllimport)
#endif
#endif
#define CONDITION_ERROR(Condition) \
do \
{ \
if (!(Condition)) \
goto Error; \
}while(false)
#define CONDITION_SUCCESS(Condition) \
do \
{ \
if (Condition) \
goto Success; \
}while(false)
#ifndef SAFE_FREE
#define SAFE_FREE(a) if (a) { free(a); (a) = null; }
#endif //SAFE_FREE
#ifndef SAFE_DELETE
#define SAFE_DELETE(a) if (a) { delete (a); (a) = null; }
#endif //SAFE_DELETE
#ifndef SAFE_RELEASE
#define SAFE_RELEASE(a) if (a) { (a)->Release(); (a) = null; }
#endif //SAFE_RELEASE
#endif //_TINY_LOG_BASE_H
|
zzengine
|
trunk/TinyLog/include/TLBase.h
|
C
|
gpl3
| 914
|
#ifndef _TINY_LOG_DEFINE_H
#define _TINY_LOG_DEFINE_H
enum TINY_LOG_PRIORITY
{
eTinyLogPriorityReserve0 = 0,
eTinyLogPriorityReserve1 = 1,
eTinyLogPriorityReserve2 = 2,
eTinyLogPriorityError = 3,
eTinyLogPriorityReserve4 = 4,
eTinyLogPriorityWarning = 5,
eTinyLogPriorityReserve6 = 6,
eTinyLogPriorityInfo = 7,
eTinyLogPriorityReserve8 = 8,
eTinyLogPriorityDebug = 9,
eTinyLogPriorityReserve10 = 10,
eTinyLogPriorityCount
};
enum TINY_LOG_OPTION
{
eTinyLogOptionFile = 0x01,
eTinyLogOptionConsole = 0x01 << 1,
eTinyLogOptionStderr = 0x01 << 2,
};
#define GLOBAL_CLASSIFY_NAME "_Global"
struct TL_LOG_INFO
{
char BeginTag[3]; /* 0xFF; beginning of a log. 0xFFE for normal; 0xFFF for offset. */
char oftSecond[4]; /* offset; seconds passed from log begin */
char oftClassify[2]; /* offset; const char* pcszClassity */
char idxPriority; /* enum of TINY_LOG_PRIORITY; */
char oftCondition[2]; /* offset; const char* pcszCondition */
char nLine[4]; /* int; code line number */
char oftFunctionName[2];/* offset; const char* pcszFunctionName */
char oftInfo[2]; /* offset; const char* pcszAdditionInfo */
}; /* 20 bytes total */
typedef unsigned long FOURCC;
#define TLOG_TAG 'TLOG'
#define VERSION0 'V000'
struct TL_RUNTIME_PATTERN
{
unsigned cbSize;
FOURCC fccTag; /* 'TLOG' */
FOURCC fccVersion; /* 'V000' newest */
time_t ttTimeStamp;
};
#define FILE_NAME_LENGTH 32
#define FILE_PATH_LENGTH 256
#define MAX_FILE_LENGTH (1 << 16)
#endif //_TINY_LOG_DEFINE_H
|
zzengine
|
trunk/TinyLog/include/TLDefine.h
|
C
|
gpl3
| 1,567
|
/*
* TimeStamp.hh
*
* Copyright 2001, LifeLine Networks BV (www.lifeline.nl). All rights reserved.
* Copyright 2001, Bastiaan Bakker. All rights reserved.
*
* See the COPYING file for the terms of usage and distribution.
*/
#ifndef _LOG4CPP_TIMESTAMP_HH
#define _LOG4CPP_TIMESTAMP_HH
#include <log4cpp/Portability.hh>
namespace log4cpp {
/**
* A simple TimeStamp abstraction
**/
class LOG4CPP_EXPORT TimeStamp {
public:
/**
Constructs a TimeStamp representing 'now'.
**/
TimeStamp();
/**
Constructs a TimeStamp representing the given offset since the
epoch ( 00:00:00 1970/1/1 UTC).
**/
TimeStamp(unsigned int seconds, unsigned int microSeconds = 0);
/**
Returns the 'seconds' part of the TimeStamp.
**/
inline int getSeconds() const {
return _seconds;
};
/**
Returns the 'subseconds' part of the TimeStamp in milliseconds,
getMilliSeconds() == getMicroSeconds() / 1000.
**/
inline int getMilliSeconds() const {
return _microSeconds / 1000;
};
/**
Returns the subsecond part of the TimeStamp in microseconds.
The actual precision of this value depends on the platform and
may be in the order of milliseconds rather than microseconds.
**/
inline int getMicroSeconds() const {
return _microSeconds;
};
/**
Returns a TimeStamp representing the time at which the application
started.
**/
static inline const TimeStamp& getStartTime() {
return _startStamp;
};
protected:
static TimeStamp _startStamp;
int _seconds;
int _microSeconds;
};
}
#endif // _LOG4CPP_TIMESTAMP_HH
|
zzengine
|
trunk/TinyLog/include/log4cpp/TimeStamp.hh
|
C++
|
gpl3
| 1,896
|
/*
* Filter.hh
*
* Copyright 2001, LifeLine Networks BV (www.lifeline.nl). All rights reserved.
* Copyright 2001, Bastiaan Bakker. All rights reserved.
*
* See the COPYING file for the terms of usage and distribution.
*/
#ifndef _LOG4CPP_FILTER_HH
#define _LOG4CPP_FILTER_HH
#include <log4cpp/Portability.hh>
#include <log4cpp/LoggingEvent.hh>
namespace log4cpp {
/**
Users should extend this class to implement customized logging
event filtering. Note that log4cpp::Category and
lof4cpp::Appender have built-in filtering rules. It is suggested
that you first use and understand the built-in rules before rushing
to write your own custom filters.
<p>This abstract class assumes and also imposes that filters be
organized in a linear chain. The <code>decide(LoggingEvent)</code>
method of each filter is called sequentially, in the order of their
addition to the chain.
<p>The <code>decide(LoggingEvent)</code> method must return a
Decision value, either DENY, NEUTRAL or ACCCEPT.
<p>If the value DENY is returned, then the log event is
dropped immediately without consulting with the remaining
filters.
<p>If the value NEUTRAL is returned, then the next filter
in the chain is consulted. If there are no more filters in the
chain, then the log event is logged. Thus, in the presence of no
filters, the default behaviour is to log all logging events.
<p>If the value ACCEPT is returned, then the log
event is logged without consulting the remaining filters.
<p>The philosophy of log4cpp filters is largely inspired from the
Linux ipchains.
**/
class LOG4CPP_EXPORT Filter {
public:
typedef enum { DENY = -1,
NEUTRAL = 0,
ACCEPT = 1
} Decision;
/**
* Default Constructor for Filter
**/
Filter();
/**
* Destructor for Filter
**/
virtual ~Filter();
/**
* Set the next Filter in the Filter chain
* @param filter The filter to chain
**/
virtual void setChainedFilter(Filter* filter);
/**
* Get the next Filter in the Filter chain
* @return The next Filter or NULL if the current filter is the last
* in the chain
**/
virtual Filter* getChainedFilter();
/**
* Get the last Filter in the Filter chain
* @return The last Filter in the Filter chain
**/
virtual Filter* getEndOfChain();
/**
* Add a Filter to the end of the Filter chain. Convience method for
* getEndOfChain()->setChainedFilter(filter).
* @param filter The filter to add to the end of the chain.
**/
virtual void appendChainedFilter(Filter* filter);
/**
* Decide whether to accept or deny a LoggingEvent. This method will
* walk the entire chain until a non neutral decision has been made
* or the end of the chain has been reached.
* @param event The LoggingEvent to decide on.
* @return The Decision
**/
virtual Decision decide(const LoggingEvent& event);
protected:
/**
* Decide whether <b>this</b> Filter accepts or denies the given
* LoggingEvent. Actual implementation of Filter should override this
* method and not <code>decide(LoggingEvent&)</code>.
* @param event The LoggingEvent to decide on.
* @return The Decision
**/
virtual Decision _decide(const LoggingEvent& event) = 0;
private:
Filter* _chainedFilter;
};
}
#endif // _LOG4CPP_FILTER_HH
|
zzengine
|
trunk/TinyLog/include/log4cpp/Filter.hh
|
C++
|
gpl3
| 3,850
|
/*
* SyslogAppender.hh
*
* Copyright 2000, LifeLine Networks BV (www.lifeline.nl). All rights reserved.
* Copyright 2000, Bastiaan Bakker. All rights reserved.
*
* See the COPYING file for the terms of usage and distribution.
*/
#ifndef _LOG4CPP_SYSLOGAPPENDER_HH
#define _LOG4CPP_SYSLOGAPPENDER_HH
#include <log4cpp/Portability.hh>
#include <string>
#include <stdarg.h>
#include <syslog.h>
#include <log4cpp/LayoutAppender.hh>
#include <log4cpp/Priority.hh>
namespace log4cpp {
/**
* SyslogAppender sends LoggingEvents to the local syslog system.
**/
class SyslogAppender : public LayoutAppender {
public:
/**
* Translates a log4cpp priority to a syslog priority
* @param priority The log4cpp priority.
* @returns the syslog priority.
**/
static int toSyslogPriority(Priority::Value priority);
/**
* Instantiate a SyslogAppender with given name and name and facility
* for syslog. Note that the C syslog API is process global, so
* instantion of a second SyslogAppender will 'overwrite' the
* syslog name of the first.
* @param name The name of the Appender
* @param syslogName The ident parameter in the openlog(3) call.
* @param facility The syslog facility to log to. Defaults to LOG_USER.
**/
SyslogAppender(const std::string& name, const std::string& syslogName,
int facility = LOG_USER);
virtual ~SyslogAppender();
/**
* Calls closelog(3) and openlog(3).
**/
virtual bool reopen();
/**
* Calls closelog(3) to close the syslog file descriptor.
**/
virtual void close();
protected:
/**
* Calls openlog(3).
**/
virtual void open();
/**
* Sends a LoggingEvent to syslog.
* @param event the LoggingEvent to log.
**/
virtual void _append(const LoggingEvent& event);
const std::string _syslogName;
int _facility;
};
}
#endif // _LOG4CPP_SYSLOGAPPENDER_HH
|
zzengine
|
trunk/TinyLog/include/log4cpp/SyslogAppender.hh
|
C++
|
gpl3
| 2,164
|
/*
* AbortAppender.hh
*
* Copyright 2002, LifeLine Networks BV (www.lifeline.nl). All rights reserved.
* Copyright 2002, Bastiaan Bakker. All rights reserved.
*
* See the COPYING file for the terms of usage and distribution.
*/
#ifndef _LOG4CPP_ABORTAPPENDER_HH
#define _LOG4CPP_ABORTAPPENDER_HH
#include <log4cpp/Portability.hh>
#include <log4cpp/AppenderSkeleton.hh>
namespace log4cpp {
/**
* This Appender causes the application to abort() upon the first append()
* call.
*
* @since 0.3.5
**/
class LOG4CPP_EXPORT AbortAppender : public AppenderSkeleton {
public:
AbortAppender(const std::string& name);
virtual ~AbortAppender();
virtual bool reopen();
virtual void close();
/**
* The AbortAppender does not layout.
* @returns false
**/
virtual bool requiresLayout() const;
virtual void setLayout(Layout* layout);
protected:
virtual void _append(const LoggingEvent& event);
};
}
#endif // _LOG4CPP_ABORTAPPENDER_HH
|
zzengine
|
trunk/TinyLog/include/log4cpp/AbortAppender.hh
|
C++
|
gpl3
| 1,096
|
/*
* SimpleLayout.hh
*
* Copyright 2000, LifeLine Networks BV (www.lifeline.nl). All rights reserved.
* Copyright 2000, Bastiaan Bakker. All rights reserved.
*
* See the COPYING file for the terms of usage and distribution.
*/
#ifndef _LOG4CPP_SIMPLELAYOUT_HH
#define _LOG4CPP_SIMPLELAYOUT_HH
#include <log4cpp/Portability.hh>
#include <log4cpp/Layout.hh>
namespace log4cpp {
/**
* BasicLayout is a simple fixed format Layout implementation.
**/
class LOG4CPP_EXPORT SimpleLayout : public Layout {
public:
SimpleLayout();
virtual ~SimpleLayout();
/**
* Formats the LoggingEvent in SimpleLayout style:<br>
* "priority - message"
**/
virtual std::string format(const LoggingEvent& event);
};
}
#endif // _LOG4CPP_SIMPLELAYOUT_HH
|
zzengine
|
trunk/TinyLog/include/log4cpp/SimpleLayout.hh
|
C++
|
gpl3
| 842
|
/*
* StringQueueAppender.hh
*
* Copyright 2000, LifeLine Networks BV (www.lifeline.nl). All rights reserved.
* Copyright 2000, Bastiaan Bakker. All rights reserved.
*
* See the COPYING file for the terms of usage and distribution.
*/
#ifndef _LOG4CPP_STRINGQUEUEAPPENDER_HH
#define _LOG4CPP_STRINGQUEUEAPPENDER_HH
#include <log4cpp/Portability.hh>
#include <string>
#include <queue>
#include <log4cpp/LayoutAppender.hh>
namespace log4cpp {
/**
* This class puts log messages in an in-memory queue. Its primary use
* is in test cases, but it may be useful elsewhere as well.
*
* @since 0.2.4
**/
class LOG4CPP_EXPORT StringQueueAppender : public LayoutAppender {
public:
StringQueueAppender(const std::string& name);
virtual ~StringQueueAppender();
virtual bool reopen();
virtual void close();
/**
* Return the current size of the message queue.
* Shorthand for getQueue().size().
* @returns the queue size
**/
virtual size_t queueSize() const;
/**
* Return the queue to which the Appends adds messages.
* @returns the message queue
**/
virtual std::queue<std::string>& getQueue();
/**
* Return the queue to which the Appends adds messages.
* @returns the message queue
**/
virtual const std::queue<std::string>& getQueue() const;
/**
* Pop the oldest log message from the front of the queue.
* @returns the oldest log message
**/
virtual std::string popMessage();
protected:
/**
* Appends the LoggingEvent to the queue.
* @param event the LoggingEvent to layout and append to the queue.
**/
virtual void _append(const LoggingEvent& event);
std::queue<std::string> _queue;
};
}
#endif // _LOG4CPP_STRINGQUEUEAPPENDER_HH
|
zzengine
|
trunk/TinyLog/include/log4cpp/StringQueueAppender.hh
|
C++
|
gpl3
| 1,974
|
/*
* FileAppender.hh
*
* Copyright 2000, LifeLine Networks BV (www.lifeline.nl). All rights reserved.
* Copyright 2000, Bastiaan Bakker. All rights reserved.
*
* See the COPYING file for the terms of usage and distribution.
*/
#ifndef _LOG4CPP_FILEAPPENDER_HH
#define _LOG4CPP_FILEAPPENDER_HH
#include <log4cpp/Portability.hh>
#include <log4cpp/LayoutAppender.hh>
#include <string>
#include <stdarg.h>
namespace log4cpp {
class LOG4CPP_EXPORT FileAppender : public LayoutAppender {
public:
/**
Constructs a FileAppender.
@param name the name of the Appender.
@param fileName the name of the file to which the Appender has
to log.
@param append whether the Appender has to truncate the file or
just append to it if it already exists. Defaults to 'true'.
@param mode file mode to open the logfile with. Defaults to 00644.
**/
FileAppender(const std::string& name, const std::string& fileName,
bool append = true, mode_t mode = 00644);
/**
Constructs a FileAppender to an already open file descriptor.
@param name the name of the Appender.
@param fd the file descriptor to which the Appender has to log.
**/
FileAppender(const std::string& name, int fd);
virtual ~FileAppender();
/**
Reopens the logfile.
This can be useful for logfiles that are rotated externally,
e.g. by logrotate. This method is a NOOP for FileAppenders that
have been constructed with a file descriptor.
@returns true if the reopen succeeded.
**/
virtual bool reopen();
/**
Closes the logfile.
**/
virtual void close();
/**
Sets the append vs truncate flag.
NB. currently the FileAppender opens the logfile in the
constructor. Therefore this method is too late to influence the
first file opening. We'll need something similar to log4j's
activateOptions().
@param append false to truncate, true to append
**/
virtual void setAppend(bool append);
/**
Gets the value of the 'append' option.
**/
virtual bool getAppend() const;
/**
Sets the file open mode.
**/
virtual void setMode(mode_t mode);
/**
Gets the file open mode.
**/
virtual mode_t getMode() const;
protected:
virtual void _append(const LoggingEvent& event);
const std::string _fileName;
int _fd;
int _flags;
mode_t _mode;
};
}
#endif // _LOG4CPP_FILEAPPENDER_HH
|
zzengine
|
trunk/TinyLog/include/log4cpp/FileAppender.hh
|
C++
|
gpl3
| 2,798
|
/*
* AppenderSkeleton.hh
*
* Copyright 2001, LifeLine Networks BV (www.lifeline.nl). All rights reserved.
* Copyright 2001, Bastiaan Bakker. All rights reserved.
*
* See the COPYING file for the terms of usage and distribution.
*/
#ifndef _LOG4CPP_APPENDERSKELETON_HH
#define _LOG4CPP_APPENDERSKELETON_HH
#include <log4cpp/Portability.hh>
#include <log4cpp/Appender.hh>
#include <log4cpp/Filter.hh>
namespace log4cpp {
/**
* AppenderSkeleton is a helper class, simplifying implementation of
* Appenders: it already takes care of handling of Thresholds and
* Filters.
**/
class LOG4CPP_EXPORT AppenderSkeleton : public Appender {
protected:
/**
* Constructor for AppenderSkeleton. Will only be used in
* getAppender() (and in derived classes of course).
* @param name The name of this Appender.
**/
AppenderSkeleton(const std::string& name);
public:
/**
* Destructor for AppenderSkeleton.
**/
virtual ~AppenderSkeleton();
/**
* Log in Appender specific way.
* @param event The LoggingEvent to log.
**/
virtual void doAppend(const LoggingEvent& event);
/**
* Reopens the output destination of this Appender, e.g. the logfile
* or TCP socket.
* @returns false if an error occured during reopening, true otherwise.
**/
virtual bool reopen();
/**
* Release any resources allocated within the appender such as file
* handles, network connections, etc.
**/
virtual void close() = 0;
/**
* Check if the appender uses a layout.
*
* @returns true if the appender implementation requires a layout.
**/
virtual bool requiresLayout() const = 0;
/**
* Set the Layout for this appender.
* @param layout The layout to use.
**/
virtual void setLayout(Layout* layout) = 0;
/**
* Set the threshold priority of this Appender. The Appender will not
* appender LoggingEvents with a priority lower than the threshold.
* Use Priority::NOTSET to disable threshold checking.
* @param priority The priority to set.
**/
virtual void setThreshold(Priority::Value priority);
/**
* Get the threshold priority of this Appender.
* @returns the threshold
**/
virtual Priority::Value getThreshold();
/**
* Set a Filter for this appender.
**/
virtual void setFilter(Filter* filter);
/**
* Get the Filter for this appender.
* @returns the filter, or NULL if no filter has been set.
**/
virtual Filter* getFilter();
protected:
/**
* Log in Appender specific way. Subclasses of Appender should
* implement this method to perform actual logging.
* @param event The LoggingEvent to log.
**/
virtual void _append(const LoggingEvent& event) = 0;
private:
Priority::Value _threshold;
Filter* _filter;
};
}
#endif // _LOG4CPP_APPENDERSKELETON_HH
|
zzengine
|
trunk/TinyLog/include/log4cpp/AppenderSkeleton.hh
|
C++
|
gpl3
| 3,285
|
/*
* SyslogAppender.hh
*
* Copyright 2001, LifeLine Networks BV (www.lifeline.nl). All rights reserved.
* Copyright 2001, Walter Stroebel. All rights reserved.
*
* See the COPYING file for the terms of usage and distribution.
*/
#ifndef _LOG4CPP_REMOTESYSLOGAPPENDER_HH
#define _LOG4CPP_REMOTESYSLOGAPPENDER_HH
#include <log4cpp/Portability.hh>
#include <string>
#include <stdarg.h>
#include <log4cpp/LayoutAppender.hh>
#include <log4cpp/Priority.hh>
#ifdef WIN32
#include <winsock2.h>
#else
#include <netinet/in.h>
#endif
#ifdef LOG4CPP_HAVE_SYSLOG
#include <syslog.h>
#else
/// from syslog.h
typedef enum {
LOG_EMERG = 0, ///< system is unusable
LOG_ALERT = 1, ///< action must be taken immediately
LOG_CRIT = 2, ///< critical conditions
LOG_ERR = 3, ///< error conditions
LOG_WARNING = 4, ///< warning conditions
LOG_NOTICE = 5, ///< normal but significant condition
LOG_INFO = 6, ///< informational
LOG_DEBUG = 7, ///< debug-level messages
} SyslogLevel;
typedef enum {
LOG_KERN = (0<<3), ///< kernel messages
LOG_USER = (1<<3), ///< random user-level messages
LOG_MAIL = (2<<3), ///< mail system
LOG_DAEMON = (3<<3), ///< system daemons
LOG_AUTH = (4<<3), ///< security/authorization messages
LOG_SYSLOG = (5<<3), ///< messages generated internally by syslogd
LOG_LPR = (6<<3), ///< line printer subsystem
LOG_NEWS = (7<<3), ///< network news subsystem
LOG_UUCP = (8<<3), ///< UUCP subsystem
LOG_CRON = (9<<3), ///< clock daemon
LOG_AUTHPRIV = (10<<3), ///< security/authorization messages (private)
LOG_FTP = (11<<3), ///< ftp daemon
/* other codes through 15 reserved for system use */
LOG_LOCAL0 = (16<<3), ///< reserved for local use
LOG_LOCAL1 = (17<<3), ///< reserved for local use
LOG_LOCAL2 = (18<<3), ///< reserved for local use
LOG_LOCAL3 = (19<<3), ///< reserved for local use
LOG_LOCAL4 = (20<<3), ///< reserved for local use
LOG_LOCAL5 = (21<<3), ///< reserved for local use
LOG_LOCAL6 = (22<<3), ///< reserved for local use
LOG_LOCAL7 = (23<<3), ///< reserved for local use
} SyslogFacility;
#endif
namespace log4cpp {
/**
* RemoteSyslogAppender sends LoggingEvents to a remote syslog system.
*
* Also see: draft-ietf-syslog-syslog-12.txt
**/
class LOG4CPP_EXPORT RemoteSyslogAppender : public LayoutAppender {
public:
/**
* Translates a log4cpp priority to a syslog priority
* @param priority The log4cpp priority.
* @returns the syslog priority.
**/
static int toSyslogPriority(Priority::Value priority);
/**
* Instantiate a RemoteSyslogAppender with given name and name and
* facility for syslog.
* @param name The name of the Appender
* @param syslogName The ident parameter in the openlog(3) call.
* @param relayer The IP address or hostname of a standard syslog host.
* @param facility The syslog facility to log to. Defaults to LOG_USER.
* Value '-1' implies to use the default.
* @param portNumber An alternative port number. Defaults to the
* standard syslog port number (514).
* Value '-1' implies to use the default.
**/
RemoteSyslogAppender(const std::string& name,
const std::string& syslogName,
const std::string& relayer,
int facility = LOG_USER,
int portNumber = 514);
virtual ~RemoteSyslogAppender();
/**
* Closes and reopens the socket.
**/
virtual bool reopen();
/**
* Closes the socket
**/
virtual void close();
protected:
/**
* Just creates the socket.
**/
virtual void open();
/**
* Sends a LoggingEvent to the remote syslog.
* @param event the LoggingEvent to log.
**/
virtual void _append(const LoggingEvent& event);
const std::string _syslogName;
const std::string _relayer;
int _facility;
int _portNumber;
#ifdef WIN32
SOCKET _socket;
#else
int _socket;
#endif
in_addr_t _ipAddr;
private:
int _cludge;
};
}
#endif // _LOG4CPP_REMOTESYSLOGAPPENDER_HH
|
zzengine
|
trunk/TinyLog/include/log4cpp/RemoteSyslogAppender.hh
|
C++
|
gpl3
| 4,559
|
/*
* CategoryStream.hh
*
* Copyright 2001, LifeLine Networks BV (www.lifeline.nl). All rights reserved.
* Copyright 2001, Bastiaan Bakker. All rights reserved.
*
* See the COPYING file for the terms of usage and distribution.
*/
#ifndef _LOG4CPP_CATEGORYSTREAM_HH
#define _LOG4CPP_CATEGORYSTREAM_HH
#include <log4cpp/Portability.hh>
#include <log4cpp/Priority.hh>
#include <ios>
#ifdef LOG4CPP_HAVE_SSTREAM
#include <sstream>
#endif
#include <log4cpp/Manipulator.hh>
namespace log4cpp {
class LOG4CPP_EXPORT Category;
/**
* This class enables streaming simple types and objects to a category.
* Use category.errorStream(), etc. to obtain a CategoryStream class.
**/
class LOG4CPP_EXPORT CategoryStream {
public:
/**
* Enumeration of special 'Separators'. Currently only contains the
* 'ENDLINE' separator, which separates two log messages.
**/
typedef enum {
ENDLINE = 0,
EOL = 0
} Separator;
/**
* Construct a CategoryStream for given Category with given priority.
* @param category The category this stream will send log messages to.
* @param priority The priority the log messages will get or
* Priority::NOTSET to silently discard any streamed in messages.
**/
CategoryStream(Category& category, Priority::Value priority);
/**
* Destructor for CategoryStream
**/
~CategoryStream();
/**
* Returns the destination Category for this stream.
* @returns The Category.
**/
inline Category& getCategory() const { return _category; };
/**
* Returns the priority for this stream.
* @returns The priority.
**/
inline Priority::Value getPriority() const throw() {
return _priority;
};
/**
* Streams in a Separator. If the separator equals
* CategoryStream::ENDLINE it sends the contents of the stream buffer
* to the Category with set priority and empties the buffer.
* @param separator The Separator
* @returns A reference to itself.
**/
CategoryStream& operator<<(Separator separator);
/**
* Flush the contents of the stream buffer to the Category and
* empties the buffer.
**/
void flush();
/**
* Stream in arbitrary types and objects.
* @param t The value or object to stream in.
* @returns A reference to itself.
**/
template<typename T> CategoryStream& operator<<(const T& t) {
if (getPriority() != Priority::NOTSET) {
if (!_buffer) {
if (!(_buffer = new std::ostringstream)) {
// XXX help help help
}
}
(*_buffer) << t;
}
return *this;
}
template<typename T> CategoryStream& operator<<(const std::string& t) {
if (getPriority() != Priority::NOTSET) {
if (!_buffer) {
if (!(_buffer = new std::ostringstream)) {
// XXX help help help
}
}
(*_buffer) << t;
}
return *this;
}
template<typename T> CategoryStream& operator<<(const std::wstring& t) {
if (getPriority() != Priority::NOTSET) {
if (!_wbuffer) {
if (!(_wbuffer = new std::wostringstream)) {
// XXX help help help
}
}
(*_wbuffer) << t;
}
return *this;
}
/**
* Set the width output on CategoryStream
**/
std::streamsize width(std::streamsize wide );
private:
Category& _category;
Priority::Value _priority;
union {
std::ostringstream* _buffer;
std::wostringstream* _wbuffer;
};
public:
typedef CategoryStream& (*cspf) (CategoryStream&);
CategoryStream& operator<< (cspf);
/**
* eol manipulator
**/
friend LOG4CPP_EXPORT CategoryStream& eol (CategoryStream& os);
/**
* left manipulator
**/
friend LOG4CPP_EXPORT CategoryStream& left (CategoryStream& os);
};
}
#endif // _LOG4CPP_CATEGORYSTREAM_HH
|
zzengine
|
trunk/TinyLog/include/log4cpp/CategoryStream.hh
|
C++
|
gpl3
| 4,456
|
/*
* SimpleConfigurator.hh
*
* Copyright 2001, Glen Scott. All rights reserved.
*
* See the COPYING file for the terms of usage and distribution.
*/
#ifndef _LOG4CPP_SIMPLECONFIGURATOR_HH
#define _LOG4CPP_SIMPLECONFIGURATOR_HH
#include <log4cpp/Portability.hh>
#include <iostream>
#include <string>
#include <log4cpp/Configurator.hh>
namespace log4cpp {
/**
* This class implements a simple Configurator for log4cpp.
* It is a temporary hack with an undocumented configuration format.
* @deprecated As of version 0.3.2 log4cpp includes a log4j format
* compatible PropertyConfigurator, removing the need for
* SimpleConfigurator. This class will be removed in 0.4.0.
**/
class LOG4CPP_EXPORT SimpleConfigurator {
public:
/**
* Configure log4cpp with the configuration in the given file.
* NB. The configuration file format is undocumented and may change
* without notice.
* @since 0.2.6
* @param initFileName name of the configuration file
* @exception ConfigureFailure if the method encountered a read or
* syntax error.
**/
static void configure(const std::string& initFileName) throw (ConfigureFailure);
/**
* Configure log4cpp with the configuration in the given file.
* NB. The configuration file format is undocumented and may change
* without notice.
* @since 0.3.1
* @param initFile an input stream to the configuration file
* @exception ConfigureFailure if the method encountered a read or
* syntax error.
**/
static void configure(std::istream& initFile) throw (ConfigureFailure); };
}
#endif
|
zzengine
|
trunk/TinyLog/include/log4cpp/SimpleConfigurator.hh
|
C++
|
gpl3
| 1,740
|
/*
* Configurator.hh
*
* Copyright 2001, Glen Scott. All rights reserved.
*
* See the COPYING file for the terms of usage and distribution.
*/
#ifndef _LOG4CPP_CONFIGURATOR_HH
#define _LOG4CPP_CONFIGURATOR_HH
#include <log4cpp/Portability.hh>
#include <log4cpp/Export.hh>
#include <string>
#include <stdexcept>
namespace log4cpp {
/**
* Exception class for configuration.
*/
class LOG4CPP_EXPORT ConfigureFailure : public std::runtime_error {
public:
/**
* Constructor.
* @param reason String containing the description of the exception.
*/
ConfigureFailure(const std::string& reason);
};
}
#endif // _LOG4CPP_CONFIGURATOR_HH
|
zzengine
|
trunk/TinyLog/include/log4cpp/Configurator.hh
|
C++
|
gpl3
| 709
|
/*
* BasicLayout.hh
*
* Copyright 2000, LifeLine Networks BV (www.lifeline.nl). All rights reserved.
* Copyright 2000, Bastiaan Bakker. All rights reserved.
*
* See the COPYING file for the terms of usage and distribution.
*/
#ifndef _LOG4CPP_BASICLAYOUT_HH
#define _LOG4CPP_BASICLAYOUT_HH
#include <log4cpp/Portability.hh>
#include <log4cpp/Layout.hh>
namespace log4cpp {
/**
* BasicLayout is a simple fixed format Layout implementation.
**/
class LOG4CPP_EXPORT BasicLayout : public Layout {
public:
BasicLayout();
virtual ~BasicLayout();
/**
* Formats the LoggingEvent in BasicLayout style:<br>
* "timeStamp priority category ndc: message"
**/
virtual std::string format(const LoggingEvent& event);
};
}
#endif // _LOG4CPP_BASICLAYOUT_HH
|
zzengine
|
trunk/TinyLog/include/log4cpp/BasicLayout.hh
|
C++
|
gpl3
| 852
|
/*
* Appender.hh
*
* Copyright 2000, LifeLine Networks BV (www.lifeline.nl). All rights reserved.
* Copyright 2000, Bastiaan Bakker. All rights reserved.
*
* See the COPYING file for the terms of usage and distribution.
*/
#ifndef _LOG4CPP_APPENDER_HH
#define _LOG4CPP_APPENDER_HH
#include <log4cpp/Portability.hh>
#include <string>
#include <map>
#include <set>
#include <stdarg.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <log4cpp/Priority.hh>
#include <log4cpp/Layout.hh>
#include <log4cpp/LoggingEvent.hh>
#include <log4cpp/threading/Threading.hh>
namespace log4cpp {
class LOG4CPP_EXPORT Filter;
/**
* Implement this interface for your own strategies for printing log
* statements.
**/
class LOG4CPP_EXPORT Appender {
public:
/**
* Get a pointer to an exitsing Appender.
* @param name The name of the Appender to return.
* @returns a pointer to an existing Appender, or NULL if no appender
* with the specfied name exists.
**/
static Appender* getAppender(const std::string& name);
/**
* Call reopen() on all existing Appenders.
* @returns true if all Appenders returned true on their reopen() call.
**/
static bool reopenAll();
/**
* Call reopen() on all existing Appenders.
* @returns true if all Appenders returned true on their reopen() call.
**/
static void closeAll();
protected:
/**
* Constructor for Appender. Will only be used in getAppender() (and
* in derived classes of course).
* @param name The name of this Appender.
**/
Appender(const std::string& name);
public:
/**
* Destructor for Appender.
**/
virtual ~Appender();
/**
* Log in Appender specific way.
* @param event The LoggingEvent to log.
**/
virtual void doAppend(const LoggingEvent& event) = 0;
/**
* Reopens the output destination of this Appender, e.g. the logfile
* or TCP socket.
* @returns false if an error occured during reopening, true otherwise.
**/
virtual bool reopen() = 0;
/**
* Release any resources allocated within the appender such as file
* handles, network connections, etc.
**/
virtual void close() = 0;
/**
* Check if the appender uses a layout.
*
* @returns true if the appender implementation requires a layout.
**/
virtual bool requiresLayout() const = 0;
/**
* Set the Layout for this appender.
* @param layout The layout to use.
**/
virtual void setLayout(Layout* layout) = 0;
/**
* Get the name of this appender. The name identifies the appender.
* @returns the name of the appender.
**/
inline const std::string& getName() const { return _name; };
/**
* Set the threshold priority of this Appender. The Appender will not
* appender LoggingEvents with a priority lower than the threshold.
* Use Priority::NOTSET to disable threshold checking.
* @param priority The priority to set.
**/
virtual void setThreshold(Priority::Value priority) = 0;
/**
* Get the threshold priority of this Appender.
* @returns the threshold
**/
virtual Priority::Value getThreshold() = 0;
/**
* Set a Filter for this appender.
**/
virtual void setFilter(Filter* filter) = 0;
/**
* Get the Filter for this appender.
* @returns the filter, or NULL if no filter has been set.
**/
virtual Filter* getFilter() = 0;
private:
typedef std::map<std::string, Appender*> AppenderMap;
static AppenderMap* _allAppenders;
static threading::Mutex _appenderMapMutex;
static AppenderMap& _getAllAppenders();
static void _deleteAllAppenders();
static void _addAppender(Appender* appender);
static void _removeAppender(Appender* appender);
const std::string _name;
};
typedef std::set<Appender *> AppenderSet;
}
#endif // _LOG4CPP_APPENDER_HH
|
zzengine
|
trunk/TinyLog/include/log4cpp/Appender.hh
|
C++
|
gpl3
| 4,536
|
/*
* FixedContextCategory.hh
*
* Copyright 2001, LifeLine Networks BV (www.lifeline.nl). All rights reserved.
* Copyright 2001, Bastiaan Bakker. All rights reserved.
*
* See the COPYING file for the terms of usage and distribution.
*/
#ifndef _LOG4CPP_FIXEDCONTEXTCATEGORY_HH
#define _LOG4CPP_FIXEDCONTEXTCATEGORY_HH
#include <log4cpp/Portability.hh>
#include <log4cpp/Category.hh>
namespace log4cpp {
/**
* This Category subclass replaces the NDC field in LoggingEvents with
* a fixed context string. All handling of Appenders, etc. is delgated
* to the 'normal' Category with the same name. Its intended use is
* for object instances that serve a single client: they contruct a
* FixedContextCategory with the client identifier as context.
* Unlike with regular Category instances one has to explicitly create
* FixedContextCategory instances using the constructor. This also
* implies one has to take cake of destruction of the instance as well.
* @since 0.2.4
**/
class LOG4CPP_EXPORT FixedContextCategory : public Category {
public:
/**
* Constructor
* @param name the fully qualified name of this Categories delegate
* Category.
* @param context the context to fill the NDC field of LoggingEvents
* with.
**/
FixedContextCategory(const std::string& name,
const std::string& context = "");
/**
* Destructor for Category.
**/
virtual ~FixedContextCategory();
/**
* Set the context string used as NDC.
* @param context the context string
**/
virtual void setContext(const std::string& context);
/**
* Return the context string used as NDC.
* @return the context string.
**/
virtual std::string getContext() const;
/**
* Returns the assigned Priority, if any, for this Category.
* @return Priority - the assigned Priority, can be Priority::NOTSET
**/
virtual Priority::Value getPriority() const throw();
/**
* Starting from this Category, search the category hierarchy for a
* set priority and return it. Otherwise, return the priority
* of the root category.
*
* <p>The Category class is designed so that this method executes as
* quickly as possible.
**/
virtual Priority::Value getChainedPriority() const throw();
/**
* For the moment this method does nothing.
**/
virtual void addAppender(Appender* appender) throw();
/**
* For the moment this method does nothing.
**/
virtual void addAppender(Appender& appender);
/**
* Returns the Appender for this Category, or NULL if no Appender has
* been set.
* @returns The Appender.
**/
virtual Appender* getAppender() const;
/**
* Returns the specified Appender for this Category, or NULL if
* the Appender is not attached to this Category.
* @since 0.2.7
* @returns The Appender.
**/
virtual Appender* getAppender(const std::string& name) const;
/**
* Returns the set of Appenders currently attached to this Catogory.
* @since 0.3.1
* @returns The set of attached Appenders.
**/
virtual AppenderSet getAllAppenders() const;
/**
* Removes all appenders set for this Category. Currently a Category
* can have only one appender, but this may change in the future.
**/
virtual void removeAllAppenders();
/**
* FixedContextAppenders cannot own Appenders.
* @returns false
**/
virtual bool ownsAppender() const throw();
/**
* FixedContextAppenders cannot own Appenders.
* @returns false
**/
virtual bool ownsAppender(Appender* appender)
const throw();
/**
* Call the appenders in the hierarchy starting at
* <code>this</code>. If no appenders could be found, emit a
* warning.
*
* <p>This method always calls all the appenders inherited form the
* hierracy circumventing any evaluation of whether to log or not to
* log the particular log request.
*
* @param event The LoggingEvent to log.
**/
virtual void callAppenders(const LoggingEvent& event) throw();
/**
* Set the additivity flag for this Category instance.
**/
virtual void setAdditivity(bool additivity);
/**
* Returns the additivity flag for this Category instance.
**/
virtual bool getAdditivity() const throw();
protected:
/**
* Unconditionally log a message with the specified priority.
* @param priority The priority of this log message.
* @param message string to write in the log file
**/
virtual void _logUnconditionally2(Priority::Value priority,
const std::string& message) throw();
private:
/**
* The delegate category of this FixedContextCategory.
**/
Category& _delegate;
/** The context of this FixedContextCategory. */
std::string _context;
};
}
#endif // _LOG4CPP_FIXEDCONTEXTCATEGORY_HH
|
zzengine
|
trunk/TinyLog/include/log4cpp/FixedContextCategory.hh
|
C++
|
gpl3
| 5,632
|
/*
* Layout.hh
*
* Copyright 2000, LifeLine Networks BV (www.lifeline.nl). All rights reserved.
* Copyright 2000, Bastiaan Bakker. All rights reserved.
*
* See the COPYING file for the terms of usage and distribution.
*/
#ifndef _LOG4CPP_LAYOUT_HH
#define _LOG4CPP_LAYOUT_HH
#include <log4cpp/Portability.hh>
#include <log4cpp/LoggingEvent.hh>
#include <string>
namespace log4cpp {
/**
* Extend this abstract class to create your own log layout format.
**/
class LOG4CPP_EXPORT Layout {
public:
/**
* Destructor for Layout.
**/
virtual ~Layout() { };
/**
* Formats the LoggingEvent data to a string that appenders can log.
* Implement this method to create your own layout format.
* @param event The LoggingEvent.
* @returns an appendable string.
**/
virtual std::string format(const LoggingEvent& event) = 0;
};
}
#endif // _LOG4CPP_LAYOUT_HH
|
zzengine
|
trunk/TinyLog/include/log4cpp/Layout.hh
|
C++
|
gpl3
| 978
|
SUBDIRS = threading
liblog4cppincludedir = $(includedir)/log4cpp
liblog4cppinclude_HEADERS = \
Appender.hh \
AppenderSkeleton.hh \
FixedContextCategory.hh \
LayoutAppender.hh \
FileAppender.hh \
RollingFileAppender.hh \
IdsaAppender.hh \
OstreamAppender.hh \
StringQueueAppender.hh \
SyslogAppender.hh \
RemoteSyslogAppender.hh \
Layout.hh \
SimpleLayout.hh \
BasicLayout.hh \
PatternLayout.hh \
Category.hh \
CategoryStream.hh \
HierarchyMaintainer.hh \
Configurator.hh \
BasicConfigurator.hh \
SimpleConfigurator.hh \
PropertyConfigurator.hh \
LoggingEvent.hh \
Priority.hh \
NDC.hh \
TimeStamp.hh \
Filter.hh \
Export.hh \
Portability.hh \
Win32DebugAppender.hh \
NTEventLogAppender.hh \
AbortAppender.hh \
Manipulator.hh \
config.h \
config-win32.h \
config-openvms.h
dist-hook:
$(RM) -f $(distdir)/config.h
distclean-local:
$(RM) config.h
|
zzengine
|
trunk/TinyLog/include/log4cpp/Makefile.am
|
Makefile
|
gpl3
| 886
|
/*
* NDC.hh
*
* Copyright 2000, LifeLine Networks BV (www.lifeline.nl). All rights reserved.
* Copyright 2000, Bastiaan Bakker. All rights reserved.
*
* See the COPYING file for the terms of usage and distribution.
*/
#ifndef _LOG4CPP_NDC_HH
#define _LOG4CPP_NDC_HH
#include <log4cpp/Portability.hh>
#include <string>
#include <vector>
namespace log4cpp {
/**
The NDC class implements <i>nested diagnostic contexts</i> as
defined by Neil Harrison in the article "Patterns for Logging
Diagnostic Messages" part of the book "<i>Pattern Languages of
Program Design 3</i>" edited by Martin et al.
<p>A Nested Diagnostic Context, or NDC in short, is an instrument
to distinguish interleaved log output from different sources. Log
output is typically interleaved when a server handles multiple
clients near-simulatanously.
<p>Interleaved log output can still be meaningful if each log entry
from different contexts had a distinctive stamp. This is where NDCs
come into play.
<p><em><b>Note that NDCs are managed on a per thread
basis</b></em>. NDC operations such as <code>push</code>, <code>
pop</code>, <code>clear</code>, <code>getDepth</code> and <code>
setMaxDepth</code> affect the NDC of the <em>current</em> thread only.
NDCs of other threads remain unaffected.
<p>To build an NDC one uses the <code>push</code> operation.
Simply put,
<p><ul>
<li>Contexts can be nested.
<p><li>When entering a context, call <code>NDC.push</code>. As a
side effect, if there is no nested diagnostic context for the
current thread, this method will create it.
<p><li>When leaving a context, call <code>NDC.pop</code>.
</ul>
<p>There is no penalty for forgetting to match each
<code>push</code> operation with a corresponding <code>pop</code>,
except the obvious mismatch between the real application context
and the context set in the NDC.
<p>Custom Layouts may include the nested diagnostic context for the
current thread in log messages, without any user intervention.
Hence, even if a server is serving multiple clients
simultaneously, the logs emanating from the same code (belonging to
the same category) can still be distinguished because each client
request will have a different NDC tag.
<p><em>Unfortunately, unlike Java, C++ does not have platform
independent multithreading support. Therefore, currently log4cpp is
not multithread aware, it implicitly assumes only one thread exists,
the main process thread. </em>
**/
class LOG4CPP_EXPORT NDC {
public:
struct DiagnosticContext {
DiagnosticContext(const std::string& message);
DiagnosticContext(const std::string& message,
const DiagnosticContext& parent);
std::string message;
std::string fullMessage;
};
typedef std::vector<DiagnosticContext> ContextStack;
/**
Clear any nested disgnostic information if any. This method is
useful in cases where the same thread can be potentially used
over and over in different unrelated contexts.
<p>This method is equivalent to calling the <code>setMaxDepth</code>
method with a zero <code>maxDepth</code> argument.
**/
static void clear();
/**
Clone the diagnostic context for the current thread.
<p>Internally a diagnostic context is represented as a stack. A
given thread can supply the stack (i.e. diagnostic context) to a
child thread so that the child can inherit the parent thread's
diagnostic context.
<p>The child thread uses the <code>inherit</code> method to
inherit the parent's diagnostic context.
@return Stack A clone of the current thread's diagnostic context.
**/
static ContextStack* cloneStack();
/**
Get the current diagnostic context string.
@return the context string.
**/
static const std::string& get();
/**
Get the current nesting depth of this diagnostic context.
@return the nesting depth
**/
static size_t getDepth();
static void inherit(ContextStack* stack);
/**
Clients should call this method before leaving a diagnostic
context.
<p>The returned value is the value that was pushed last. If no
context is available, then the empty string "" is returned.
@return String The innermost diagnostic context.
**/
static std::string pop();
/**
Push new diagnostic context information for the current thread.
<p>The contents of the <code>message</code> parameter is
determined solely by the client.
@param message The new diagnostic context information.
**/
static void push(const std::string& message);
/**
Set the maximum nesting depth for the current NDC. Curently NDCs
do not enforce a maximum depth and consequentially this method
has no effect.
@param maxDepth the maximum nesting depth
**/
static void setMaxDepth(int maxDepth);
/**
Return the NDC for the current thread.
@return the NDC for the current thread
**/
static NDC& getNDC();
NDC();
virtual ~NDC();
public:
virtual void _clear();
virtual ContextStack* _cloneStack();
virtual const std::string& _get() const;
virtual size_t _getDepth() const;
virtual void _inherit(ContextStack* stack);
virtual std::string _pop();
virtual void _push(const std::string& message);
virtual void _setMaxDepth(int maxDepth);
ContextStack _stack;
};
}
#endif // _LOG4CPP_NDC_HH
|
zzengine
|
trunk/TinyLog/include/log4cpp/NDC.hh
|
C++
|
gpl3
| 6,280
|
/*
* Priority.hh
*
* Copyright 2000, LifeLine Networks BV (www.lifeline.nl). All rights reserved.
* Copyright 2000, Bastiaan Bakker. All rights reserved.
*
* See the COPYING file for the terms of usage and distribution.
*/
#ifndef _LOG4CPP_PRIORITY_HH
#define _LOG4CPP_PRIORITY_HH
#include <log4cpp/Portability.hh>
#include <string>
#include <stdexcept>
/*
* Optionally work around rudeness in windows.h on Win32.
*/
#ifdef ERROR
#ifdef LOG4CPP_FIX_ERROR_COLLISION
namespace log4cpp {
static const int _tmpERRORValue = ERROR;
}
#undef ERROR
static const int ERROR = log4cpp::_tmpERRORValue;
#define ERROR ERROR
#else // LOG4CPP_FIX_ERROR_COLLISION
#error Naming collision for 'ERROR' detected. Please read the FAQ for a \
workaround.
#endif // LOG4CPP_FIX_ERROR_COLLISION
#endif // ERROR
/*
* Other Win32 rudeness in EDK.h
*/
#ifdef DEBUG
#ifdef LOG4CPP_FIX_ERROR_COLLISION
#undef DEBUG
#define DEBUG DEBUG
#else // LOG4CPP_FIX_ERROR_COLLISION
#error Naming collision for 'DEBUG' detected. Please read the FAQ for a \
workaround.
#endif // LOG4CPP_FIX_ERROR_COLLISION
#endif // DEBUG
namespace log4cpp {
/**
* The Priority class provides importance levels with which one
* can categorize log messages.
**/
class LOG4CPP_EXPORT Priority {
public:
static const int MESSAGE_SIZE = 8;
/**
* Predefined Levels of Priorities. These correspond to the
* priority levels used by syslog(3).
**/
typedef enum {EMERG = 0,
FATAL = 0,
ALERT = 100,
CRIT = 200,
ERROR = 300,
WARN = 400,
NOTICE = 500,
INFO = 600,
DEBUG = 700,
NOTSET = 800
} PriorityLevel;
/**
* The type of Priority Values
**/
typedef int Value;
/**
* Returns the name of the given priority value.
* Currently, if the value is not one of the PriorityLevel values,
* the method returns the name of the largest priority smaller
* the given value.
* @param priority the numeric value of the priority.
* @returns a string representing the name of the priority.
**/
static const std::string& getPriorityName(int priority) throw();
/**
* Returns the value of the given priority name.
* This can be either one of EMERG ... NOTSET or a
* decimal string representation of the value, e.g. '700' for DEBUG.
* @param priorityName the string containing the the of the priority
* @return the value corresponding with the priority name
* @throw std::invalid_argument if the priorityName does not
* correspond with a known Priority name or a number
**/
static Value getPriorityValue(const std::string& priorityName)
throw(std::invalid_argument);
};
}
#endif // _LOG4CPP_PRIORITY_HH
|
zzengine
|
trunk/TinyLog/include/log4cpp/Priority.hh
|
C++
|
gpl3
| 3,006
|
/*
* LayoutAppender.hh
*
* Copyright 2000, LifeLine Networks BV (www.lifeline.nl). All rights reserved.
* Copyright 2000, Bastiaan Bakker. All rights reserved.
*
* See the COPYING file for the terms of usage and distribution.
*/
#ifndef _LOG4CPP_LAYOUTAPPENDER_HH
#define _LOG4CPP_LAYOUTAPPENDER_HH
#include <string>
#include <log4cpp/Portability.hh>
#include <log4cpp/AppenderSkeleton.hh>
#include <log4cpp/BasicLayout.hh>
namespace log4cpp {
/**
* LayoutAppender is a common superclass for all Appenders that require
* a Layout.
**/
class LOG4CPP_EXPORT LayoutAppender : public AppenderSkeleton {
public:
typedef BasicLayout DefaultLayoutType;
LayoutAppender(const std::string& name);
virtual ~LayoutAppender();
/**
* Check if the appender requires a layout. All LayoutAppenders do,
* therefore this method returns true for all subclasses.
*
* @returns true.
**/
virtual bool requiresLayout() const;
virtual void setLayout(Layout* layout = NULL);
protected:
/**
* Return the layout of the appender.
* This method is the Layout accessor for subclasses of LayoutAppender.
* @returns the Layout.
**/
Layout& _getLayout();
private:
Layout* _layout;
};
}
#endif // _LOG4CPP_LAYOUTAPPENDER_HH
|
zzengine
|
trunk/TinyLog/include/log4cpp/LayoutAppender.hh
|
C++
|
gpl3
| 1,421
|
/*
* PatternLayout.hh
*
* Copyright 2002, Bastiaan Bakker. All rights reserved.
*
* See the COPYING file for the terms of usage and distribution.
*/
#ifndef _LOG4CPP_PATTERNLAYOUT_HH
#define _LOG4CPP_PATTERNLAYOUT_HH
#include <log4cpp/Portability.hh>
#include <log4cpp/Layout.hh>
#include <log4cpp/Configurator.hh>
#include <vector>
#ifdef LOG4CPP_HAVE_SSTREAM
#include <sstream>
#endif
namespace log4cpp {
/**
* PatternLayout is a simple fixed format Layout implementation.
**/
class LOG4CPP_EXPORT PatternLayout : public Layout {
public:
/**
The default conversion pattern
**/
static const char* DEFAULT_CONVERSION_PATTERN;
/**
A conversion pattern equivalent to the SimpleLayout.
**/
static const char* SIMPLE_CONVERSION_PATTERN;
/**
A conversion pattern equivalent to the BasicLayout.
**/
static const char* BASIC_CONVERSION_PATTERN;
/**
A conversion pattern equivalent to the TTCCLayout.
Note: TTCCLayout is in log4j but not log4cpp.
**/
static const char* TTCC_CONVERSION_PATTERN;
PatternLayout();
virtual ~PatternLayout();
// NOTE: All double percentage signs ('%%') followed by a character
// in the following comments should actually be a single char.
// The doubles are included so that doxygen will print them correctly.
/**
* Formats the LoggingEvent in the style set by
* the setConversionPattern call. By default, set
* to "%%m%%n"
**/
virtual std::string format(const LoggingEvent& event);
/**
* Sets the format of log lines handled by this
* PatternLayout. By default, set to "%%m%%n".<br>
* Format characters are as follows:<br>
* <li><b>%%</b> - a single percent sign</li>
* <li><b>%%c</b> - the category</li>
* <li><b>%%d</b> - the date\n
* Date format: The date format character may be followed by a date format
* specifier enclosed between braces. For example, %%d{%%H:%%M:%%S,%%l} or %%d{%%d %%m %%Y %%H:%%M:%%S,%%l}.
* If no date format specifier is given then the following format is used:
* "Wed Jan 02 02:03:55 1980". The date format specifier admits the same syntax
* as the ANSI C function strftime, with 1 addition. The addition is the specifier
* %%l for milliseconds, padded with zeros to make 3 digits.</li>
* <li><b>%%m</b> - the message</li>
* <li><b>%%n</b> - the platform specific line separator</li>
* <li><b>%%p</b> - the priority</li>
* <li><b>%%r</b> - milliseconds since this layout was created.</li>
* <li><b>%%R</b> - seconds since Jan 1, 1970</li>
* <li><b>%%u</b> - clock ticks since process start</li>
* <li><b>%%x</b> - the NDC</li>
* @param conversionPattern the conversion pattern
* @exception ConfigureFailure if the pattern is invalid
**/
virtual void setConversionPattern(const std::string& conversionPattern)
throw(ConfigureFailure);
virtual std::string getConversionPattern() const;
virtual void clearConversionPattern();
class LOG4CPP_EXPORT PatternComponent {
public:
inline virtual ~PatternComponent() {};
virtual void append(std::ostringstream& out, const LoggingEvent& event) = 0;
};
private:
typedef std::vector<PatternComponent*> ComponentVector;
ComponentVector _components;
std::string _conversionPattern;
};
}
#endif // _LOG4CPP_PATTERNLAYOUT_HH
|
zzengine
|
trunk/TinyLog/include/log4cpp/PatternLayout.hh
|
C++
|
gpl3
| 3,768
|
/*
* Category.hh
*
* Copyright 2000, LifeLine Networks BV (www.lifeline.nl). All rights reserved.
* Copyright 2000, Bastiaan Bakker. All rights reserved.
*
* See the COPYING file for the terms of usage and distribution.
*/
#ifndef _LOG4CPP_CATEGORY_HH
#define _LOG4CPP_CATEGORY_HH
#include <log4cpp/Portability.hh>
#include <log4cpp/Appender.hh>
#include <log4cpp/LoggingEvent.hh>
#include <log4cpp/Priority.hh>
#include <log4cpp/CategoryStream.hh>
#include <log4cpp/threading/Threading.hh>
#include <map>
#include <vector>
#include <cstdarg>
#include <stdexcept>
namespace log4cpp {
/**
* This is the central class in the log4j package. One of the distintive
* features of log4j (and hence log4cpp) are hierarchal categories and
* their evaluation.
**/
class LOG4CPP_EXPORT Category {
friend class HierarchyMaintainer;
public:
/**
* Return the root of the Category hierarchy.
*
* <p>The root category is always instantiated and available. It's
* name is the empty string.
* <p>Unlike in log4j, calling <code>Category.getInstance("")</code>
* <em>does</em> retrieve the root category
* and not a category just under root named "".
* @returns The root category
**/
static Category& getRoot();
/**
* Set the priority of the root Category.
* @param priority The new priority for the root Category
**/
static void setRootPriority(Priority::Value priority);
/**
* Get the priority of the <code>root</code> Category.
* @returns the priority of the root category
**/
static Priority::Value getRootPriority() throw();
/**
* Instantiate a Category with name <code>name</code>. This
* method does not set priority of the category which is by
* default <code>Priority::NOTSET</code>.
*
* @param name The name of the category to retrieve.
**/
static Category& getInstance(const std::string& name);
/**
* If the named category exists (in the default hierarchy) then it
* returns a reference to the category, otherwise it returns NULL.
* @since 0.2.7
**/
static Category* exists(const std::string& name);
/**
* Returns all the currently defined categories as a vector of
* Category pointers. Note: this function does not pass ownership
* of the categories in the vector to the caller, only the ownership
* of the vector. However vector<Category&>* is not legal C++,
* so we can't follow the default ownership conventions.
*
* <p>Unlike in log4j, the root category <em>is</em> included
* in the returned set.
*
* @since 0.3.2. Before 0.3.2 this method returned a std::set
**/
static std::vector<Category*>* getCurrentCategories();
/**
* This method will remove all Appenders from Categories.XXX
**/
static void shutdown();
/**
* Destructor for Category.
**/
virtual ~Category();
/**
* Return the category name.
* @returns The category name.
*/
virtual const std::string& getName() const throw();
/**
* Set the priority of this Category.
* @param priority The priority to set. Use Priority::NOTSET to let
* the category use its parents priority as effective priority.
* @exception std::invalid_argument if the caller tries to set
* Priority::NOTSET on the Root Category.
**/
virtual void setPriority(Priority::Value priority)
throw(std::invalid_argument);
/**
* Returns the assigned Priority, if any, for this Category.
* @return Priority - the assigned Priority, can be Priority::NOTSET
**/
virtual Priority::Value getPriority() const throw();
/**
* Starting from this Category, search the category hierarchy for a
* set priority and return it. Otherwise, return the priority
* of the root category.
*
* <p>The Category class is designed so that this method executes as
* quickly as possible.
**/
virtual Priority::Value getChainedPriority() const throw();
/**
* Returns true if the chained priority of the Category is equal to
* or higher than given priority.
* @param priority The priority to compare with.
* @returns whether logging is enable for this priority.
**/
virtual bool isPriorityEnabled(Priority::Value priority) const throw();
/**
* Adds an Appender to this Category.
* This method passes ownership from the caller to the Category.
* @since 0.2.7
* @param appender The Appender to wich this category has to log.
* @exception std::invalid_argument if the appender is NULL.
**/
virtual void addAppender(Appender* appender)
throw(std::invalid_argument);
/**
* Adds an Appender for this Category.
* This method does not pass ownership from the caller to the Category.
* @since 0.2.7
* @param appender The Appender this category has to log to.
**/
virtual void addAppender(Appender& appender);
/**
* Adds an Appender to this Category.
* This method passes ownership from the caller to the Category.
* @deprecated use addAppender(Appender*) or removeAllAppenders()
* instead.
* @param appender The Appender this category has to log to or NULL
* to remove the current Appenders.
**/
inline void setAppender(Appender* appender) {
if (appender) {
addAppender(appender);
} else {
removeAllAppenders();
}
};
/**
* Adds an Appender for this Category.
* This method does not pass ownership from the caller to the Category.
* @deprecated use addAppender(Appender&) instead.
* @param appender The Appender this category has to log to.
**/
inline void setAppender(Appender& appender) {
addAppender(appender);
};
/**
* Returns the first Appender for this Category, or NULL if no
* Appender has been set.
* @deprecated use getAppender(const std::string&)
* @returns The Appender.
**/
virtual Appender* getAppender() const;
/**
* Returns the specified Appender for this Category, or NULL if
* the Appender is not attached to this Category.
* @since 0.2.7
* @returns The Appender.
**/
virtual Appender* getAppender(const std::string& name) const;
/**
* Returns the set of Appenders currently attached to this Catogory.
* @since 0.3.1
* @returns The set of attached Appenders.
**/
virtual AppenderSet getAllAppenders() const;
/**
* Removes all appenders for this Category.
**/
virtual void removeAllAppenders();
/**
* Removes specified appender for this Category.
* @since 0.2.7
**/
virtual void removeAppender(Appender* appender);
/**
* Returns true if the Category owns the first Appender in its
* Appender set. In that case the Category destructor will delete
* the Appender.
* @deprecated use ownsAppender(Appender*)
**/
inline bool ownsAppender() const throw() {
return ownsAppender(getAppender());
};
/**
* Returns true if the Category owns the Appender. In that case the
* Category destructor will delete the Appender.
* @since 0.2.7
**/
virtual bool ownsAppender(Appender* appender) const throw();
/**
* Call the appenders in the hierarchy starting at
* <code>this</code>. If no appenders could be found, emit a
* warning.
*
* <p>This method always calls all the appenders inherited form the
* hierracy circumventing any evaluation of whether to log or not to
* log the particular log request.
*
* @param event the LogginEvent to log.
**/
virtual void callAppenders(const LoggingEvent& event) throw();
/**
* Set the additivity flag for this Category instance.
**/
virtual void setAdditivity(bool additivity);
/**
* Returns the additivity flag for this Category instance.
**/
virtual bool getAdditivity() const throw();
/**
* Returns the parent category of this category, or NULL
* if the category is the root category.
* @return the parent category.
**/
virtual Category* getParent() throw();
/**
* Returns the parent category of this category, or NULL
* if the category is the root category.
* @return the parent category.
**/
virtual const Category* getParent() const throw();
/**
* Log a message with the specified priority.
* @param priority The priority of this log message.
* @param stringFormat Format specifier for the string to write
* in the log file.
* @param ... The arguments for stringFormat
**/
virtual void log(Priority::Value priority, const char* stringFormat,
...) throw();
/**
* Log a message with the specified priority.
* @param priority The priority of this log message.
* @param message string to write in the log file
**/
virtual void log(Priority::Value priority,
const std::string& message) throw();
/**
* Log a message with the specified priority.
* @since 0.2.7
* @param priority The priority of this log message.
* @param stringFormat Format specifier for the string to write
* in the log file.
* @param va The arguments for stringFormat.
**/
virtual void logva(Priority::Value priority,
const char* stringFormat,
va_list va) throw();
/**
* Log a message with debug priority.
* @param stringFormat Format specifier for the string to write
* in the log file.
* @param ... The arguments for stringFormat
**/
void debug(const char* stringFormat, ...) throw();
/**
* Log a message with debug priority.
* @param message string to write in the log file
**/
void debug(const std::string& message) throw();
/**
* Return true if the Category will log messages with priority DEBUG.
* @returns Whether the Category will log.
**/
inline bool isDebugEnabled() const throw() {
return isPriorityEnabled(Priority::DEBUG);
};
/**
* Return a CategoryStream with priority DEBUG.
* @returns The CategoryStream.
**/
inline CategoryStream debugStream() {
return getStream(Priority::DEBUG);
}
/**
* Log a message with info priority.
* @param stringFormat Format specifier for the string to write
* in the log file.
* @param ... The arguments for stringFormat
**/
void info(const char* stringFormat, ...) throw();
/**
* Log a message with info priority.
* @param message string to write in the log file
**/
void info(const std::string& message) throw();
/**
* Return true if the Category will log messages with priority INFO.
* @returns Whether the Category will log.
**/
inline bool isInfoEnabled() const throw() {
return isPriorityEnabled(Priority::INFO);
};
/**
* Return a CategoryStream with priority INFO.
* @returns The CategoryStream.
**/
inline CategoryStream infoStream() {
return getStream(Priority::INFO);
}
/**
* Log a message with notice priority.
* @param stringFormat Format specifier for the string to write
* in the log file.
* @param ... The arguments for stringFormat
**/
void notice(const char* stringFormat, ...) throw();
/**
* Log a message with notice priority.
* @param message string to write in the log file
**/
void notice(const std::string& message) throw();
/**
* Return true if the Category will log messages with priority NOTICE.
* @returns Whether the Category will log.
**/
inline bool isNoticeEnabled() const throw() {
return isPriorityEnabled(Priority::NOTICE);
};
/**
* Return a CategoryStream with priority NOTICE.
* @returns The CategoryStream.
**/
inline CategoryStream noticeStream() {
return getStream(Priority::NOTICE);
}
/**
* Log a message with warn priority.
* @param stringFormat Format specifier for the string to write
* in the log file.
* @param ... The arguments for stringFormat
**/
void warn(const char* stringFormat, ...) throw();
/**
* Log a message with warn priority.
* @param message string to write in the log file
**/
void warn(const std::string& message) throw();
/**
* Return true if the Category will log messages with priority WARN.
* @returns Whether the Category will log.
**/
inline bool isWarnEnabled() const throw() {
return isPriorityEnabled(Priority::WARN);
};
/**
* Return a CategoryStream with priority WARN.
* @returns The CategoryStream.
**/
inline CategoryStream warnStream() {
return getStream(Priority::WARN);
};
/**
* Log a message with error priority.
* @param stringFormat Format specifier for the string to write
* in the log file.
* @param ... The arguments for stringFormat
**/
void error(const char* stringFormat, ...) throw();
/**
* Log a message with error priority.
* @param message string to write in the log file
**/
void error(const std::string& message) throw();
/**
* Return true if the Category will log messages with priority ERROR.
* @returns Whether the Category will log.
**/
inline bool isErrorEnabled() const throw() {
return isPriorityEnabled(Priority::ERROR);
};
/**
* Return a CategoryStream with priority ERROR.
* @returns The CategoryStream.
**/
inline CategoryStream errorStream() {
return getStream(Priority::ERROR);
};
/**
* Log a message with crit priority.
* @param stringFormat Format specifier for the string to write
* in the log file.
* @param ... The arguments for stringFormat
**/
void crit(const char* stringFormat, ...) throw();
/**
* Log a message with crit priority.
* @param message string to write in the log file
**/
void crit(const std::string& message) throw();
/**
* Return true if the Category will log messages with priority CRIT.
* @returns Whether the Category will log.
**/
inline bool isCritEnabled() const throw() {
return isPriorityEnabled(Priority::CRIT);
};
/**
* Return a CategoryStream with priority CRIT.
* @returns The CategoryStream.
**/
inline CategoryStream critStream() {
return getStream(Priority::CRIT);
};
/**
* Log a message with alert priority.
* @param stringFormat Format specifier for the string to write
* in the log file.
* @param ... The arguments for stringFormat
**/
void alert(const char* stringFormat, ...) throw();
/**
* Log a message with alert priority.
* @param message string to write in the log file
**/
void alert(const std::string& message) throw();
/**
* Return true if the Category will log messages with priority ALERT.
* @returns Whether the Category will log.
**/
inline bool isAlertEnabled() const throw() {
return isPriorityEnabled(Priority::ALERT);
};
/**
* Return a CategoryStream with priority ALERT.
* @returns The CategoryStream.
**/
inline CategoryStream alertStream() throw() {
return getStream(Priority::ALERT);
};
/**
* Log a message with emerg priority.
* @param stringFormat Format specifier for the string to write
* in the log file.
* @param ... The arguments for stringFormat
**/
void emerg(const char* stringFormat, ...) throw();
/**
* Log a message with emerg priority.
* @param message string to write in the log file
**/
void emerg(const std::string& message) throw();
/**
* Return true if the Category will log messages with priority EMERG.
* @returns Whether the Category will log.
**/
inline bool isEmergEnabled() const throw() {
return isPriorityEnabled(Priority::EMERG);
};
/**
* Return a CategoryStream with priority EMERG.
* @returns The CategoryStream.
**/
inline CategoryStream emergStream() {
return getStream(Priority::EMERG);
};
/**
* Log a message with fatal priority.
* NB. priority 'fatal' is equivalent to 'emerg'.
* @since 0.2.7
* @param stringFormat Format specifier for the string to write
* in the log file.
* @param ... The arguments for stringFormat
**/
void fatal(const char* stringFormat, ...) throw();
/**
* Log a message with fatal priority.
* NB. priority 'fatal' is equivalent to 'emerg'.
* @since 0.2.7
* @param message string to write in the log file
**/
void fatal(const std::string& message) throw();
/**
* Return true if the Category will log messages with priority FATAL.
* NB. priority 'fatal' is equivalent to 'emerg'.
* @since 0.2.7
* @returns Whether the Category will log.
**/
inline bool isFatalEnabled() const throw() {
return isPriorityEnabled(Priority::FATAL);
};
/**
* Return a CategoryStream with priority FATAL.
* NB. priority 'fatal' is equivalent to 'emerg'.
* @since 0.2.7
* @returns The CategoryStream.
**/
inline CategoryStream fatalStream() {
return getStream(Priority::FATAL);
};
/**
* Return a CategoryStream with given Priority.
* @param priority The Priority of the CategoryStream.
* @returns The requested CategoryStream.
**/
virtual CategoryStream getStream(Priority::Value priority);
/**
* Return a CategoryStream with given Priority.
* @param priority The Priority of the CategoryStream.
* @returns The requested CategoryStream.
**/
virtual CategoryStream operator<<(Priority::Value priority);
protected:
/**
* Constructor
* @param name the fully qualified name of this Category
* @param parent the parent of this parent, or NULL for the root
* Category
* @param priority the priority for this Category. Defaults to
* Priority::NOTSET
**/
Category(const std::string& name, Category* parent,
Priority::Value priority = Priority::NOTSET);
virtual void _logUnconditionally(Priority::Value priority,
const char* format,
va_list arguments) throw();
/**
* Unconditionally log a message with the specified priority.
* @param priority The priority of this log message.
* @param message string to write in the log file
**/
virtual void _logUnconditionally2(Priority::Value priority,
const std::string& message) throw();
private:
/* prevent copying and assignment */
Category(const Category& other);
Category& operator=(const Category& other);
/** The name of this category. */
const std::string _name;
/**
* The parent of this category. All categories have al least one
* ancestor which is the root category.
**/
Category* _parent;
/**
* The assigned priority of this category.
**/
volatile Priority::Value _priority;
typedef std::map<Appender *, bool> OwnsAppenderMap;
/**
* Returns the iterator to the Appender if the Category owns the
* Appender. In that case the Category destructor will delete the
* Appender.
**/
virtual bool ownsAppender(Appender* appender,
OwnsAppenderMap::iterator& i2) throw();
AppenderSet _appender;
mutable threading::Mutex _appenderSetMutex;
/**
* Whether the category holds the ownership of the appender. If so,
* it deletes the appender in its destructor.
**/
OwnsAppenderMap _ownsAppender;
/**
* Additivity is set to true by default, i.e. a child inherits its
* ancestor's appenders by default.
*/
volatile bool _isAdditive;
};
}
#endif // _LOG4CPP_CATEGORY_HH
|
zzengine
|
trunk/TinyLog/include/log4cpp/Category.hh
|
C++
|
gpl3
| 22,914
|
/*
* SimpleConfigurator.hh
*
* Copyright 2001, Glen Scott. All rights reserved.
*
* See the COPYING file for the terms of usage and distribution.
*/
#ifndef _LOG4CPP_PROPERTYCONFIGURATOR_HH
#define _LOG4CPP_PROPERTYCONFIGURATOR_HH
#include <log4cpp/Portability.hh>
#include <log4cpp/Export.hh>
#include <string>
#include <log4cpp/Configurator.hh> // configure exceptions
namespace log4cpp {
/**
Property configurator will read a config file using the same (or similar)
format to the config file used by log4j. This file is in a standard Java
"properties" file format.
<P>Example:<BR>
<PRE>
# a simple test config
log4j.rootCategory=DEBUG, rootAppender
log4j.category.sub1=A1
log4j.category.sub2=INFO
log4j.category.sub1.sub2=ERROR, A2
log4j.appender.rootAppender=org.apache.log4j.ConsoleAppender
log4j.appender.rootAppender.layout=org.apache.log4j.BasicLayout
log4j.appender.A1=org.apache.log4j.FileAppender
log4j.appender.A1.fileName=A1.log
log4j.appender.A1.layout=org.apache.log4j.BasicLayout
log4j.appender.A2=org.apache.log4j.ConsoleAppender
log4j.appender.A2.layout=org.apache.log4j.PatternLayout
log4j.appender.A2.layout.ConversionPattern=The message %%m at time %%d%%n
</PRE>
@since 0.3.2
**/
class LOG4CPP_EXPORT PropertyConfigurator {
public:
static void configure(const std::string& initFileName) throw (ConfigureFailure);
};
}
#endif // _LOG4CPP_PROPERTYCONFIGURATOR_HH
|
zzengine
|
trunk/TinyLog/include/log4cpp/PropertyConfigurator.hh
|
C++
|
gpl3
| 1,598
|
#ifndef _LOG4CPP_EXPORT_HH
#define _LOG4CPP_EXPORT_HH
#ifdef LOG4CPP_HAS_DLL
# ifdef LOG4CPP_BUILD_DLL
# define LOG4CPP_EXPORT __declspec(dllexport)
# else
# define LOG4CPP_EXPORT __declspec(dllimport)
# endif
#else
# define LOG4CPP_EXPORT
#endif
#endif // _LOG4CPP_EXPORT_HH
|
zzengine
|
trunk/TinyLog/include/log4cpp/Export.hh
|
C++
|
gpl3
| 282
|
/*
* LoggingEvent.hh
*
* Copyright 2000, LifeLine Networks BV (www.lifeline.nl). All rights reserved.
* Copyright 2000, Bastiaan Bakker. All rights reserved.
*
* See the COPYING file for the terms of usage and distribution.
*/
#ifndef _LOG4CPP_LOGGINGEVENT_HH
#define _LOG4CPP_LOGGINGEVENT_HH
#include <log4cpp/Portability.hh>
#include <string>
#include <log4cpp/Priority.hh>
#include <log4cpp/TimeStamp.hh>
/**
* The top level namespace for all 'Log for C++' types and classes.
**/
namespace log4cpp {
/**
* The internal representation of logging events. When a affirmative
* logging decision is made a <code>LoggingEvent</code> instance is
* created. This instance is passed around the different log4cpp
* components.
*
* <p>This class is of concern to those wishing to extend log4cpp.
**/
struct LOG4CPP_EXPORT LoggingEvent {
public:
/**
* Instantiate a LoggingEvent from the supplied parameters.
*
* <p>Except <code>timeStamp</code> all the other fields of
* <code>LoggingEvent</code> are filled when actually needed.
* <p>
* @param category The category of this event.
* @param message The message of this event.
* @param ndc The nested diagnostic context of this event.
* @param priority The priority of this event.
**/
LoggingEvent(const std::string& category, const std::string& message,
const std::string& ndc, Priority::Value priority);
/** The category name. */
const std::string categoryName;
/** The application supplied message of logging event. */
const std::string message;
/** The nested diagnostic context (NDC) of logging event. */
const std::string ndc;
/** Priority of logging event. */
Priority::Value priority;
/** The name of thread in which this logging event was generated,
e.g. the PID.
*/
const std::string threadName;
/** The number of seconds elapsed since the epoch
(1/1/1970 00:00:00 UTC) until logging event was created. */
TimeStamp timeStamp;
};
}
#endif // _LOG4CPP_LOGGINGEVENT_HH
|
zzengine
|
trunk/TinyLog/include/log4cpp/LoggingEvent.hh
|
C++
|
gpl3
| 2,253
|
/*
* BasicConfigurator.hh
*
* Copyright 2002, Log4cpp Project. All rights reserved.
*
* See the COPYING file for the terms of usage and distribution.
*/
#ifndef _LOG4CPP_BASICCONFIGURATOR_HH
#define _LOG4CPP_BASICCONFIGURATOR_HH
#include <log4cpp/Portability.hh>
namespace log4cpp {
/**
This class implements a trivial default configuration for log4cpp:
it adds a FileAppender that logs to stdout and uses a BasicLayout to
the root Category.
@since 0.3.2
**/
class LOG4CPP_EXPORT BasicConfigurator {
public:
/**
Performs a minimal configuration of log4cpp.
**/
static void configure();
};
}
#endif
|
zzengine
|
trunk/TinyLog/include/log4cpp/BasicConfigurator.hh
|
C++
|
gpl3
| 693
|
/*
* Win32DebugAppender.hh
*
*
* See the COPYING file for the terms of usage and distribution.
*/
#ifndef _LOG4CPP_WIN32DEBUGAPPENDER_HH
#define _LOG4CPP_WIN32DEBUGAPPENDER_HH
#ifdef WIN32 // only use this on Win32
#include <string>
#include "log4cpp/Export.hh"
#include "log4cpp/LayoutAppender.hh"
namespace log4cpp {
/**
* Win32DebugAppender simply sends the log message to the default system
* debugger on Win32 systems. This is useful for users of MSVC and Borland
* because the log messages will show up in the debugger window.<BR>
* <B>NB:</B> This class is only available on Win32 platforms.
*/
class LOG4CPP_EXPORT Win32DebugAppender : public LayoutAppender {
public:
/**
* Constructor.
* @param name Name used by the base classes only.
*/
Win32DebugAppender(const std::string& name);
/**
* Destructor.
*/
virtual ~Win32DebugAppender();
/**
* Close method. This is called by the framework, but there is nothing
* to do for the OutputDebugString API, so it simply returns.
*/
virtual void close();
protected:
/**
* Method that does the actual work. In this case, it simply sets up the layout
* and calls the OutputDebugString API.
* @param event Event for which we are logging.
*/
virtual void _append(const LoggingEvent& event);
};
}
#else // WIN32
#error NTEventLoggAppender is not available on on Win32 platforms
#endif // WIN32
#endif // _LOG4CPP_WIN32DEBUGAPPENDER_HH
|
zzengine
|
trunk/TinyLog/include/log4cpp/Win32DebugAppender.hh
|
C++
|
gpl3
| 1,523
|
/*
* RollingFileAppender.hh
*
* See the COPYING file for the terms of usage and distribution.
*/
#ifndef _LOG4CPP_ROLLINGFILEAPPENDER_HH
#define _LOG4CPP_ROLLINGFILEAPPENDER_HH
#include <log4cpp/Portability.hh>
#include <log4cpp/FileAppender.hh>
#include <string>
#include <stdarg.h>
namespace log4cpp {
/**
RollingFileAppender is a FileAppender that rolls over the logfile once
it has reached a certain size limit.
@since 0.3.1
**/
class LOG4CPP_EXPORT RollingFileAppender : public FileAppender {
public:
RollingFileAppender(const std::string& name,
const std::string& fileName,
size_t maxFileSize = 10*1024*1024,
unsigned int maxBackupIndex = 1,
bool append = true,
mode_t mode = 00644);
virtual void setMaxBackupIndex(unsigned int maxBackups);
virtual unsigned int getMaxBackupIndex() const;
virtual void setMaximumFileSize(size_t maxFileSize);
virtual size_t getMaxFileSize() const;
virtual void rollOver();
protected:
virtual void _append(const LoggingEvent& event);
unsigned int _maxBackupIndex;
size_t _maxFileSize;
};
}
#endif // _LOG4CPP_ROLLINGFILEAPPENDER_HH
|
zzengine
|
trunk/TinyLog/include/log4cpp/RollingFileAppender.hh
|
C++
|
gpl3
| 1,350
|
/*
* Manipulator.hh
*
* Copyright 2005, Francis ANDRE. All rights reserved.
*
* See the COPYING file for the terms of usage and distribution.
*/
#ifndef _LOG4CPP_MANIPULATOR_HH
#define _LOG4CPP_MANIPULATOR_HH
#include <iostream>
#include <log4cpp/Portability.hh>
namespace log4cpp {
class LOG4CPP_EXPORT width {
private:
unsigned int size;
public:
inline width(unsigned int i) : size(i) {}
friend LOG4CPP_EXPORT std::ostream& operator<< (std::ostream& os, const width& w);
};
class LOG4CPP_EXPORT tab {
private:
unsigned int size;
public:
inline tab(unsigned int i) : size(i) {}
friend LOG4CPP_EXPORT std::ostream& operator<< (std::ostream& os, const tab& w);
};
};
#endif
|
zzengine
|
trunk/TinyLog/include/log4cpp/Manipulator.hh
|
C++
|
gpl3
| 692
|
#ifndef _INCLUDE_LOG4CPP_CONFIG_OPENVMS_H
#define _INCLUDE_LOG4CPP_CONFIG_OPENVMS_H 1
/* include/log4cpp/config.h. Generated automatically at end of configure. */
/* include/config.h. Generated automatically by configure. */
/* include/config.h.in. Generated automatically from configure.in by autoheader. */
/* Define if you have the <dlfcn.h> header file. */
#ifndef LOG4CPP_HAVE_DLFCN_H
#define LOG4CPP_HAVE_DLFCN_H 1
#endif
/* Define if you have the `ftime' function. */
#ifndef LOG4CPP_HAVE_FTIME
#define LOG4CPP_HAVE_FTIME 1
#endif
/* Define if you have the `gettimeofday' function. */
#ifndef LOG4CPP_HAVE_GETTIMEOFDAY
#define LOG4CPP_HAVE_GETTIMEOFDAY 1
#endif
/* define if the compiler has int64_t */
#ifndef LOG4CPP_HAVE_INT64_T
#define LOG4CPP_HAVE_INT64_T
#include <inttypes.h>
#endif
/* Define if you have the <io.h> header file. */
/* #undef LOG4CPP_HAVE_IO_H */
/* Define if you have the `idsa' library (-lidsa). */
/* #undef LOG4CPP_HAVE_LIBIDSA */
/* define if the compiler implements namespaces */
#ifndef LOG4CPP_HAVE_NAMESPACES
#define LOG4CPP_HAVE_NAMESPACES
#endif
/* define if the C library has snprintf */
/* #undef LOG4CPP_HAVE_SNPRINTF */
/* define if the compiler has stringstream */
#ifndef LOG4CPP_HAVE_SSTREAM
#define LOG4CPP_HAVE_SSTREAM
#endif
/* Define if you have the `syslog' function. */
/* #undef LOG4CPP_HAVE_SYSLOG */
/* Define if you have the <unistd.h> header file. */
#ifndef LOG4CPP_HAVE_UNISTD_H
#define LOG4CPP_HAVE_UNISTD_H 1
#endif
/* Name of package */
#ifndef LOG4CPP_PACKAGE
#define LOG4CPP_PACKAGE "log4cpp"
#endif
/* Version number of package */
#ifndef LOG4CPP_VERSION
#define LOG4CPP_VERSION "0.3.5"
#endif
/* _INCLUDE_LOG4CPP_CONFIG_OPENVMS_H */
#endif
|
zzengine
|
trunk/TinyLog/include/log4cpp/config-openvms.h
|
C
|
gpl3
| 1,761
|
/*
* HierarchyMaintainer.hh
*
* Copyright 2000, LifeLine Networks BV (www.lifeline.nl). All rights reserved.
* Copyright 2000, Bastiaan Bakker. All rights reserved.
*
* See the COPYING file for the terms of usage and distribution.
*/
#ifndef _LOG4CPP_HIERARCHYMAINTAINER_HH
#define _LOG4CPP_HIERARCHYMAINTAINER_HH
#include <log4cpp/Portability.hh>
#include <string>
#include <map>
#include <vector>
#include <log4cpp/Category.hh>
#include <log4cpp/threading/Threading.hh>
namespace log4cpp {
/**
* HierarchyMaintainer is an internal log4cpp class. It is responsible
* for maintaining the hierarchy of Categories. Applications should
* not have to use this class directly.
**/
class HierarchyMaintainer {
friend class Log4cppCleanup;
public:
typedef std::map<std::string, Category*> CategoryMap;
static HierarchyMaintainer& getDefaultMaintainer();
HierarchyMaintainer();
virtual ~HierarchyMaintainer();
virtual Category* getExistingInstance(const std::string& name);
virtual Category& getInstance(const std::string& name);
virtual std::vector<Category*>* getCurrentCategories() const;
virtual void shutdown();
virtual void deleteAllCategories();
protected:
virtual Category* _getExistingInstance(const std::string& name);
virtual Category& _getInstance(const std::string& name);
CategoryMap _categoryMap;
mutable threading::Mutex _categoryMutex;
private:
static HierarchyMaintainer* _defaultMaintainer;
};
}
#endif // _LOG4CPP_HIERARCHYMAINTAINER_HH
|
zzengine
|
trunk/TinyLog/include/log4cpp/HierarchyMaintainer.hh
|
C++
|
gpl3
| 1,652
|
/*
* OmniThreads.hh
*
* Copyright 2002, LifeLine Networks BV (www.lifeline.nl). All rights reserved.
* Copyright 2002, Bastiaan Bakker. All rights reserved.
*
* See the COPYING file for the terms of usage and distribution.
*/
#ifndef _LOG4CPP_THREADING_OMNITHREADS_HH
#define _LOG4CPP_THREADING_OMNITHREADS_HH
#include <log4cpp/Portability.hh>
#include <omnithread.h>
#include <stdio.h>
#include <string>
namespace log4cpp {
namespace threading {
/**
* Return an identifier for the current thread. What these
* identifiers look like is completely up to the underlying
* thread library. OmniThreads returns the POSIX thread Id.
**/
std::string getThreadId();
/**
* A simple, non recursive Mutex.
* Equivalent to Boost.Threads boost::mutex
**/
typedef omni_mutex Mutex;
/**
* A simple "resource acquisition is initialization" idiom type lock
* for Mutex.
* Equivalent to Boost.Threads boost::scoped_lock.
**/
typedef omni_mutex_lock ScopedLock;
/**
* This class holds Thread local data of type T, i.e. for each
* thread a ThreadLocalDataHolder holds 0 or 1 instance of T.
* The held object must be heap allocated and will be deleted
* upon termination of the thread to wich it belongs.
* This is an omni_threads based equivalent of Boost.Threads
* thread_specific_ptr<T> class.
**/
template<typename T> class ThreadLocalDataHolder {
public:
typedef T data_type;
inline ThreadLocalDataHolder() :
_key(omni_thread::allocate_key()) {};
inline ~ThreadLocalDataHolder() {};
/**
* Obtains the Object held for the current thread.
* @return a pointer to the held Object or NULL if no
* Object has been set for the current thread.
**/
inline T* get() const {
Holder* holder = dynamic_cast<Holder*>(
::omni_thread::self()->get_value(_key));
return (holder) ? holder->data : NULL;
};
/**
* Obtains the Object held for the current thread.
* Initially each thread holds NULL.
* @return a pointer to the held Object or NULL if no
* Object has been set for the current thread.
**/
inline T* operator->() const { return get(); };
/**
* Obtains the Object held for the current thread.
* @pre get() != NULL
* @return a reference to the held Object.
**/
inline T& operator*() const { return *get(); };
/**
* Releases the Object held for the current thread.
* @post get() == NULL
* @return a pointer to the Object thas was held for
* the current thread or NULL if no Object was held.
**/
inline T* release() {
T* result = NULL;
Holder* holder = dynamic_cast<Holder*>(
::omni_thread::self()->get_value(_key));
if (holder) {
result = holder->data;
holder->data = NULL;
}
return result;
};
/**
* Sets a new Object to be held for the current thread. A
* previously set Object will be deleted.
* @param p the new object to hold.
* @post get() == p
**/
inline void reset(T* p = NULL) {
Holder* holder = dynamic_cast<Holder*>(
::omni_thread::self()->get_value(_key));
if (holder) {
if (holder->data)
delete holder->data;
holder->data = p;
} else {
holder = new Holder(p);
::omni_thread::self()->set_value(_key, holder);
}
};
private:
class Holder : public omni_thread::value_t {
public:
Holder(data_type* data) : data(data) {};
virtual ~Holder() { if (data) delete (data); };
data_type* data;
private:
Holder(const Holder& other);
Holder& operator=(const Holder& other);
};
omni_thread::key_t _key;
};
}
}
#endif
|
zzengine
|
trunk/TinyLog/include/log4cpp/threading/OmniThreads.hh
|
C++
|
gpl3
| 4,678
|
/*
* PThreads.hh
*
* Copyright 2002, Emiliano Martin emilianomc@terra.es All rights reserved.
*
* See the COPYING file for the terms of usage and distribution.
*/
#ifndef _LOG4CPP_THREADING_PTHREADS_HH
#define _LOG4CPP_THREADING_PTHREADS_HH
#include <log4cpp/Portability.hh>
#include <stdio.h>
#include <pthread.h>
#include <string>
#include <assert.h>
namespace log4cpp {
namespace threading {
/**
* returns the thread ID
**/
std::string getThreadId();
/**
**/
class Mutex {
private:
pthread_mutex_t mutex;
public:
inline Mutex() {
::pthread_mutex_init(&mutex, NULL);
}
inline void lock() {
::pthread_mutex_lock(&mutex);
}
inline void unlock() {
::pthread_mutex_unlock(&mutex);
}
inline ~Mutex() {
::pthread_mutex_destroy(&mutex);
}
private:
Mutex(const Mutex& m);
Mutex& operator=(const Mutex &m);
};
/**
* definition of ScopedLock;
**/
class ScopedLock {
private:
Mutex& _mutex;
public:
inline ScopedLock(Mutex& mutex) :
_mutex(mutex) {
_mutex.lock();
}
inline ~ScopedLock() {
_mutex.unlock();
}
};
/**
*
**/
template<typename T> class ThreadLocalDataHolder {
private:
pthread_key_t _key;
public:
typedef T data_type;
inline ThreadLocalDataHolder() {
::pthread_key_create(&_key, freeHolder);
}
inline static void freeHolder(void *p) {
assert(p != NULL);
delete reinterpret_cast<T *>(p);
}
inline ~ThreadLocalDataHolder() {
T *data = get();
if (data != NULL) {
delete data;
}
::pthread_key_delete(_key);
}
inline T* get() const {
return reinterpret_cast<T *>(::pthread_getspecific(_key));
}
inline T* operator->() const { return get(); }
inline T& operator*() const { return *get(); }
inline T* release() {
T* result = get();
::pthread_setspecific(_key, NULL);
return result;
}
inline void reset(T* p = NULL) {
T *data = get();
if (data != NULL) {
delete data;
}
::pthread_setspecific(_key, p);
}
};
}
}
#endif
|
zzengine
|
trunk/TinyLog/include/log4cpp/threading/PThreads.hh
|
C++
|
gpl3
| 2,925
|
liblog4cppincludedir = $(includedir)/log4cpp/threading
liblog4cppinclude_HEADERS = \
BoostThreads.hh \
DummyThreads.hh \
OmniThreads.hh \
PThreads.hh \
MSThreads.hh \
Threading.hh
|
zzengine
|
trunk/TinyLog/include/log4cpp/threading/Makefile.am
|
Makefile
|
gpl3
| 187
|
/*
* DummyThreads.hh
*
* Copyright 2002, LifeLine Networks BV (www.lifeline.nl). All rights reserved.
* Copyright 2002, Bastiaan Bakker. All rights reserved.
*
* See the COPYING file for the terms of usage and distribution.
*/
#ifndef _LOG4CPP_THREADING_DUMMYTHREADS_HH
#define _LOG4CPP_THREADING_DUMMYTHREADS_HH
#include <log4cpp/Portability.hh>
#include <stdio.h>
#include <string>
namespace log4cpp {
namespace threading {
std::string getThreadId();
/**
Dummy type 'int' for Mutex. Yes, this adds a bit of overhead in
the for of extra memory, but unfortunately 'void' is illegal.
**/
typedef int Mutex;
/**
Dummy type 'int' defintion of ScopedLock;
**/
typedef int ScopedLock;
template<typename T> class ThreadLocalDataHolder {
public:
typedef T data_type;
inline ThreadLocalDataHolder() {};
inline ~ThreadLocalDataHolder() {
if (_data)
delete _data;
};
inline T* get() const {
return _data;
};
inline T* operator->() const { return get(); };
inline T& operator*() const { return *get(); };
inline T* release() {
T* result = _data;
_data = NULL;
return result;
};
inline void reset(T* p = NULL) {
if (_data)
delete _data;
_data = p;
};
private:
T* _data;
};
}
}
#endif
|
zzengine
|
trunk/TinyLog/include/log4cpp/threading/DummyThreads.hh
|
C++
|
gpl3
| 1,683
|
/*
* Threading.hh
*
* Copyright 2002, LifeLine Networks BV (www.lifeline.nl). All rights reserved.
* Copyright 2002, Bastiaan Bakker. All rights reserved.
*
* See the COPYING file for the terms of usage and distribution.
*/
#ifndef _LOG4CPP_THREADING_THREADING_HH
#define _LOG4CPP_THREADING_THREADING_HH
#include <log4cpp/Portability.hh>
#ifdef LOG4CPP_HAVE_THREADING
#ifdef LOG4CPP_USE_OMNITHREADS
#include <log4cpp/threading/OmniThreads.hh>
#endif
#ifdef LOG4CPP_USE_BOOSTTHREADS
#include <log4cpp/threading/BoostThreads.hh>
#endif
#ifdef LOG4CPP_USE_MSTHREADS
#include <log4cpp/threading/MSThreads.hh>
#endif
#ifdef LOG4CPP_USE_PTHREADS
#include <log4cpp/threading/PThreads.hh>
#endif
#else /* LOG4CPP_HAVE_THREADING */
#include <log4cpp/threading/DummyThreads.hh>
#endif /* LOG4CPP_HAVE_THREADING */
#endif
|
zzengine
|
trunk/TinyLog/include/log4cpp/threading/Threading.hh
|
C++
|
gpl3
| 827
|
/*
* MSThreads.hh
*
* Copyright 2002, LifeLine Networks BV (www.lifeline.nl). All rights reserved.
* Copyright 2002, Bastiaan Bakker. All rights reserved.
*
* See the COPYING file for the terms of usage and distribution.
*/
#ifndef _LOG4CPP_THREADING_MSTHREADS_HH
#define _LOG4CPP_THREADING_MSTHREADS_HH
#include <string>
// deal with ERROR #define
// N.B. This #includes windows.h with NOGDI and WIN32_LEAN_AND_MEAN #defined.
// If this is not what the user wants, #include windows.h before this file.
#ifndef _WINDOWS_
# ifndef NOGDI
# define NOGDI // this will circumvent the ERROR #define in windows.h
# define LOG4CPP_UNDEFINE_NOGDI
# endif
# ifndef WIN32_LEAN_AND_MEAN
# define WIN32_LEAN_AND_MEAN
# define LOG4CPP_UNDEFINE_WIN32_LEAN_AND_MEAN
# endif
# include <windows.h>
# ifdef LOG4CPP_UNDEFINE_NOGDI
# undef NOGDI
# endif
# ifdef LOG4CPP_UNDEFINE_WIN32_LEAN_AND_MEAN
# undef WIN32_LEAN_AND_MEAN
# endif
#endif // done dealing with ERROR #define
namespace log4cpp {
namespace threading {
/**
* Return an identifier for the current thread. What these
* identifiers look like is completely up to the underlying
* thread library.
**/
std::string getThreadId();
/**
* A simple object wrapper around CreateMutex() and DeleteMutex()
*/
class LOG4CPP_EXPORT MSMutex {
public:
MSMutex() { InitializeCriticalSection(&_criticalSection); }
~MSMutex() { DeleteCriticalSection(&_criticalSection); }
inline LPCRITICAL_SECTION getCriticalSection() {
return &_criticalSection;
}
private:
MSMutex(const MSMutex& other);
CRITICAL_SECTION _criticalSection;
};
/**
* A simple, non recursive Mutex.
**/
typedef MSMutex Mutex;
/**
* A simple object wrapper around WaitForSingleObject() and
* ReleaseMutex()
*/
class MSScopedLock {
public:
MSScopedLock(MSMutex& mutex) {
_criticalSection = mutex.getCriticalSection();
EnterCriticalSection(_criticalSection);
}
~MSScopedLock() { LeaveCriticalSection(_criticalSection); }
private:
MSScopedLock(const MSScopedLock& other);
LPCRITICAL_SECTION _criticalSection;
};
/**
* A simple "resource acquisition is initialization" idiom type lock
* for Mutex.
**/
typedef MSScopedLock ScopedLock;
/**
* This class holds Thread local data of type T, i.e. for each
* thread a ThreadLocalDataHolder holds 0 or 1 instance of T.
* The held object must be heap allocated and will be deleted
* upon termination of the thread to which it belongs.
**/
template<typename T> class ThreadLocalDataHolder {
public:
inline ThreadLocalDataHolder() :
_key(TlsAlloc()) {};
inline ~ThreadLocalDataHolder() { TlsFree(_key); };
/**
* Obtains the Object held for the current thread.
* @return a pointer to the held Object or NULL if no
* Object has been set for the current thread.
**/
inline T* get() const {
return (T*)TlsGetValue(_key);
};
/**
* Obtains the Object held for the current thread.
* Initially each thread holds NULL.
* @return a pointer to the held Object or NULL if no
* Object has been set for the current thread.
**/
inline T* operator->() const { return get(); };
/**
* Obtains the Object held for the current thread.
* @pre get() != NULL
* @return a reference to the held Object.
**/
inline T& operator*() const { return *get(); };
/**
* Releases the Object held for the current thread.
* @post get() == NULL
* @return a pointer to the Object thas was held for
* the current thread or NULL if no Object was held.
**/
inline T* release() {
T* result = (T*)TlsGetValue(_key);
TlsSetValue(_key, NULL);
return result;
};
/**
* Sets a new Object to be held for the current thread. A
* previously set Object will be deleted.
* @param p the new object to hold.
* @post get() == p
**/
inline void reset(T* p = NULL) {
T* thing = (T*)TlsGetValue(_key);
delete thing;
TlsSetValue(_key, p);
};
private:
DWORD _key;
};
}
}
#endif
|
zzengine
|
trunk/TinyLog/include/log4cpp/threading/MSThreads.hh
|
C++
|
gpl3
| 5,027
|
/*
* BoostThreads.hh
*
* Copyright 2002, LifeLine Networks BV (www.lifeline.nl). All rights reserved.
* Copyright 2002, Bastiaan Bakker. All rights reserved.
*
* See the COPYING file for the terms of usage and distribution.
*/
#ifndef _LOG4CPP_THREADING_BOOSTTHREADS_HH
#define _LOG4CPP_THREADING_BOOSTTHREADS_HH
#include <log4cpp/Portability.hh>
#include <boost/thread/thread.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/thread/tss.hpp>
#include <cstdio>
#include <string>
namespace log4cpp {
namespace threading {
static std::string getThreadId() {
char buffer[14];
// Boost.Threads stores the thread ID but doesn't expose it
sprintf(buffer, "not available");
return std::string(buffer);
};
typedef boost::mutex Mutex;
typedef boost::mutex::scoped_lock ScopedLock;
template<typename T> class ThreadLocalDataHolder {
public:
inline T* get() const {
return _localData.get();
};
inline T* operator->() const { return _localData.get(); };
inline T& operator*() const { return *_localData.get(); };
inline T* release() {
return _localData.release();
};
inline void reset(T* p = NULL) {
_localData.reset(p);
};
private:
boost::thread_specific_ptr<T> _localData;
};
}
}
#endif
|
zzengine
|
trunk/TinyLog/include/log4cpp/threading/BoostThreads.hh
|
C++
|
gpl3
| 1,491
|
/*
* Portability.hh
*
* Copyright 2001, LifeLine Networks BV (www.lifeline.nl). All rights reserved.
* Copyright 2001, Bastiaan Bakker. All rights reserved.
*
* See the COPYING file for the terms of usage and distribution.
*/
#ifndef _LOG4CPP_PORTABILITY_HH
#define _LOG4CPP_PORTABILITY_HH
#if defined (_MSC_VER) || defined(__BORLANDC__)
# if defined (LOG4CPP_STLPORT_AND_BOOST_BUILD)
# include <log4cpp/config-win32-stlport-boost.h>
# else
# include <log4cpp/config-win32.h>
# endif
#else
#if defined(__OPENVMS__)
# include <log4cpp/config-openvms.h>
#else
# include <log4cpp/config.h>
#endif
#endif
#include <log4cpp/Export.hh>
#if defined(_MSC_VER)
# pragma warning( disable : 4786 ) // 255 char debug symbol limit
# pragma warning( disable : 4290 ) // throw specifier not implemented
# pragma warning( disable : 4251 ) // "class XXX should be exported"
#endif
#ifndef LOG4CPP_HAVE_SSTREAM
#include <strstream>
namespace std {
class LOG4CPP_EXPORT ostringstream : public ostrstream {
public:
std::string str();
};
}
#endif
#endif
|
zzengine
|
trunk/TinyLog/include/log4cpp/Portability.hh
|
C++
|
gpl3
| 1,108
|
/*
* NTEventLogAppender.hh
*
* See the COPYING file for the terms of usage and distribution.
*/
#ifndef _LOG4CPP_NTEVENTLOGAPPENDER_HH
#define _LOG4CPP_NTEVENTLOGAPPENDER_HH
#ifdef WIN32 // only available on Win32
// deal with ERROR #define
// N.B. This #includes windows.h with NOGDI and WIN32_LEAN_AND_MEAN #defined.
// If this is not what the user wants, #include windows.h before this file.
#ifndef _WINDOWS_
# ifndef NOGDI
# define NOGDI // this will circumvent the ERROR #define in windows.h
# define LOG4CPP_UNDEFINE_NOGDI
# endif
# ifndef WIN32_LEAN_AND_MEAN
# define WIN32_LEAN_AND_MEAN
# define LOG4CPP_UNDEFINE_WIN32_LEAN_AND_MEAN
# endif
# include <windows.h>
# ifdef LOG4CPP_UNDEFINE_NOGDI
# undef NOGDI
# endif
# ifdef LOG4CPP_UNDEFINE_WIN32_LEAN_AND_MEAN
# undef WIN32_LEAN_AND_MEAN
# endif
#endif // done dealing with ERROR #define
#include <log4cpp/Portability.hh>
#include <log4cpp/AppenderSkeleton.hh>
namespace log4cpp {
/**
* NTEventLogAppender is an Appender that sends LoggingEvents to the
* Windows event log.
* Building log4cpp.dsp/log4cppDLL.dsp creates the resource DLL NTEventLogAppender.dll.
* Do not forget to place this DLL in a directory that is on the PATH
* of the Windows system. Otherwise, the category and message will not display
* correctly in Event Viewer.<BR>
* <B>NB:</B> This class is only available on Win32 platforms.
**/
class LOG4CPP_EXPORT NTEventLogAppender : public AppenderSkeleton {
public:
/**
* Instantiate an NTEventLogAppender with given name and source.
* @param name The name of the Appender
* @param sourceName The source name to log
**/
NTEventLogAppender(const std::string& name, const std::string& sourceName);
virtual ~NTEventLogAppender();
/**
* Calls open() and close()
**/
virtual bool reopen();
virtual void close();
/**
* The NTEventLogAppender does its own Layout.
* @returns false
**/
virtual bool requiresLayout() const;
virtual void setLayout(Layout* layout);
protected:
WORD getCategory(Priority::Value priority);
WORD getType(Priority::Value priority);
HKEY regGetKey(TCHAR *subkey, DWORD *disposition);
void regSetString(HKEY hkey, TCHAR *name, TCHAR *value);
void regSetDword(HKEY hkey, TCHAR *name, DWORD value);
void addRegistryInfo(const char *source);
virtual void open();
/**
* Sends a LoggingEvent to NT Event log.
* @param event the LoggingEvent to log.
**/
virtual void _append(const LoggingEvent& event);
HANDLE _hEventSource;
std::string _strSourceName;
};
}
#else // WIN32
#error NTEventLoggAppender is not available on on Win32 platforms
#endif // WIN32
#endif // _LOG4CPP_NTEVENTLOGAPPENDER_HH
|
zzengine
|
trunk/TinyLog/include/log4cpp/NTEventLogAppender.hh
|
C++
|
gpl3
| 2,989
|
/*
* IdsaAppender.hh
*
* Copyright 2000, Marc Welz
*
* See the COPYING file for the terms of usage and distribution.
*/
#ifndef _LOG4CPP_IDSAAPPENDER_HH
#define _LOG4CPP_IDSAAPPENDER_HH
#include <log4cpp/Portability.hh>
#include <string>
#include <stdarg.h>
#include <idsa.h>
#include <log4cpp/AppenderSkeleton.hh>
namespace log4cpp {
/**
* IdsaAppender is an Appender that sends LoggingEvents to the IDS/A
* logger and reference monitor by Marc Welz.
* See http://jade.cs.uct.ac.za/idsa/ for more information on IDS/A.
**/
class IdsaAppender : public AppenderSkeleton {
public:
/**
* Instantiate an IdsaAppender with given name and name.
* Unlike the syslog API, idsa allows multiple connections.
* @param name The name of the Appender
* @param idsaName The service parameter of idsa
**/
IdsaAppender(const std::string& name, const std::string& idsaName);
virtual ~IdsaAppender();
/**
* Calls idsa_open() and idsa_close()
**/
virtual bool reopen();
/**
* Calls idsa_close()
**/
virtual void close();
/**
* The IdsaAppender does its own Layout.
* @returns false
**/
virtual bool requiresLayout() const;
virtual void setLayout(Layout* layout);
protected:
/**
* Calls idsa_open().
**/
virtual void open();
/**
* Sends a LoggingEvent to idsa.
* @param event the LoggingEvent to log.
**/
virtual void _append(const LoggingEvent& event);
const std::string _idsaName;
IDSA_CONNECTION *_idsaConnection;
};
}
#endif // _LOG4CPP_IDSAAPPENDER_HH
|
zzengine
|
trunk/TinyLog/include/log4cpp/IdsaAppender.hh
|
C++
|
gpl3
| 1,807
|
/*
* OstreamAppender.hh
*
* Copyright 2000, LifeLine Networks BV (www.lifeline.nl). All rights reserved.
* Copyright 2000, Bastiaan Bakker. All rights reserved.
*
* See the COPYING file for the terms of usage and distribution.
*/
#ifndef _LOG4CPP_OSTREAMAPPENDER_HH
#define _LOG4CPP_OSTREAMAPPENDER_HH
#include <log4cpp/Portability.hh>
#include <string>
#include <iostream>
#include <log4cpp/LayoutAppender.hh>
namespace log4cpp {
/**
* OstreamAppender appends LoggingEvents to ostreams.
**/
class LOG4CPP_EXPORT OstreamAppender : public LayoutAppender {
public:
OstreamAppender(const std::string& name, std::ostream* stream);
virtual ~OstreamAppender();
virtual bool reopen();
virtual void close();
protected:
virtual void _append(const LoggingEvent& event);
std::ostream* _stream;
};
}
#endif // _LOG4CPP_OSTREAMAPPENDER_HH
|
zzengine
|
trunk/TinyLog/include/log4cpp/OstreamAppender.hh
|
C++
|
gpl3
| 935
|
//////////////////////////////////////////////////////////////////////////////////////
//
// FileName : KGError.h
// Version : 1.0
// Creater : Freeway Chen
// Date : 2004-12-17 10:32:32
// Comment : Kingsoft Game Public Error Code
//
//////////////////////////////////////////////////////////////////////////////////////
#ifndef _KGERROR_H_
#define _KGERROR_H_ 1
#ifdef WIN32
// if Win32 platform
#include <Windows.h>
#include <Unknwn.h>
#else // #ifndef WIN32
#ifndef _HRESULT_DEFINED
#define _HRESULT_DEFINED
typedef long HRESULT;
#endif // !_HRESULT_DEFINED
#ifndef SUCCEEDED
#define SUCCEEDED(Status) ((HRESULT)(Status) >= 0)
#endif
#ifndef FAILED
#define FAILED(Status) ((HRESULT)(Status) < 0)
#endif
#ifndef _HRESULT_TYPEDEF_
#define _HRESULT_TYPEDEF_(_sc) ((HRESULT)_sc)
#endif
#endif // #ifdef WIN32 #else
//=============================================================================
//
// Error Code From WinError.h Start
//
//=============================================================================
//
// Success codes
//
#define KG_S_OK _HRESULT_TYPEDEF_(0x00000000L)
#define KG_S_FALSE _HRESULT_TYPEDEF_(0x00000001L)
//
// MessageId: KG_E_NOTIMPL
//
// MessageText:
//
// Not implemented
//
#define KG_E_NOTIMPL _HRESULT_TYPEDEF_(0x80004001L)
//
// MessageId: KG_E_OUTOFMEMORY
//
// MessageText:
//
// Ran out of memory
//
#define KG_E_OUTOFMEMORY _HRESULT_TYPEDEF_(0x8007000EL)
//
// MessageId: KG_E_INVALIDARG
//
// MessageText:
//
// One or more arguments are invalid
//
#define KG_E_INVALIDARG _HRESULT_TYPEDEF_(0x80070057L)
//
// MessageId: KG_E_NOINTERFACE
//
// MessageText:
//
// No such interface supported
//
#define KG_E_NOINTERFACE _HRESULT_TYPEDEF_(0x80004002L)
//
// MessageId: KG_E_POINTER
//
// MessageText:
//
// Invalid pointer
//
#define KG_E_POINTER _HRESULT_TYPEDEF_(0x80004003L)
//
// MessageId: KG_E_HANDLE
//
// MessageText:
//
// Invalid handle
//
#define KG_E_HANDLE _HRESULT_TYPEDEF_(0x80070006L)
//
// MessageId: KG_E_ABORT
//
// MessageText:
//
// Operation aborted
//
#define KG_E_ABORT _HRESULT_TYPEDEF_(0x80004004L)
//
// MessageId: KG_E_FAIL
//
// MessageText:
//
// Unspecified error
//
#define KG_E_FAIL _HRESULT_TYPEDEF_(0x80004005L)
//
// MessageId: KG_E_ACCESSDENIED
//
// MessageText:
//
// General access denied error
//
#define KG_E_ACCESSDENIED _HRESULT_TYPEDEF_(0x80070005L)
//=============================================================================
//
// Error Code From WinError.h End
//
//=============================================================================
//=============================================================================
//
// Error Code for Kingsoft Game Start
//
//=============================================================================
//
// MessageId: KG_E_TIMEOUT
//
// MessageText:
//
// Timeout
//
#define KG_E_TIMEOUT _HRESULT_TYPEDEF_(0x80880001L)
//
// MessageId: KG_E_SOCKET
//
// MessageText:
//
// socket error
//
#define KG_E_SOCKET _HRESULT_TYPEDEF_(0x80880002L)
//
// MessageId: KG_E_NO_DATA
//
// MessageText:
//
// data not arrive
//
#define KG_E_NO_DATA _HRESULT_TYPEDEF_(0x80880003L)
//
// MessageId: KG_E_DATA_NO_FOUND
//
// MessageText:
//
// data not found in out queue
//
#define KG_E_DATA_NO_FOUND _HRESULT_TYPEDEF_(0x80880004L)
//=============================================================================
//
// Error Code for Kingsoft Game End
//
//=============================================================================
#endif // _KGERROR_H_
|
zzengine
|
trunk/TinyLog/include/kingsoft/KGError.h
|
C
|
gpl3
| 4,125
|
//////////////////////////////////////////////////////////////////////////////////////
//
// FileName : KGLog.h
// Version : 1.0
// Creater : Freeway Chen
// Date : 2004-12-22 17:39:39
// Comment :
//
//////////////////////////////////////////////////////////////////////////////////////
#ifndef _KGLOG_H_
#define _KGLOG_H_ 1
#include "EngineBase.h"
#include "KGCRT.h"
#include "KSUnknown.h"
#include "KGPublic.h"
// priorities/facilities are encoded into a single 32-bit quantity, where the
// bottom 3 bits are the priority (0-7) and the top 28 bits are the facility
// (0-big number). Both the priorities and the facilities map roughly
// one-to-one to strings in the syslogd(8) source code. This mapping is
// included in this file.
//
// priorities (these are ordered)
enum KGLOG_PRIORITY
{
KGLOG_RESERVE0 = 0, // KGLOG_EMERG = 0, // system is unusable
KGLOG_RESERVE1 = 1, // KGLOG_ALERT = 1, // action must be taken immediately
KGLOG_RESERVE2 = 2, // KGLOG_CRIT = 2, // critical conditions
KGLOG_ERR = 3, // error conditions
KGLOG_WARNING = 4, // warning conditions
KGLOG_RESERVE3 = 5, // KGLOG_NOTICE = 5, // normal but significant condition
KGLOG_INFO = 6, // informational
KGLOG_DEBUG = 7, // debug-level messages
KGLOG_PRIORITY_MAX
};
enum KGLOG_OPTIONS
{
KGLOG_OPTION_FILE = 0x01, // log on to file, default
KGLOG_OPTION_CONSOLE = 0x02, // log on the console if errors in sending
KGLOG_OPTION_STDERR = 0x04, // log on the stderr stream
//KGLOG_UDP = 0x08, // log to syslogd server use UDP
};
#define KGLOG_PRIMASK 0x07
#define KGLOG_PRI(pri) ((pri) & KGLOG_PRIMASK)
// arguments to setlogmask.
#define KGLOG_MASK(pri) (1 << (pri)) // mask for one priority
#define KGLOG_UPTO(pri) ((1 << ((pri)+1)) - 1) // all priorities through pri
typedef struct _KGLOG_PARAM
{
char szPath[PATH_MAX]; // if KGLOG_FILE
char szIdent[PATH_MAX]; // if KGLOG_FILE
KGLOG_OPTIONS Options; // 0 is default
int nMaxLineEachFile;
} KGLOG_PARAM;
// cszIdent is file name prefix
ENGINE_API int KGLogInit(const KGLOG_PARAM& cLogParam, void *pvContext);
ENGINE_API int KGLogUnInit(void *pvContext);
// Set the log mask level if nPriorityMask != 0
ENGINE_API int KGLogSetPriorityMask(int nPriorityMask);
ENGINE_API int KGLogPrintf(KGLOG_PRIORITY Priority, const char cszFormat[], ...);
#define KGLOG_PROCESS_ERROR(Condition) \
do \
{ \
if (!(Condition)) \
{ \
KGLogPrintf( \
KGLOG_DEBUG, \
"KGLOG_PROCESS_ERROR(%s) at line %d in %s\n", #Condition, __LINE__, KG_FUNCTION \
); \
goto Exit0; \
} \
} WHILE_FALSE_NO_WARNING
#define KGLOG_OUTPUT_ERROR(Condition) \
do \
{ \
if (!(Condition)) \
{ \
KGLogPrintf( \
KGLOG_DEBUG, \
"KGLOG_PROCESS_ERROR(%s) at line %d in %s\n", #Condition, __LINE__, KG_FUNCTION \
); \
} \
} WHILE_FALSE_NO_WARNING
#define KGLOG_PROCESS_SUCCESS(Condition) \
do \
{ \
if (Condition) \
{ \
KGLogPrintf( \
KGLOG_DEBUG, \
"KGLOG_PROCESS_SUCCESS(%s) at line %d in %s\n", #Condition, __LINE__, KG_FUNCTION \
); \
goto Exit1; \
} \
} WHILE_FALSE_NO_WARNING
#define KGLOG_PROCESS_ERROR_RET_CODE(Condition, Code) \
do \
{ \
if (!(Condition)) \
{ \
KGLogPrintf( \
KGLOG_DEBUG, \
"KGLOG_PROCESS_ERROR_RET_CODE(%s, %d) at line %d in %s\n", \
#Condition, (Code), __LINE__, KG_FUNCTION \
); \
nResult = (Code); \
goto Exit0; \
} \
} WHILE_FALSE_NO_WARNING
#define KGLOG_PROCESS_ERROR_RET_COM_CODE(Condition, Code) \
do \
{ \
if (!(Condition)) \
{ \
KGLogPrintf( \
KGLOG_DEBUG, \
"KGLOG_PROCESS_ERROR_RET_CODE(%s, %d) at line %d in %s\n", \
#Condition, (Code), __LINE__, KG_FUNCTION \
); \
hrResult = (Code); \
goto Exit0; \
} \
} WHILE_FALSE_NO_WARNING
#define KGLOG_COM_PROCESS_ERROR(Condition) \
do \
{ \
if (FAILED(Condition)) \
{ \
KGLogPrintf( \
KGLOG_DEBUG, \
"KGLOG_COM_PROCESS_ERROR(0x%X) at line %d in %s\n", (Condition), __LINE__, KG_FUNCTION \
); \
goto Exit0; \
} \
} WHILE_FALSE_NO_WARNING
#define KGLOG_COM_PROCESS_SUCCESS(Condition) \
do \
{ \
if (SUCCEEDED(Condition)) \
{ \
KGLogPrintf( \
KGLOG_DEBUG, \
"KGLOG_COM_PROCESS_SUCCESS(0x%X) at line %d in %s\n", (Condition), __LINE__, KG_FUNCTION \
); \
goto Exit1; \
} \
} WHILE_FALSE_NO_WARNING
// KG_COM_PROCESS_ERROR_RETURN_ERROR
#define KGLOG_COM_PROC_ERR_RET_ERR(Condition) \
do \
{ \
if (FAILED(Condition)) \
{ \
KGLogPrintf( \
KGLOG_DEBUG, \
"KGLOG_COM_PROC_ERR_RET_ERR(0x%X) at line %d in %s\n", (Condition), __LINE__, KG_FUNCTION \
); \
hrResult = (Condition); \
goto Exit0; \
} \
} WHILE_FALSE_NO_WARNING
#define KGLOG_COM_PROC_ERROR_RET_CODE(Condition, Code) \
do \
{ \
if (FAILED(Condition)) \
{ \
KGLogPrintf( \
KGLOG_DEBUG, \
"KGLOG_COM_PROC_ERROR_RET_CODE(0x%X, 0x%X) at line %d in %s\n", (Condition), (Code), __LINE__, KG_FUNCTION \
); \
hrResult = (Code); \
goto Exit0; \
} \
} WHILE_FALSE_NO_WARNING
#define KGLOG_CHECK_ERROR(Condition) \
do \
{ \
if (!(Condition)) \
{ \
KGLogPrintf( \
KGLOG_DEBUG, \
"KGLOG_CHECK_ERROR(%s) at line %d in %s\n", #Condition, __LINE__, KG_FUNCTION \
); \
} \
} WHILE_FALSE_NO_WARNING
#define KGLOG_COM_CHECK_ERROR(Condition) \
do \
{ \
if (FAILED(Condition)) \
{ \
KGLogPrintf( \
KGLOG_DEBUG, \
"KGLOG_COM_CHECK_ERROR(0x%X) at line %d in %s\n", (Condition), __LINE__, KG_FUNCTION \
); \
} \
} WHILE_FALSE_NO_WARNING
#endif // _KGLOGGER_H_
|
zzengine
|
trunk/TinyLog/include/kingsoft/KGLog.h
|
C
|
gpl3
| 7,883
|
//////////////////////////////////////////////////////////////////////////////////////
//
// FileName : KGCRT.h
// Version : 1.0
// Creater : Freeway Chen
// Date : 2004-12-23 9:28:46
// Comment : Kingsoft Game C Runtime
//
//////////////////////////////////////////////////////////////////////////////////////
#ifndef _KGCRT_H
#define _KGCRT_H 1
#include "EngineBase.h"
#if (defined(_MSC_VER) || defined(__ICL))
#include <direct.h>
#include <io.h>
#else // if linux
#endif
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <errno.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#if (defined(_MSC_VER) || defined(__ICL))
#define snprintf _snprintf
#define vsnprintf _vsnprintf
#endif
//#if (defined(_MSC_VER) || defined(__ICL))
//#define fileno _fileno
//#endif
inline unsigned KG_Rand()
{
static unsigned s_uHoldRand = (unsigned)time(NULL);
s_uHoldRand = s_uHoldRand * 214013L + 2531011L;
return s_uHoldRand;
}
#if (defined(_MSC_VER) || defined(__ICL))
#define KG_mkdir mkdir
#else // if linux
inline int KG_mkdir(const char cszDir[])
{
return mkdir(cszDir, 0777);
}
#endif
#define KG_rmdir rmdir
#define KG_chdir chdir
#if (defined(_MSC_VER) || defined(__ICL))
inline struct tm *localtime_r(const time_t *timep, struct tm *result)
{
struct tm *ptm = localtime(timep);
if (
(result) &&
(ptm)
)
{
*result = *ptm;
}
return ptm;
};
#endif
#ifndef PATH_MAX
#define PATH_MAX 1024
#endif
#ifdef __GNUC__
// return true or false
int kbhit();
#endif // __GNUC__, for "kbhit()" implementation
#endif // _KGCRT_H
|
zzengine
|
trunk/TinyLog/include/kingsoft/KGCRT.h
|
C
|
gpl3
| 1,804
|
#ifndef _KSUNKNOWN_H_
#define _KSUNKNOWN_H_ 1
#ifdef _WIN32
#include <Unknwn.h>
#else // POSIX
#ifdef __cplusplus
extern "C"{
#endif
/* header files for imported files */
#include "KSCOMTypes.h"
extern const IID IID_IUnknown;
MIDL_INTERFACE("00000000-0000-0000-C000-000000000046")
IUnknown
{
public:
BEGIN_INTERFACE
virtual HRESULT STDMETHODCALLTYPE QueryInterface(
/* [in] */ REFIID riid,
/* [iid_is][out] */ void **ppvObject) = 0;
virtual ULONG STDMETHODCALLTYPE AddRef( void) = 0;
virtual ULONG STDMETHODCALLTYPE Release( void) = 0;
END_INTERFACE
};
/* [local] */
typedef /* [unique] */ IUnknown __RPC_FAR *LPUNKNOWN;
extern const IID IID_IClassFactory;
MIDL_INTERFACE("00000001-0000-0000-C000-000000000046")
IClassFactory : public IUnknown
{
public:
virtual /* [local] */ HRESULT STDMETHODCALLTYPE CreateInstance(
/* [unique][in] */ IUnknown *pUnkOuter,
/* [in] */ REFIID riid,
/* [iid_is][out] */ void **ppvObject) = 0;
virtual /* [local] */ HRESULT STDMETHODCALLTYPE LockServer(
/* [in] */ int fLock) = 0;
};
/* [local] */
typedef /* [unique] */ IClassFactory __RPC_FAR *LPCLASSFACTORY;
#ifdef __cplusplus
}
#endif
#endif // _WIN32
#endif // _KSUNKNOWN_H_
|
zzengine
|
trunk/TinyLog/include/kingsoft/KSUnknown.h
|
C
|
gpl3
| 1,474
|
//////////////////////////////////////////////////////////////////////////////////////
//
// FileName : KSGPublic.h
// Version : 1.0
// Creater : Freeway Chen
// Date : 2004-4-19 20:44:49
// Comment : Kingsoft Game Public header file
//
//////////////////////////////////////////////////////////////////////////////////////
#ifndef _KGPUBLIC_H
#define _KGPUBLIC_H 1
#include <assert.h>
#include "KGError.h"
#ifndef ASSERT
#define ASSERT assert
#endif
#ifdef WIN32
#define KG_FUNCTION __FUNCTION__
#else
#define KG_FUNCTION __PRETTY_FUNCTION__
#endif
#ifdef _MSC_VER
#define TEMP_DISABLE_WARNING(warningCode, expression) \
__pragma(warning(push)) \
__pragma(warning(disable:warningCode)) \
expression \
__pragma(warning(pop))
#else
#define TEMP_DISABLE_WARNING(warningCode, expression) \
expression
#endif
// _MSC_VER warning C4127: conditional expression is constant
// use this macro instead "WHILE_FALSE_NO_WARNING", you can enjoy the level 4 warning ^_^
#define WHILE_FALSE_NO_WARNING \
TEMP_DISABLE_WARNING(4127, while (false))
#define KG_USE_ARGUMENT(arg) (arg)
#define KG_PROCESS_ERROR(Condition) \
do \
{ \
if (!(Condition)) \
goto Exit0; \
} WHILE_FALSE_NO_WARNING
#define KG_PROCESS_SUCCESS(Condition) \
do \
{ \
if (Condition) \
goto Exit1; \
} WHILE_FALSE_NO_WARNING
#define KG_PROCESS_ERROR_RET_CODE(Condition, Code) \
do \
{ \
if (!(Condition)) \
{ \
nResult = Code; \
goto Exit0; \
} \
} WHILE_FALSE_NO_WARNING
#define KG_PROCESS_ERROR_RET_COM_CODE(Condition, Code) \
do \
{ \
if (!(Condition)) \
{ \
hrResult = Code; \
goto Exit0; \
} \
} WHILE_FALSE_NO_WARNING
#define KG_COM_PROCESS_ERROR(Condition) \
do \
{ \
if (FAILED(Condition)) \
goto Exit0; \
} WHILE_FALSE_NO_WARNING
#define KG_COM_PROCESS_SUCCESS(Condition) \
do \
{ \
if (SUCCEEDED(Condition)) \
goto Exit1; \
} WHILE_FALSE_NO_WARNING
// KG_COM_PROCESS_ERROR_RETURN_ERROR
#define KG_COM_PROC_ERR_RET_ERR(Condition) \
do \
{ \
if (FAILED(Condition)) \
{ \
hrResult = Condition; \
goto Exit0; \
} \
} WHILE_FALSE_NO_WARNING
#define KG_COM_PROC_ERROR_RET_CODE(Condition, Code) \
do \
{ \
if (FAILED(Condition)) \
{ \
hrResult = Code; \
goto Exit0; \
} \
} WHILE_FALSE_NO_WARNING
#define KG_COM_RELEASE(pInterface) \
do \
{ \
if (pInterface) \
{ \
(pInterface)->Release(); \
(pInterface) = NULL; \
} \
} WHILE_FALSE_NO_WARNING
#define KG_DELETE_ARRAY(pArray) \
do \
{ \
if (pArray) \
{ \
delete [](pArray); \
(pArray) = NULL; \
} \
} WHILE_FALSE_NO_WARNING
#define KG_DELETE(p) \
do \
{ \
if (p) \
{ \
delete (p); \
(p) = NULL; \
} \
} WHILE_FALSE_NO_WARNING
#define KG_CHECK_ERROR(Condition) \
do \
{ \
if (!(Condition)) \
{ \
} \
} WHILE_FALSE_NO_WARNING
#define KG_COM_CHECK_ERROR(Condition) \
do \
{ \
if (FAILED(Condition)) \
{ \
} \
} WHILE_FALSE_NO_WARNING
#ifdef _DEBUG
#define KG_ASSERT_EXIT(Condition) \
do \
{ \
assert(Condition); \
if (!(Condition)) \
goto Exit0; \
} WHILE_FALSE_NO_WARNING
#else
#define KG_ASSERT_EXIT(Condition) \
do \
{ \
if (!(Condition)) \
goto Exit0; \
} WHILE_FALSE_NO_WARNING
#endif
#ifndef KG_HANDLE_DEFINED
#define KG_HANDLE_DEFINED
typedef void *KGHANDLE;
#endif // KG_HANDLE_DEFINED
#ifdef __GNUC__
#include <stdint.h>
#endif
#if _MSC_VER >= 1200 // >= VS 6.0
typedef __int8 int8_t;
typedef __int16 int16_t;
typedef __int32 int32_t;
typedef __int64 int64_t;
typedef unsigned __int8 uint8_t;
typedef unsigned __int16 uint16_t;
typedef unsigned __int32 uint32_t;
typedef unsigned __int64 uint64_t;
#if defined(_WIN64)
typedef __int64 intptr_t;
typedef unsigned __int64 uintptr_t;
#else
typedef _W64 __int32 intptr_t;
typedef _W64 unsigned __int32 uintptr_t;
#endif
#endif //_MSC_VER
#if _MSC_VER >= 1200 // >= VS 6.0
# define KG_LITTLE_ENDIAN 1234
# define KG_BIG_ENDIAN 4321
# define KG_PDP_ENDIAN 3412
# define KG_BYTE_ORDER KG_LITTLE_ENDIAN
#else
# include <endian.h>
# define KG_LITTLE_ENDIAN __LITTLE_ENDIAN
# define KG_BIG_ENDIAN __BIG_ENDIAN
# define KG_PDP_ENDIAN __PDP_ENDIAN
# define KG_BYTE_ORDER __BYTE_ORDER
#endif
#endif // _KGPUBLIC_H
|
zzengine
|
trunk/TinyLog/include/kingsoft/KGPublic.h
|
C
|
gpl3
| 5,981
|
#ifndef _I_TINY_LOG_H
#define _I_TINY_LOG_H
#include "TLBase.h"
#include "TLDefine.h"
struct ITinyLog
{
virtual int Release() = 0;
virtual int Log(TINY_LOG_PRIORITY Priority, const char* csClassify, const char fmt[], ...) = 0;
virtual int Log(TINY_LOG_PRIORITY Priority
, const char* csClassify /* classify for this message */
, const char* pcszCondition /* condition for logging */
, int nLine /* code line number */
, const char* pcszFunctionName /* function name which for logging*/
, const char* pcszInfo = NULL) = 0; /* additional infomation */
virtual TINY_LOG_PRIORITY SetPriority(TINY_LOG_PRIORITY priNew) = 0;
};
#ifndef PATH_COUNT
#define PATH_COUNT 256
#endif
struct TINY_LOG_PARAM
{
unsigned cbSize;
char szPath[PATH_COUNT];
TINY_LOG_OPTION Options;
int nVersionCreate;
};
enum eITLCode
{
eCreateITLSuccess = 0,
eCreateITLVersionError,
eCreateITLError,
eCreateITLInitError,
};
TLAPI eITLCode CreateTinyLog(TINY_LOG_PARAM* pParam, ITinyLog** ppi);
#ifdef WIN32
#define _FUNCTION __FUNCTION__
#else
#define _FUNCTION __PRETTY_FUNCTION__
#endif
#define LOG_CONDITION_ERROR(ptl, Condition) \
do \
{ \
if (!(Condition) && (ptl)) \
{ \
ptl->Log( \
eTinyLogPriorityError, \
GLOBAL_CLASSIFY_NAME, \
#Condition, \
__LINE__, \
_FUNCTION \
); \
goto Error; \
} \
} while (false)
#define LOG_CONDITION_SUCCESS(ptl, Condition) \
do \
{ \
if (Condition && (ptl)) \
{ \
ptl->Log( \
eTinyLogPriorityInfo, \
GLOBAL_CLASSIFY_NAME, \
#Condition, \
__LINE__, \
_FUNCTION \
); \
goto Success; \
} \
} while (false)
TLAPI int logS_Init(TINY_LOG_PARAM* pParam);
TLAPI int logS_Uninit();
TLAPI int logS_Log(TINY_LOG_PRIORITY Priority, const char* csClassify, const char fmt[], ...);
TLAPI int logS_Log(TINY_LOG_PRIORITY Priority
, const char* csClassify
, const char* pcszCondition
, int nLine
, const char* pcszFunctionName
, const char* pcszInfo = NULL);
#define LOGS_CONDITION_ERROR(Condition) \
do \
{ \
if (!(Condition)) \
{ \
logS_Log( \
eTinyLogPriorityError, \
GLOBAL_CLASSIFY_NAME, \
#Condition, \
__LINE__, \
_FUNCTION \
); \
goto Error; \
} \
} while (false)
#define LOGS_CONDITION_SUCCESS(Condition) \
do \
{ \
if (Condition) \
{ \
logS_Log( \
eTinyLogPriorityInfo, \
GLOBAL_CLASSIFY_NAME, \
#Condition, \
__LINE__, \
_FUNCTION \
); \
goto Success; \
} \
} while (false)
#endif //_I_TINY_LOG_H
|
zzengine
|
trunk/TinyLog/include/ITinyLog.h
|
C
|
gpl3
| 2,720
|
#ifndef _IE_TINY_LOG_H
#define _IE_TINY_LOG_H
#include "TLBase.h"
#include "TLDefine.h"
struct ETL_LOG_TIME /* value -1 is wildcard */
{
int nYear;
int nMonth;
int nDay;
int nHour;
int nMinuter;
int nSecond;
};
struct ETL_LOG
{
char BeginTag[3]; /* 0xFFF or 0xFFE */
ETL_LOG_TIME Time;
const char* pcszClassify;
TINY_LOG_PRIORITY Pri;
const char* pcszCondition;
int nLine;
const char* pcszFunctionName;
const char* pcszInfo;
};
struct ETL_FILE_INFO
{
char szFileName[FILE_NAME_LENGTH];
char szFilePath[FILE_PATH_LENGTH];
int nFileCount;
char szTag[8];
char szVersion[8];
time_t ttTime;
};
struct IETinyLog
{
virtual int Release() = 0;
virtual int LoadFromFile(const char* pcszFilePath) = 0;
virtual int LoadFromAssemble(const char* pcszName) = 0;
/*
if nCount == -1, return item counts
you can use this number to malloc memory to receive Logs
*/
virtual int SelectAll(ETL_LOG** pLogs, int nCount) = 0;
virtual int SelectItems(ETL_LOG* pKey, ETL_LOG** pLogs, int nCount) = 0;
virtual int GetFileInfo(ETL_FILE_INFO* pInfo, size_t uSize) = 0;
virtual const char* ToString(ETL_LOG* pLog) = 0;
};
enum eIETLCode
{
eCreateIETLSuccess = 0,
eCreateIETLError,
};
struct ETINY_LOG_PARAM
{
unsigned cbSize;
int nVersionCreate;
};
TLAPI eIETLCode CreateETinyLog(ETINY_LOG_PARAM* pParam, IETinyLog** ppi);
#endif
|
zzengine
|
trunk/TinyLog/include/IETinyLog.h
|
C
|
gpl3
| 1,429
|
#ifndef _TINY_LOG_BASE_H
#define _TINY_LOG_BASE_H
#ifdef __GNUC__
#define TLAPI
#define C_TLAPI extern "C"
#else
#ifdef BUILD_AS_DLL
#define TLAPI __declspec(dllexport)
#define C_TLAPI extern "C" __declspec(dllexport)
#else
#define TLAPI __declspec(dllimport)
#define C_TLAPI extern "C" __declspec(dllimport)
#endif
#endif
#define CONDITION_ERROR(Condition) \
do \
{ \
if (!(Condition)) \
goto Error; \
}while(false)
#define CONDITION_SUCCESS(Condition) \
do \
{ \
if (Condition) \
goto Success; \
}while(false)
#ifndef SAFE_FREE
#define SAFE_FREE(a) if (a) { free(a); (a) = null; }
#endif //SAFE_FREE
#ifndef SAFE_DELETE
#define SAFE_DELETE(a) if (a) { delete (a); (a) = null; }
#endif //SAFE_DELETE
#ifndef SAFE_RELEASE
#define SAFE_RELEASE(a) if (a) { (a)->Release(); (a) = null; }
#endif //SAFE_RELEASE
#endif //_TINY_LOG_BASE_H
|
zzengine
|
trunk/TinyLog/TinyLog/Src/Interface/TLBase.h
|
C
|
gpl3
| 914
|
#ifndef _TINY_LOG_DEFINE_H
#define _TINY_LOG_DEFINE_H
enum TINY_LOG_PRIORITY
{
eTinyLogPriorityReserve0 = 0,
eTinyLogPriorityReserve1 = 1,
eTinyLogPriorityReserve2 = 2,
eTinyLogPriorityError = 3,
eTinyLogPriorityReserve4 = 4,
eTinyLogPriorityWarning = 5,
eTinyLogPriorityReserve6 = 6,
eTinyLogPriorityInfo = 7,
eTinyLogPriorityReserve8 = 8,
eTinyLogPriorityDebug = 9,
eTinyLogPriorityReserve10 = 10,
eTinyLogPriorityCount
};
enum TINY_LOG_OPTION
{
eTinyLogOptionFile = 0x01,
eTinyLogOptionConsole = 0x01 << 1,
eTinyLogOptionStderr = 0x01 << 2,
};
#define GLOBAL_CLASSIFY_NAME "_Global"
struct TL_LOG_INFO
{
char BeginTag[3]; /* 0xFF; beginning of a log. 0xFFE for normal; 0xFFF for offset. */
char oftSecond[4]; /* offset; seconds passed from log begin */
char oftClassify[2]; /* offset; const char* pcszClassity */
char idxPriority; /* enum of TINY_LOG_PRIORITY; */
char oftCondition[2]; /* offset; const char* pcszCondition */
char nLine[4]; /* int; code line number */
char oftFunctionName[2];/* offset; const char* pcszFunctionName */
char oftInfo[2]; /* offset; const char* pcszAdditionInfo */
}; /* 20 bytes total */
typedef unsigned long FOURCC;
#define TLOG_TAG 'TLOG'
#define VERSION0 'V000'
struct TL_RUNTIME_PATTERN
{
unsigned cbSize;
FOURCC fccTag; /* 'TLOG' */
FOURCC fccVersion; /* 'V000' newest */
time_t ttTimeStamp;
};
#define FILE_NAME_LENGTH 32
#define FILE_PATH_LENGTH 256
#define MAX_FILE_LENGTH (1 << 16)
#endif //_TINY_LOG_DEFINE_H
|
zzengine
|
trunk/TinyLog/TinyLog/Src/Interface/TLDefine.h
|
C
|
gpl3
| 1,567
|
#ifndef _I_TINY_LOG_H
#define _I_TINY_LOG_H
#include "TLBase.h"
#include "TLDefine.h"
struct ITinyLog
{
virtual int Release() = 0;
virtual int Log(TINY_LOG_PRIORITY Priority, const char* csClassify, const char fmt[], ...) = 0;
virtual int Log(TINY_LOG_PRIORITY Priority
, const char* csClassify /* classify for this message */
, const char* pcszCondition /* condition for logging */
, int nLine /* code line number */
, const char* pcszFunctionName /* function name which for logging*/
, const char* pcszInfo = NULL) = 0; /* additional infomation */
virtual TINY_LOG_PRIORITY SetPriority(TINY_LOG_PRIORITY priNew) = 0;
};
#ifndef PATH_COUNT
#define PATH_COUNT 256
#endif
struct TINY_LOG_PARAM
{
unsigned cbSize;
char szPath[PATH_COUNT];
TINY_LOG_OPTION Options;
int nVersionCreate;
};
enum eITLCode
{
eCreateITLSuccess = 0,
eCreateITLVersionError,
eCreateITLError,
eCreateITLInitError,
};
TLAPI eITLCode CreateTinyLog(TINY_LOG_PARAM* pParam, ITinyLog** ppi);
#ifdef WIN32
#define _FUNCTION __FUNCTION__
#else
#define _FUNCTION __PRETTY_FUNCTION__
#endif
#define LOG_CONDITION_ERROR(ptl, Condition) \
do \
{ \
if (!(Condition) && (ptl)) \
{ \
ptl->Log( \
eTinyLogPriorityError, \
GLOBAL_CLASSIFY_NAME, \
#Condition, \
__LINE__, \
_FUNCTION \
); \
goto Error; \
} \
} while (false)
#define LOG_CONDITION_SUCCESS(ptl, Condition) \
do \
{ \
if (Condition && (ptl)) \
{ \
ptl->Log( \
eTinyLogPriorityInfo, \
GLOBAL_CLASSIFY_NAME, \
#Condition, \
__LINE__, \
_FUNCTION \
); \
goto Success; \
} \
} while (false)
TLAPI int logS_Init(TINY_LOG_PARAM* pParam);
TLAPI int logS_Uninit();
TLAPI int logS_Log(TINY_LOG_PRIORITY Priority, const char* csClassify, const char fmt[], ...);
TLAPI int logS_Log(TINY_LOG_PRIORITY Priority
, const char* csClassify
, const char* pcszCondition
, int nLine
, const char* pcszFunctionName
, const char* pcszInfo = NULL);
#define LOGS_CONDITION_ERROR(Condition) \
do \
{ \
if (!(Condition)) \
{ \
logS_Log( \
eTinyLogPriorityError, \
GLOBAL_CLASSIFY_NAME, \
#Condition, \
__LINE__, \
_FUNCTION \
); \
goto Error; \
} \
} while (false)
#define LOGS_CONDITION_SUCCESS(Condition) \
do \
{ \
if (Condition) \
{ \
logS_Log( \
eTinyLogPriorityInfo, \
GLOBAL_CLASSIFY_NAME, \
#Condition, \
__LINE__, \
_FUNCTION \
); \
goto Success; \
} \
} while (false)
#endif //_I_TINY_LOG_H
|
zzengine
|
trunk/TinyLog/TinyLog/Src/Interface/ITinyLog.h
|
C
|
gpl3
| 2,720
|
#ifndef _IE_TINY_LOG_H
#define _IE_TINY_LOG_H
#include "TLBase.h"
#include "TLDefine.h"
struct ETL_LOG_TIME /* value -1 is wildcard */
{
int nYear;
int nMonth;
int nDay;
int nHour;
int nMinuter;
int nSecond;
};
struct ETL_LOG
{
char BeginTag[3]; /* 0xFFF or 0xFFE */
ETL_LOG_TIME Time;
const char* pcszClassify;
TINY_LOG_PRIORITY Pri;
const char* pcszCondition;
int nLine;
const char* pcszFunctionName;
const char* pcszInfo;
};
struct ETL_FILE_INFO
{
char szFileName[FILE_NAME_LENGTH];
char szFilePath[FILE_PATH_LENGTH];
int nFileCount;
char szTag[8];
char szVersion[8];
time_t ttTime;
};
struct IETinyLog
{
virtual int Release() = 0;
virtual int LoadFromFile(const char* pcszFilePath) = 0;
virtual int LoadFromAssemble(const char* pcszName) = 0;
/*
if nCount == -1, return item counts
you can use this number to malloc memory to receive Logs
*/
virtual int SelectAll(ETL_LOG** pLogs, int nCount) = 0;
virtual int SelectItems(ETL_LOG* pKey, ETL_LOG** pLogs, int nCount) = 0;
virtual int GetFileInfo(ETL_FILE_INFO* pInfo, size_t uSize) = 0;
virtual const char* ToString(ETL_LOG* pLog) = 0;
};
enum eIETLCode
{
eCreateIETLSuccess = 0,
eCreateIETLError,
};
struct ETINY_LOG_PARAM
{
unsigned cbSize;
int nVersionCreate;
};
TLAPI eIETLCode CreateETinyLog(ETINY_LOG_PARAM* pParam, IETinyLog** ppi);
#endif
|
zzengine
|
trunk/TinyLog/TinyLog/Src/Interface/IETinyLog.h
|
C
|
gpl3
| 1,429
|
#ifndef _TINY_LOG_EDIT_H
#define _TINY_LOG_EDIT_H
#include "Interface/IETinyLog.h"
typedef std::vector<ETL_LOG> LogVector;
typedef LogVector::iterator LogVectorPtr;
typedef std::vector<void*> BufferVector;
typedef BufferVector::iterator BufferVectorPtr;
class TinyLogE : public IETinyLog
{
public:
TinyLogE();
virtual ~TinyLogE();
public:
int Release();
int LoadFromFile(const char* pcszFilePath);
int LoadFromAssemble(const char* pcszName);
int SelectAll(ETL_LOG** pLogs, int nCount);
int SelectItems(ETL_LOG* pKey, ETL_LOG** pLogs, int nCount);
int GetFileInfo(ETL_FILE_INFO* pInfo, size_t uSize);
const char* ToString(ETL_LOG* pLog);
private:
ETL_FILE_INFO m_FileInfo;
LogVector m_Logs;
BufferVector m_Buffers;
char m_szStr[MAX_FILE_LENGTH];
private:
int Reset();
int GetItemCount(ETL_LOG* pKey);
int GetFileInfo(const char* pcszFile);
int NextFile(int nFile); /* return -1 means end. 0 for Error. file index for else. */
int AppendLogs(char* pBuffer, int nSize);
};
#endif //_TINY_LOG_EDIT_H
|
zzengine
|
trunk/TinyLog/TinyLog/Src/TinyLogE.h
|
C++
|
gpl3
| 1,078
|
#include "stdafx.h"
#include "ntype.h"
#include "memory.h"
struct TL_MEMORY_UNIT
{
TL_MEMORY_UNIT* pNext;
uint32 uCapacity;
uint32 uOffset;
char* pBuffer;
};
struct TL_MEMORY
{
uint32 cbSize;
TL_MEMORY_UNIT* pPool;
};
#define CAPACITY_SIZE 128
memS_t memS_create()
{
TL_MEMORY* ptlMem = (TL_MEMORY*)malloc(sizeof(TL_MEMORY));
assert(ptlMem);
ptlMem->cbSize = sizeof(TL_MEMORY);
ptlMem->pPool = (TL_MEMORY_UNIT*)malloc(sizeof(TL_MEMORY_UNIT) + CAPACITY_SIZE);
assert(ptlMem->pPool);
TL_MEMORY_UNIT* pPool = ptlMem->pPool;
pPool->pNext = NULL;
pPool->uCapacity = CAPACITY_SIZE;
pPool->uOffset = 0;
pPool->pBuffer = (char*)(ptlMem->pPool + 1);
return ptlMem;
}
void memS_destroy(memS_t t)
{
assert(t);
assert(t->cbSize == sizeof(TL_MEMORY));
TL_MEMORY_UNIT* ptlMem = t->pPool;
TL_MEMORY_UNIT* ptlTmp = NULL;
while (ptlMem)
{
ptlTmp = ptlMem->pNext;
free(ptlMem);
ptlMem = ptlTmp;
}
free(t);
t = NULL;
}
void* memS_alloc(memS_t t, int nSize)
{
assert(t);
assert(t->cbSize == sizeof(TL_MEMORY));
assert(nSize > 0);
TL_MEMORY_UNIT* ptlMem = t->pPool;
uint32 uSize = (uint32)nSize;
char* pBuffer = NULL;
if (uSize <= ptlMem->uCapacity - ptlMem->uOffset)
{
pBuffer = ptlMem->pBuffer + ptlMem->uOffset;
ptlMem->uOffset += uSize;
return pBuffer;
}
else
{
uint32 uNewSize = (ptlMem->uCapacity + uSize) << 1;
TL_MEMORY_UNIT* ptlNew = (TL_MEMORY_UNIT*)malloc(sizeof(TL_MEMORY_UNIT) + uNewSize);
assert(ptlNew);
ptlNew->uCapacity = uNewSize;
ptlNew->uOffset = 0;
ptlNew->pBuffer = (char*)(ptlNew + 1);
ptlNew->pNext = ptlMem;
t->pPool = ptlNew;
return memS_alloc(t, nSize);
}
}
|
zzengine
|
trunk/TinyLog/TinyLog/Src/Common/memory.cpp
|
C++
|
gpl3
| 1,730
|
#ifndef _TINY_LOG_MEMORY_H
#define _TINY_LOG_MEMORY_H
#include "ntype.h"
typedef struct TL_MEMORY *memS_t;
memS_t memS_create();
void memS_destroy(memS_t t);
void* memS_alloc(memS_t t, int nSize);
#endif //_TINY_LOG_MEMORY_H
|
zzengine
|
trunk/TinyLog/TinyLog/Src/Common/memory.h
|
C
|
gpl3
| 239
|
#include "stdafx.h"
#include "atom.h"
#include "hash.h"
#include "memory.h"
#define BUCKET_COUNT 2048
struct TL_ATOM_UNIT
{
TL_ATOM_UNIT* pNext;
uint32 uLen;
char* pStr;
};
struct TL_ATOM
{
uint32 cbSize;
memS_t memST;
TL_ATOM_UNIT* pBuckets[BUCKET_COUNT];
};
atom_t atom_create()
{
TL_ATOM* pAtom = (TL_ATOM*)malloc(sizeof(TL_ATOM));
assert(pAtom);
pAtom->cbSize = sizeof(TL_ATOM);
pAtom->memST = memS_create();
assert(pAtom->memST);
memset(pAtom->pBuckets, 0, sizeof(TL_ATOM_UNIT*) * BUCKET_COUNT);
return pAtom;
}
void atom_destroy(atom_t t)
{
assert(t);
assert(t->cbSize == sizeof(TL_ATOM));
memS_destroy(t->memST);
free(t);
}
c_str atom_new(atom_t t, c_str cstr, uint32 uLen)
{
assert(t);
assert(t->cbSize == sizeof(TL_ATOM));
assert(cstr);
uint32 uPos = hash_string(cstr, uLen);
uPos &= NELEMS(t->pBuckets) - 1;
TL_ATOM_UNIT* pAtomUnit = NULL;
uint32 uIndex = 0;
for (pAtomUnit = t->pBuckets[uPos]; pAtomUnit; pAtomUnit = pAtomUnit->pNext)
{
if (uLen == pAtomUnit->uLen)
{
uIndex = 0;
while (uIndex <= uLen && pAtomUnit->pStr[uIndex] == cstr[uIndex])
++uIndex;
if (uIndex == uLen + 1)
return pAtomUnit->pStr;
}
}
pAtomUnit = (TL_ATOM_UNIT*)memS_alloc(t->memST, sizeof(TL_ATOM_UNIT) + uLen + 1);
assert(pAtomUnit);
pAtomUnit->uLen = uLen;
pAtomUnit->pStr = (char*)(pAtomUnit + 1);
pAtomUnit->pNext = t->pBuckets[uPos];
memcpy(pAtomUnit->pStr, cstr, uLen + 1);
t->pBuckets[uPos] = pAtomUnit;
return pAtomUnit->pStr;
}
c_str atom_string(atom_t t, c_str cstr)
{
assert(t);
assert(t->cbSize == sizeof(TL_ATOM));
assert(cstr);
return atom_new(t, cstr, strlen(cstr));
}
|
zzengine
|
trunk/TinyLog/TinyLog/Src/Common/atom.cpp
|
C++
|
gpl3
| 1,729
|
#include "stdafx.h"
#include "hash.h"
uint32 hash_string(c_str cstr, uint32 uLen)
{
unsigned int uValue = 0;
unsigned int nSeed = 4;
if (cstr)
{
while (uLen --)
{
uValue ^= ((uValue & 0x3F) + nSeed) * (*cstr++) + (uValue << 8);
nSeed += 3;
}
}
return uValue;
}
|
zzengine
|
trunk/TinyLog/TinyLog/Src/Common/hash.cpp
|
C++
|
gpl3
| 295
|
#ifndef _TINY_LOG_CRT_H
#define _TINY_LOG_CRT_H
#if (defined(_MSC_VER) || defined(__ICL)) //window platform
#include <direct.h>
#include <io.h>
#else
#include <pthread.h>
#endif
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <fcntl.h>
#include <map>
#include <vector>
#define NELEMS(x) (sizeof((x))/(sizeof(((x)[0]))))
#endif //_TINY_LOG_CRT_H
|
zzengine
|
trunk/TinyLog/TinyLog/Src/Common/crt.h
|
C++
|
gpl3
| 498
|
#ifndef _TINY_LOG_COMMON_H
#define _TINY_LOG_COMMON_H
#include "ntype.h"
#define null 0
inline uint32 RandNumber()
{
static uint32 s_uNumber = (uint32)time(NULL);
s_uNumber = s_uNumber * 214013L + 2531011L;
return s_uNumber;
}
#if (defined(_MSC_VER) || defined(__ICL))
#define mkdir _mkdir
#else
inline int32 mkdir(c_str cszDir[])
{
return mkdir(cszDir, 0777);
}
#endif
inline void ToLower(pstr psz)
{
for (pstr pc = psz; *pc; ++pc)
{
if ((*pc) >= 'A' && (*pc) <= 'Z')
*pc = *pc + ('a' - 'A');
}
}
inline bool IsFileExist(const char* pcszFileName)
{
#ifdef WIN32
return !(GetFileAttributesA(pcszFileName) & FILE_ATTRIBUTE_DIRECTORY);
#else
int nFile = _sopen(pcszFileName, _O_BINARY, _SH_DENYNO, 0);
if (nFile != -1)
{
_close(nFile);
return true;
}
return false;
#endif
}
inline size_t GetFileSize(FILE* pFile)
{
size_t uLen = 0;
fseek(pFile, 0, SEEK_END);
uLen = ftell(pFile);
rewind(pFile);
return uLen;
}
#ifndef PATH_COUNT
#define PATH_COUNT 256
#endif
#include <assert.h>
#ifndef ASSERT
#define ASSERT assert
#endif
#endif //_TINY_LOG_COMMON_H
|
zzengine
|
trunk/TinyLog/TinyLog/Src/Common/common.h
|
C
|
gpl3
| 1,152
|
#ifndef _TINY_LOG_HASH_H
#define _TINY_LOG_HASH_H
#include "ntype.h"
uint32 hash_string(c_str cstr, uint32 uLen);
#endif //_TINY_LOG_HASH_H
|
zzengine
|
trunk/TinyLog/TinyLog/Src/Common/hash.h
|
C
|
gpl3
| 149
|
#ifndef _TINY_LOG_NTYPE_H
#define _TINY_LOG_NTYPE_H
#include <sys/types.h>
typedef int int32;
typedef unsigned int uint32;
typedef const char* c_str;
typedef char* pstr;
typedef c_str pcstr;
#endif //_TINY_LOG_NTYPE_H
|
zzengine
|
trunk/TinyLog/TinyLog/Src/Common/ntype.h
|
C
|
gpl3
| 233
|
#ifndef _TINY_LOG_ATOM_H
#define _TINY_LOG_ATOM_H
#include "ntype.h"
typedef struct TL_ATOM *atom_t;
atom_t atom_create();
void atom_destroy(atom_t t);
c_str atom_new(atom_t t, c_str cstr, uint32 uLen);
c_str atom_string(atom_t t, c_str cstr);
#endif //_TINY_LOG_ATOM_H
|
zzengine
|
trunk/TinyLog/TinyLog/Src/Common/atom.h
|
C
|
gpl3
| 285
|
#include "stdafx.h"
#include "TinyLogE.h"
static char s_PriorityName[][16] = {
"",
"",
"",
"Error",
"",
"Warning",
"",
"Info",
"",
"Debug",
"",
};
static bool IsEqual(ETL_LOG* pLog, ETL_LOG* pKey)
{
bool bRet = false;
if (pKey->BeginTag[0] != -1)
{
bRet = pLog->BeginTag[0] == pKey->BeginTag[0] &&
pLog->BeginTag[1] == pKey->BeginTag[1] &&
pLog->BeginTag[2] == pKey->BeginTag[2];
if (!bRet)
return bRet;
}
if ((INT_PTR)pKey->pcszClassify != -1 && pLog->pcszClassify)
{
bRet = strcmp(pKey->pcszClassify, pLog->pcszClassify) == 0;
if (!bRet)
return bRet;
}
if (pKey->Pri != -1)
{
bRet = pKey->Pri == pLog->Pri;
if (!bRet)
return bRet;
}
if ((INT_PTR)pKey->pcszCondition != -1 && pLog->pcszCondition)
{
bRet = strcmp(pKey->pcszCondition, pLog->pcszCondition) == 0;
if (!bRet)
return bRet;
}
if (pKey->nLine != -1)
{
bRet = pKey->nLine == pLog->nLine;
if (!bRet)
return bRet;
}
if ((INT_PTR)pKey->pcszFunctionName != -1 && pLog->pcszFunctionName)
{
bRet = strcmp(pKey->pcszFunctionName, pLog->pcszFunctionName) == 0;
if (!bRet)
return bRet;
}
if ((INT_PTR)pKey->pcszInfo != -1 && pLog->pcszInfo)
{
bRet = strcmp(pKey->pcszInfo, pLog->pcszInfo) == 0;
if (!bRet)
return bRet;
}
return true;
}
TinyLogE::TinyLogE()
{
Reset();
}
TinyLogE::~TinyLogE()
{
Reset();
}
int TinyLogE::Release()
{
delete this;
return true;
}
int TinyLogE::LoadFromFile(const char* pcszFilePath)
{
int nRetCode = false;
int nResult = false;
int nFile = 0;
CONDITION_ERROR(pcszFilePath);
nRetCode = IsFileExist(pcszFilePath);
CONDITION_ERROR(nRetCode);
nRetCode = GetFileInfo(pcszFilePath);
CONDITION_ERROR(nRetCode);
while (true)
{
nFile = NextFile(nFile);
CONDITION_ERROR(nFile != 0);
if (nFile == -1)
break;
m_FileInfo.nFileCount++;
}
nResult = true;
Error:
return nResult;
}
int TinyLogE::LoadFromAssemble(const char* pcszName)
{
int nRetCode = false;
int nResult = false;
CONDITION_ERROR(pcszName);
nResult = true;
Error:
return nResult;
}
int TinyLogE::SelectAll(ETL_LOG** pLogs, int nCount)
{
if (nCount == -1)
{
ETL_LOG LogKey;
memset(&LogKey, -1, sizeof(LogKey));
return GetItemCount(&LogKey);
}
int nRetCode = false;
int nResult = false;
int nIndex = 0;
ETL_LOG** pLog = NULL;
CONDITION_ERROR(pLogs);
CONDITION_ERROR(nCount > 0);
pLog = pLogs;
for (LogVectorPtr ptr = m_Logs.begin(); ptr != m_Logs.end(); ++ptr, ++nIndex)
{
if (nIndex >= nCount)
break;
*pLog = &(*ptr);
pLog++;
}
nResult = true;
Error:
return nResult;
}
int TinyLogE::SelectItems(ETL_LOG* pKey, ETL_LOG** pLogs, int nCount)
{
if (pKey && nCount == -1)
return GetItemCount(pKey);
int nRetCode = false;
int nResult = false;
int nIndex = 0;
ETL_LOG** pLog = NULL;
CONDITION_ERROR(pKey);
CONDITION_ERROR(pLogs);
CONDITION_ERROR(nCount > 0);
pLog = pLogs;
for (LogVectorPtr ptr = m_Logs.begin(); ptr != m_Logs.end(); ++ptr)
{
if (nIndex >= nCount)
break;
if (IsEqual(&(*ptr), pKey))
{
*pLog = &(*ptr);
pLog++;
nIndex++;
}
}
nResult = true;
Error:
return nResult;
}
int TinyLogE::GetFileInfo(ETL_FILE_INFO* pInfo, size_t uSize)
{
int nResult = false;
CONDITION_ERROR(pInfo);
CONDITION_ERROR(uSize == sizeof(ETL_FILE_INFO));
memcpy(pInfo, &m_FileInfo, uSize);
nResult = true;
Error:
return nResult;
}
const char* TinyLogE::ToString(ETL_LOG* pLog)
{
int nRetCode = false;
int nResult = false;
CONDITION_ERROR(pLog);
m_szStr[0] = '\0';
_snprintf(m_szStr, sizeof(m_szStr) - 1,
"[%d-%2.2d-%2.2d %2.2d:%2.2d:%2.2d][%s] %s: Condition(%s) at line(%d) in function(%s). Info: %s.\r\n",
pLog->Time.nYear, pLog->Time.nMonth, pLog->Time.nDay,
pLog->Time.nHour, pLog->Time.nMinuter, pLog->Time.nSecond,
pLog->pcszClassify, s_PriorityName[pLog->Pri],
pLog->pcszCondition, pLog->nLine,
pLog->pcszFunctionName, pLog->pcszInfo);
nResult = true;
Error:
return m_szStr;
}
int TinyLogE::Reset()
{
int nRetCode = false;
int nResult = false;
m_Logs.clear();
for (BufferVectorPtr ptr = m_Buffers.begin(); ptr != m_Buffers.end(); ++ptr)
{
SAFE_FREE(*ptr);
}
m_Buffers.clear();
nResult = true;
//Error:
return nResult;
}
int TinyLogE::GetItemCount(ETL_LOG* pKey)
{
int nRetCode = false;
int nResult = false;
int nCount = 0;
CONDITION_ERROR(pKey);
for (LogVectorPtr ptr = m_Logs.begin(); ptr != m_Logs.end(); ++ptr)
{
ETL_LOG* pLog = &(*ptr);
if (IsEqual(pLog, pKey))
nCount++;
}
nResult = true;
Error:
return nCount;
}
int TinyLogE::GetFileInfo(const char* pcszFile)
{
int nRetCode = false;
int nResult = false;
int nIndex = 0;
char szFile[FILE_PATH_LENGTH];
m_FileInfo.szFileName[0] = '\0';
m_FileInfo.szFilePath[0] = '\0';
m_FileInfo.nFileCount = 0;
m_FileInfo.szTag[0] = '\0';
m_FileInfo.szVersion[0] = '\0';
m_FileInfo.ttTime = 0;
nIndex = (int)strlen(pcszFile) - 1;
CONDITION_ERROR(nIndex > (int)strlen(".tlog") + (int)strlen("1900_01_01_01_01_01(part)"));
strcpy_s(szFile, sizeof(szFile), pcszFile);
for (; nIndex > 0; --nIndex)
{
if (szFile[nIndex] == '(')
szFile[nIndex] = '\0';
if (szFile[nIndex] == '\\' || szFile[nIndex] == '/')
{
szFile[nIndex] = '\0';
++nIndex;
break;
}
}
strcpy_s(m_FileInfo.szFileName, sizeof(m_FileInfo.szFileName), &szFile[nIndex]);
strcpy_s(m_FileInfo.szFilePath, sizeof(m_FileInfo.szFilePath), szFile);
nResult = true;
Error:
return nResult;
}
int TinyLogE::NextFile(int nFile)
{
int nRetCode = false;
int nResult = false;
char szFile[FILE_PATH_LENGTH];
FILE* pFile = NULL;
size_t uFileSize = 0;
TL_RUNTIME_PATTERN* pTL = NULL;
void* pBuffer = NULL;
_snprintf(szFile, sizeof(szFile) - 1, "%s/%s(part%d).tlog"
, m_FileInfo.szFilePath, m_FileInfo.szFileName, nFile);
szFile[sizeof(szFile) - 1] = '\0';
nRetCode = IsFileExist(szFile);
if (!nRetCode)
{
nResult = -1;
goto Error;
}
pFile = fopen(szFile, "rb");
CONDITION_ERROR(pFile);
uFileSize = GetFileSize(pFile);
CONDITION_ERROR(uFileSize > sizeof(TL_RUNTIME_PATTERN));
pBuffer = malloc(uFileSize);
CONDITION_ERROR(pBuffer);
m_Buffers.push_back(pBuffer);
nRetCode = (int)fread(pBuffer, 1, uFileSize, pFile);
CONDITION_ERROR(nRetCode == uFileSize);
pTL = (TL_RUNTIME_PATTERN*)pBuffer;
CONDITION_ERROR(pTL->fccTag == TLOG_TAG);
*(FOURCC*)(LONG_PTR)m_FileInfo.szTag = pTL->fccTag;
m_FileInfo.szTag[sizeof(FOURCC)] = '\0';
*(FOURCC*)(LONG_PTR)m_FileInfo.szVersion = pTL->fccVersion;
m_FileInfo.szVersion[sizeof(FOURCC)] = '\0';
m_FileInfo.ttTime = pTL->ttTimeStamp;
nRetCode = AppendLogs((char*)pBuffer, (int)uFileSize);
CONDITION_ERROR(nRetCode);
nResult = nFile + 1;
Error:
if (pFile)
{
fclose(pFile);
pFile = NULL;
}
return nResult;
}
int TinyLogE::AppendLogs(char* pBuffer, int nSize)
{
int nRetCode = false;
int nResult = false;
int nIndex = 0;
CONDITION_ERROR(pBuffer);
while (nIndex < nSize - 3)
{
if (pBuffer[nIndex] == 0xF && pBuffer[nIndex + 1] == 0xF)
{
ETL_LOG eLog;
TL_LOG_INFO* pLog = (TL_LOG_INFO*)(&pBuffer[nIndex]);
time_t tt = m_FileInfo.ttTime;
struct tm* ptm;
unsigned short usOffset;
memset(&eLog, 0, sizeof(eLog));
eLog.BeginTag[0] = pLog->BeginTag[0];
eLog.BeginTag[1] = pLog->BeginTag[1];
eLog.BeginTag[2] = pLog->BeginTag[2];
tt += *(int*)(pLog->oftSecond);
ptm = localtime(&tt);
eLog.Time.nYear = ptm->tm_year + 1900;
eLog.Time.nMonth = ptm->tm_mon + 1;
eLog.Time.nDay = ptm->tm_mday;
eLog.Time.nHour = ptm->tm_hour;
eLog.Time.nMinuter = ptm->tm_min;
eLog.Time.nSecond = ptm->tm_sec;
if (pLog->BeginTag[2] == 0xF)
{
usOffset = *(unsigned short*)pLog->oftClassify;
CONDITION_ERROR(usOffset < nSize);
pLog = (TL_LOG_INFO*)(pBuffer + usOffset);
}
usOffset = *(unsigned short*)pLog->oftClassify;
if (usOffset)
eLog.pcszClassify = (const char*)(pBuffer + usOffset);
eLog.Pri = (TINY_LOG_PRIORITY)pLog->idxPriority;
usOffset = *(unsigned short*)pLog->oftCondition;
if (usOffset)
eLog.pcszCondition = (const char*)(pBuffer + usOffset);
eLog.nLine = *(int*)(pLog->nLine);
usOffset = *(unsigned short*)pLog->oftFunctionName;
if (usOffset)
eLog.pcszFunctionName = (const char*)(pBuffer + usOffset);
usOffset = *(unsigned short*)pLog->oftInfo;
if (usOffset)
eLog.pcszInfo = (const char*)(pBuffer + usOffset);
m_Logs.push_back(eLog);
nIndex += 2;
}
++nIndex;
}
nResult = true;
Error:
return nResult;
}
TLAPI eIETLCode CreateETinyLog(ETINY_LOG_PARAM* pParam, IETinyLog** ppi)
{
eIETLCode eRet = eCreateIETLError;
TinyLogE* pTinyLogE = NULL;
CONDITION_ERROR(pParam);
CONDITION_ERROR(ppi);
CONDITION_ERROR(pParam->cbSize == sizeof(ETINY_LOG_PARAM));
pTinyLogE = new TinyLogE();
CONDITION_ERROR(pTinyLogE);
*ppi = static_cast<IETinyLog*>(pTinyLogE);
Error:
return eRet;
}
|
zzengine
|
trunk/TinyLog/TinyLog/Src/TinyLogE.cpp
|
C++
|
gpl3
| 9,311
|
#ifndef _TINY_LOG_H
#define _TINY_LOG_H
#include "Interface/ITinyLog.h"
#include "Common/atom.h"
typedef std::map<c_str, short> TLOffsetMap;
typedef TLOffsetMap::iterator TLOffsetMapPtr;
class TinyLog : public ITinyLog
{
public:
TinyLog();
virtual ~TinyLog();
public:
int Release();
int Log(TINY_LOG_PRIORITY Priority, const char* csClassify, const char fmt[], ...);
int Log(TINY_LOG_PRIORITY Priority
, const char* csClassify
, const char* pcszCondition
, int nLine
, const char* pcszFunctionName
, const char* pcszInfo /* = NULL */);
TINY_LOG_PRIORITY SetPriority(TINY_LOG_PRIORITY priNew);
public:
int Init(TINY_LOG_PARAM* pParam);
private:
atom_t m_atLogs;
atom_t m_atStrings;
TLOffsetMap m_LogMap;
TLOffsetMap m_StringMap;
TINY_LOG_PARAM m_Param;
int m_nIndex;
char m_szFileName[FILE_NAME_LENGTH];
char m_szFilePath[FILE_PATH_LENGTH];
int m_nFileHandle;
TINY_LOG_PRIORITY m_CurrentPriority; //Todo: share memory
TL_RUNTIME_PATTERN m_RTPattern;
unsigned short m_usOffset;
unsigned short m_usBufferOffset;
char m_szBuffer[MAX_FILE_LENGTH];
#ifdef WIN32
CRITICAL_SECTION m_CriticalSection;
void Lock() { EnterCriticalSection(&m_CriticalSection); }
void Unlock() { LeaveCriticalSection(&m_CriticalSection); }
#else
pthread_mutex_t m_Mutex;
void Lock() { pthread_mutex_lock(&m_Mutex); }
void Unlock() { pthread_mutex_unlock(&m_Mutex); }
#endif
private:
void Reset();
int NextLogFile();
int AddString(const char* pcszStr, unsigned short* pusRet);
};
#endif //_TINY_LOG_H
|
zzengine
|
trunk/TinyLog/TinyLog/Src/TinyLog.h
|
C++
|
gpl3
| 1,607
|
#include "stdafx.h"
#include "TinyLog.h"
#define TLOG_OPENFILEFLAG (O_CREAT | O_APPEND | O_WRONLY | O_TRUNC | O_BINARY)
#define TLOG_OPENFILEMODE (S_IREAD | S_IWRITE)
TinyLog::TinyLog()
: m_atLogs(NULL)
, m_atStrings(NULL)
, m_nIndex(0)
, m_nFileHandle(-1)
, m_usOffset(0)
, m_usBufferOffset(0)
{
Reset();
memset(&m_Param, 0, sizeof(m_Param));
m_szFileName[0] = '\0';
m_szFilePath[0] = '\0';
m_CurrentPriority = eTinyLogPriorityCount;
m_RTPattern.cbSize = sizeof(m_RTPattern);
m_RTPattern.fccTag = TLOG_TAG;
m_RTPattern.fccVersion = VERSION0;
m_RTPattern.ttTimeStamp = 0;
#ifdef WIN32
InitializeCriticalSection(&m_CriticalSection);
#else
pthread_mutex_init(&m_Mutex, NULL);
#endif
}
TinyLog::~TinyLog()
{
#ifdef WIN32
DeleteCriticalSection(&m_CriticalSection);
#else
pthread_mutex_destroy(&m_Mutex);
#endif
if (m_atLogs)
{
atom_destroy(m_atLogs);
m_atLogs = NULL;
}
if (m_atStrings)
{
atom_destroy(m_atStrings);
m_atStrings = NULL;
}
m_LogMap.clear();
m_StringMap.clear();
}
int TinyLog::Release()
{
delete this;
return 0;
}
int TinyLog::Log(TINY_LOG_PRIORITY Priority, const char* csClassify, const char fmt[], ...)
{
int nRetCode = false;
int nResult = false;
char szBuffer[1024];
va_list marker;
CONDITION_SUCCESS(Priority > m_CurrentPriority);
va_start(marker, fmt);
nRetCode = vsnprintf(szBuffer, sizeof(szBuffer) - 1, fmt, marker);
va_end(marker);
szBuffer[sizeof(szBuffer) - 1] = '\0';
nRetCode = Log(Priority, csClassify, NULL, -1, NULL, szBuffer);
CONDITION_ERROR(nRetCode);
Success:
nResult = true;
Error:
return nResult;
}
int TinyLog::Log(TINY_LOG_PRIORITY Priority
, const char* csClassify
, const char* pcszCondition
, int nLine
, const char* pcszFunctionName
, const char* pcszInfo)
{
int nRetCode = false;
int nResult = false;
size_t nMaxCount = 0;
time_t ttNow = 0;
TL_LOG_INFO tlLog = { 0 };
c_str cstr = NULL;
TLOffsetMapPtr ptr;
CONDITION_SUCCESS(Priority > m_CurrentPriority);
if (csClassify)
nMaxCount += strlen(csClassify) + 1;
if (pcszCondition)
nMaxCount += strlen(pcszCondition) + 1;
if (pcszFunctionName)
nMaxCount += strlen(pcszFunctionName) + 1;
if (pcszInfo)
nMaxCount += strlen(pcszInfo) + 1;
nMaxCount += sizeof(TL_LOG_INFO);
CONDITION_ERROR(nMaxCount < MAX_FILE_LENGTH - sizeof(TL_RUNTIME_PATTERN));
if (nMaxCount > MAX_FILE_LENGTH - m_usOffset)
{
nRetCode = NextLogFile();
CONDITION_ERROR(nRetCode);
}
ttNow = time(NULL);
tlLog.BeginTag[0] = 0xF;
tlLog.BeginTag[1] = 0xF;
*(int*)tlLog.oftSecond = (int)(ttNow - m_RTPattern.ttTimeStamp);
m_usBufferOffset = 0;
Lock();
nRetCode = AddString(csClassify, (unsigned short*)(tlLog.oftClassify));
CONDITION_ERROR(nRetCode);
nRetCode = AddString(pcszCondition, (unsigned short*)(tlLog.oftCondition));
CONDITION_ERROR(nRetCode);
*(int*)tlLog.nLine = nLine;
tlLog.idxPriority = (char)Priority;
nRetCode = AddString(pcszFunctionName, (unsigned short*)(tlLog.oftFunctionName));
CONDITION_ERROR(nRetCode);
nRetCode = AddString(pcszInfo, (unsigned short*)(tlLog.oftInfo));
CONDITION_ERROR(nRetCode);
cstr = atom_new(m_atLogs, tlLog.oftClassify
, (uint32)sizeof(TL_LOG_INFO) - (tlLog.oftClassify - tlLog.BeginTag));
ptr = m_LogMap.find(cstr);
if (ptr != m_LogMap.end())
{
tlLog.BeginTag[2] = 0xF;
*(unsigned short*)tlLog.oftClassify = ptr->second;
unsigned int uBytes = &tlLog.idxPriority - tlLog.BeginTag;
nRetCode = _write(m_nFileHandle, &tlLog, uBytes);
CONDITION_ERROR(nRetCode == uBytes);
m_usOffset += nRetCode;
goto Success;
}
m_LogMap.insert(std::make_pair(cstr, m_usOffset));
tlLog.BeginTag[2] = 0xE;
nRetCode = _write(m_nFileHandle, &tlLog, sizeof(TL_LOG_INFO));
CONDITION_ERROR(nRetCode == sizeof(TL_LOG_INFO));
m_usOffset += nRetCode;
Success:
nResult = true;
Error:
Unlock();
return nResult;
}
int TinyLog::Init(TINY_LOG_PARAM* pParam)
{
int nRetCode = false;
int nResult = false;
time_t ttNow = 0;
struct tm* tmNow;
CONDITION_ERROR(pParam);
memcpy(&m_Param, pParam, sizeof(m_Param));
if (m_Param.Options == 0)
m_Param.Options = eTinyLogOptionFile;
m_Param.szPath[sizeof(m_Param.szPath) - 1] = '\0';
CONDITION_SUCCESS(m_Param.Options != eTinyLogOptionFile);
nRetCode = (int)strlen(m_Param.szPath);
CONDITION_ERROR(nRetCode < FILE_PATH_LENGTH);
if (m_Param.szPath[nRetCode - 1] == '\\')
m_Param.szPath[nRetCode - 1] = '/';
if (m_Param.szPath[nRetCode - 1] != '/')
{
m_Param.szPath[nRetCode] = '/';
m_Param.szPath[nRetCode + 1] = '\0';
}
ttNow = time(NULL);
tmNow = localtime(&ttNow);
m_RTPattern.ttTimeStamp = ttNow;
nRetCode = _snprintf(m_szFilePath, sizeof(m_szFilePath) - 1, "%s%d-%2.2d-%2.2d/"
, m_Param.szPath, tmNow->tm_year + 1900, tmNow->tm_mon + 1, tmNow->tm_mday);
m_szFilePath[sizeof(m_szFilePath) - 1] = '\0';
nRetCode = _snprintf(m_szFileName, sizeof(m_szFileName) - 1, "%d_%2.2d_%2.2d_%2.2d_%2.2d_%2.2d",
tmNow->tm_year + 1900, tmNow->tm_mon + 1, tmNow->tm_mday, tmNow->tm_hour, tmNow->tm_min, tmNow->tm_sec);
m_szFileName[sizeof(m_szFileName) - 1] = '\0';
nRetCode = NextLogFile();
CONDITION_ERROR(nRetCode);
Success:
nResult = true;
Error:
if (!nResult)
{
m_szFileName[0] = '\0';
m_szFilePath[0] = '\0';
m_RTPattern.ttTimeStamp = 0;
memset(&m_Param, 0, sizeof(m_Param));
}
return nResult;
}
TINY_LOG_PRIORITY TinyLog::SetPriority(TINY_LOG_PRIORITY priNew)
{
TINY_LOG_PRIORITY priOld = m_CurrentPriority;
m_CurrentPriority = priNew;
return priOld;
}
void TinyLog::Reset()
{
if (m_atLogs)
{
atom_destroy(m_atLogs);
m_atLogs = NULL;
}
if (m_atStrings)
{
atom_destroy(m_atStrings);
m_atStrings = NULL;
}
m_LogMap.clear();
m_StringMap.clear();
m_atLogs = atom_create();
assert(m_atLogs);
m_atStrings = atom_create();
assert(m_atStrings);
if (m_nFileHandle != -1)
{
_close(m_nFileHandle);
m_nFileHandle = -1;
}
m_usOffset = 0;
}
int TinyLog::AddString(const char* pcszStr, unsigned short* pusRet)
{
int nRetCode = false;
int nResult = false;
c_str cstr = NULL;
TLOffsetMapPtr ptr;
CONDITION_ERROR(pusRet);
*pusRet = 0;
CONDITION_SUCCESS(pcszStr == NULL);
cstr = atom_string(m_atStrings, pcszStr);
ptr = m_StringMap.find(cstr);
if (ptr != m_StringMap.end())
{
*pusRet = ptr->second;
goto Success;
}
*pusRet = m_usOffset;
m_StringMap.insert(std::make_pair(cstr, m_usOffset));
nRetCode = _write(m_nFileHandle, pcszStr, (unsigned int)strlen(pcszStr) + 1);
m_usOffset += nRetCode;
Success:
nResult = true;
Error:
return nResult;
}
int TinyLog::NextLogFile()
{
int nRetCode = false;
int nResult = false;
char szFullPath[FILE_PATH_LENGTH];
nRetCode = mkdir(m_Param.szPath);
CONDITION_ERROR((nRetCode == 0) || (errno == EEXIST));
nRetCode = mkdir(m_szFilePath);
CONDITION_ERROR((nRetCode == 0) || (errno == EEXIST));
Reset();
nRetCode = _snprintf(szFullPath, sizeof(szFullPath) - 1, "%s%s(part%d).tlog"
, m_szFilePath, m_szFileName, m_nIndex);
szFullPath[sizeof(szFullPath) - 1] = '\0';
m_nFileHandle = _open(szFullPath, TLOG_OPENFILEFLAG, TLOG_OPENFILEMODE);
CONDITION_ERROR(m_nFileHandle != -1);
nRetCode = _write(m_nFileHandle, &m_RTPattern, m_RTPattern.cbSize);
CONDITION_ERROR(nRetCode == (int)m_RTPattern.cbSize);
m_usOffset += (unsigned short)nRetCode;
nResult = true;
m_nIndex++;
Error:
if (!nResult)
{
if (m_nFileHandle != -1)
{
_close(m_nFileHandle);
m_nFileHandle = -1;
}
}
return nResult;
}
#ifdef BUILD_AS_DLL
__declspec(dllexport)
#else
extern
#endif
eITLCode CreateTinyLog(TINY_LOG_PARAM* pParam, ITinyLog** ppi)
{
if (!pParam || pParam->cbSize != sizeof(TINY_LOG_PARAM))
return eCreateITLVersionError;
if (!ppi)
return eCreateITLError;
TinyLog* pTinyLog = NULL;
pTinyLog = new TinyLog();
if (!pTinyLog)
return eCreateITLError;
if (!pTinyLog->Init(pParam))
return eCreateITLInitError;
*ppi = static_cast<ITinyLog*>(pTinyLog);
return eCreateITLSuccess;
}
static ITinyLog* gs_TinyLogS = NULL;
TLAPI int logS_Init(TINY_LOG_PARAM* pParam)
{
int nRetCode = false;
int nResult = false;
CONDITION_ERROR(gs_TinyLogS == NULL);
nRetCode = CreateTinyLog(pParam, &gs_TinyLogS);
CONDITION_ERROR(nRetCode == eCreateITLSuccess);
nResult = true;
Error:
return nResult;
}
TLAPI int logS_Uninit()
{
int nResult = false;
CONDITION_ERROR(gs_TinyLogS);
gs_TinyLogS->Release();
nResult = true;
Error:
return nResult;
}
TLAPI int logS_Log(TINY_LOG_PRIORITY Priority, const char* csClassify, const char fmt[], ...)
{
int nResult = false;
char szBuffer[1024];
va_list marker;
CONDITION_ERROR(gs_TinyLogS);
va_start(marker, fmt);
vsnprintf(szBuffer, sizeof(szBuffer) - 1, fmt, marker);
va_end(marker);
szBuffer[sizeof(szBuffer) - 1] = '\0';
nResult = gs_TinyLogS->Log(Priority, csClassify, NULL, -1, NULL, szBuffer);
Error:
return nResult;
}
TLAPI int logS_Log(TINY_LOG_PRIORITY Priority
, const char* csClassify
, const char* pcszCondition
, int nLine
, const char* pcszFunctionName
, const char* pcszInfo /* = NULL */)
{
int nResult = false;
CONDITION_ERROR(gs_TinyLogS);
nResult = gs_TinyLogS->Log(Priority, csClassify, pcszCondition, nLine, pcszFunctionName, pcszInfo);
Error:
return nResult;
}
|
zzengine
|
trunk/TinyLog/TinyLog/Src/TinyLog.cpp
|
C++
|
gpl3
| 9,697
|
#include "stdafx.h"
#include "log.h"
#include "test.h"
static void FunctionStackOne()
{
int nRandomNumber = rand();
LOG_ERROR(nRandomNumber % 2);
LOG_SUCCESS(nRandomNumber % 2);
Error:
Success:
Exit0:
Exit1:
return;
}
void Run()
{
for (int i = 0; i < 100000; ++i)
FunctionStackOne();
}
|
zzengine
|
trunk/TinyLog/TestTinyLog/test.cpp
|
C++
|
gpl3
| 316
|
// stdafx.cpp : source file that includes just the standard includes
// TestTinyLog.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"
// TODO: reference any additional headers you need in STDAFX.H
// and not in this file
|
zzengine
|
trunk/TinyLog/TestTinyLog/stdafx.cpp
|
C++
|
gpl3
| 298
|
#include "stdafx.h"
#include "log.h"
int KLogInit()
{
int nRetCode = false;
int nResult = false;
KGLOG_PARAM param = { 0 };
nRetCode = sprintf_s(param.szPath, _countof(param.szPath), "%s", "Logs");
KG_PROCESS_ERROR(nRetCode > 0);
nRetCode = sprintf_s(param.szIdent, _countof(param.szIdent), "%s", "Kingsoft");
KG_PROCESS_ERROR(nRetCode > 0);
param.nMaxLineEachFile = 1 << 16;
param.Options = (KGLOG_OPTIONS)KGLOG_OPTION_FILE;
nRetCode = KGLogInit(param, NULL);
KG_PROCESS_ERROR(nRetCode);
nResult = true;
Exit0:
return nResult;
}
int KLogUninit()
{
int nRetCode = false;
int nResult = false;
nRetCode = KGLogUnInit(NULL);
KG_PROCESS_ERROR(nRetCode);
nResult = true;
Exit0:
return nResult;
}
int TLogInit()
{
int nRetCode = false;
int nResult = false;
TINY_LOG_PARAM param = { sizeof(TINY_LOG_PARAM) };
nRetCode = sprintf_s(param.szPath, _countof(param.szPath), "%s/%s", "Logs", "TinyLog");
CONDITION_ERROR(nRetCode > 0);
param.Options = eTinyLogOptionFile;
nRetCode = logS_Init(¶m);
CONDITION_ERROR(nRetCode);
nResult = true;
Error:
return nResult;
}
int TLogUninit()
{
int nRetCode = false;
int nResult = false;
nRetCode = logS_Uninit();
CONDITION_ERROR(nRetCode);
nResult = true;
Error:
return nResult;
}
int LLogInit()
{
log4cpp::Layout* layout = new log4cpp::BasicLayout();
log4cpp::Appender* pFile = new log4cpp::FileAppender("FileAppender", "./testlog.llog");
log4cpp::Category& dLog = log4cpp::Category::getRoot().getInstance("Error");
dLog.addAppender(pFile);
log4cpp::Category& iLog = log4cpp::Category::getRoot().getInstance("Info");
iLog.addAppender(pFile);
return true;
}
int LLogUninit()
{
//log4cpp::Category::shutdown();
return true;
}
int LLogPrint(const char* pcszPri, const char* pcszCate, const char* pcszCondition, int nLine, const char* pcszFuncName)
{
char szInfo[256];
sprintf_s(szInfo, _countof(szInfo), "%s at Line %d in %s.", pcszCondition, nLine, pcszFuncName);
log4cpp::Category& log = log4cpp::Category::getRoot().getInstance(pcszCate);
if (pcszPri == "Error")
log.setPriority(log4cpp::Priority::ERROR);
else
log.setPriority(log4cpp::Priority::INFO);
log.error(szInfo);
return true;
}
|
zzengine
|
trunk/TinyLog/TestTinyLog/log.cpp
|
C++
|
gpl3
| 2,291
|
#pragma once
void Run();
|
zzengine
|
trunk/TinyLog/TestTinyLog/test.h
|
C
|
gpl3
| 27
|
#include "stdafx.h"
#include "..\include\ITinyLog.h"
|
zzengine
|
trunk/TinyLog/TestTinyLog/main.cpp
|
C++
|
gpl3
| 53
|
#pragma once
#include "../include/kingsoft/KGLog.h"
#include "../include/ITinyLog.h"
#include "log4cpp/Category.hh"
#include "log4cpp/Priority.hh"
#include "log4cpp/OstreamAppender.hh"
#include "log4cpp/FileAppender.hh"
#include "log4cpp/BasicLayout.hh"
int KLogInit();
int KLogUninit();
int TLogInit();
int TLogUninit();
int LLogInit();
int LLogUninit();
int LLogPrint(const char* pcszPri, const char* pcszCate, const char* pcszCondition, int nLine, const char* pcszFuncName);
#define LogInit TLogInit
#define LogUninit TLogUninit
#ifdef KINGSOFT
#define LogInit KLogInit
#define LogUninit KLogUninit
#endif
#ifdef LOG4CPP
#define LogInit LLogInit
#define LogUninit LLogUninit
#endif
#define LOG_ERROR LOGS_CONDITION_ERROR
#define LOG_SUCCESS LOGS_CONDITION_SUCCESS
#ifdef KINGSOFT
#define LOG_ERROR KGLOG_PROCESS_ERROR
#define LOG_SUCCESS KGLOG_PROCESS_SUCCESS
#endif
#define LLOG_CONDITION_ERROR(Condition) \
do \
{ \
if (!(Condition)) \
{ \
LLogPrint( \
"Error", \
"Error", \
#Condition, \
__LINE__, \
_FUNCTION \
); \
goto Error; \
} \
} while (false)
#define LLOG_CONDITION_SUCCESS(Condition) \
do \
{ \
if (Condition) \
{ \
LLogPrint( \
"Info", \
"Info", \
#Condition, \
__LINE__, \
_FUNCTION \
); \
goto Success; \
} \
} while (false)
#ifdef LOG4CPP
#define LOG_ERROR LLOG_CONDITION_ERROR
#define LOG_SUCCESS LLOG_CONDITION_SUCCESS
#endif
|
zzengine
|
trunk/TinyLog/TestTinyLog/log.h
|
C
|
gpl3
| 1,550
|
// stdafx.h : include file for standard system include files,
// or project specific include files that are used frequently, but
// are changed infrequently
//
#pragma once
#ifndef _WIN32_WINNT // Allow use of features specific to Windows XP or later.
#define _WIN32_WINNT 0x0501 // Change this to the appropriate value to target other versions of Windows.
#endif
#include <stdio.h>
#include <tchar.h>
#include <stdlib.h>
//#define KINGSOFT 1
#define LOG4CPP 1
|
zzengine
|
trunk/TinyLog/TestTinyLog/stdafx.h
|
C
|
gpl3
| 506
|
package com.ning;
import java.io.IOException;
import javax.servlet.http.*;
import com.ning.google.SendMailManager2;
@SuppressWarnings("serial")
public class GoogleAnalyticsAutoEmailServlet2 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response){
try {
String content = SendMailManager2.instance().send();
request.setCharacterEncoding("utf-8");
response.setContentType( "text/html;charset=utf-8");
response.getWriter().write(content);
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
|
zzzhukkcc
|
trunk/src/com/ning/GoogleAnalyticsAutoEmailServlet2.java
|
Java
|
asf20
| 579
|
package com.ning.google;
import java.text.DecimalFormat;
import java.text.NumberFormat;
public class SourceInfo {
private String title;
private String date;
private int pv;
private int uv;
private int newUv;
private double percentNewUv;
public String getPercentNewUv() {
NumberFormat format = new DecimalFormat("#0.00");
return format.format(percentNewUv);
}
public void setPercentNewUv(double percentNewUv) {
this.percentNewUv = percentNewUv;
}
public int getNewUv() {
return newUv;
}
public void setNewUv(int newUv) {
this.newUv = newUv;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public int getPv() {
return pv;
}
public void setPv(int pv) {
this.pv = pv;
}
public int getUv() {
return uv;
}
public void setUv(int uv) {
this.uv = uv;
}
@Override
public String toString() {
return "InfoTwo [title=" + title + ", date=" + date + ", pv=" + pv
+ ", uv=" + uv + "]";
}
}
|
zzzhukkcc
|
trunk/src/com/ning/google/SourceInfo.java
|
Java
|
asf20
| 1,153
|
package com.ning.google;
import java.text.DecimalFormat;
import java.text.NumberFormat;
public class GeneralInfo {
private int pv;
private int uv;
private int newuv;
private int avgtime;
private double percentNewUv;
private String date;
private double perPageUser;
private double exitRate;
private String type;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getExitRate(){
DecimalFormat df = new DecimalFormat("######0.00");
return df.format(exitRate);
}
public void setExitRate(double exitRate) {
this.exitRate = exitRate;
}
public String getPerPageUser(){
DecimalFormat df = new DecimalFormat("######0.00");
return df.format(perPageUser);
}
public void setPerPageUser(double perPageUser) {
this.perPageUser = perPageUser;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public int getPv() {
return pv;
}
public void setPv(int pv) {
this.pv = pv;
}
public int getUv() {
return uv;
}
public void setUv(int uv) {
this.uv = uv;
}
public int getNewuv() {
return newuv;
}
public void setNewuv(int newuv) {
this.newuv = newuv;
}
public int getAvgtime() {
return avgtime;
}
public void setAvgtime(int avgtime) {
this.avgtime = avgtime;
}
public String getPercentNewUv() {
NumberFormat format = new DecimalFormat("#0.00");
return format.format(percentNewUv);
}
public void setPercentNewUv(double percentNewUv) {
this.percentNewUv = percentNewUv;
}
@Override
public String toString() {
return "GeneralInfo [pv=" + pv + ", uv=" + uv + ", newuv=" + newuv
+ ", avgtime=" + avgtime + ", percentNewUv=" + percentNewUv
+ ", date=" + date + ", perPageUser=" + perPageUser
+ ", exitRate=" + exitRate + "]";
}
}
|
zzzhukkcc
|
trunk/src/com/ning/google/GeneralInfo.java
|
Java
|
asf20
| 1,905
|
package com.ning.google;
import java.text.DecimalFormat;
import java.text.NumberFormat;
public class SearchInfo {
private String title;
private String date;
private int pv;
private int uv;
private int newUv;
private double percentNewUv;
public String getPercentNewUv() {
NumberFormat format = new DecimalFormat("#0.00");
return format.format(percentNewUv);
}
public void setPercentNewUv(double percentNewUv) {
this.percentNewUv = percentNewUv;
}
public int getNewUv() {
return newUv;
}
public void setNewUv(int newUv) {
this.newUv = newUv;
}
@Override
public String toString() {
return "SearchInfo [title=" + title + ", date=" + date + ", pv=" + pv
+ ", uv=" + uv + "]";
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public int getPv() {
return pv;
}
public void setPv(int pv) {
this.pv = pv;
}
public int getUv() {
return uv;
}
public void setUv(int uv) {
this.uv = uv;
}
}
|
zzzhukkcc
|
trunk/src/com/ning/google/SearchInfo.java
|
Java
|
asf20
| 1,159
|
package com.ning.google;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;
public class SendMailManager2 {
private static SendMailManager2 _instance = new SendMailManager2();
public static SendMailManager2 instance() {
return _instance;
}
public String send(){
Properties props = new Properties();
Session session = Session.getDefaultInstance(props, null);
Calendar c = Calendar.getInstance();
c.add(Calendar.DATE, -1);
String date = new SimpleDateFormat("yyyy-MM-dd").format(c.getTime());
String msgBody = "<div style=\"width:620px; border:1px solid #ccc;padding:5px;\">"+
"<table style=\"width:600px; border:0; margin:0 auto;border-collapse:collapse;border-spacing:0; \">"+
"<tr>"+
"<td>"+
"<div style=\"min-height:45px;font-size:20px;font-weight:bold;max-height:45px; text-align:center;border-bottom:1px solid #ccc;\">统计日报【"+date+"】</div>"+
"</td>"+
"</tr>"+
"<tr>"+
"<td>"+
"<div style=\"font-size:14px; padding:10px;color:#2C2C2C;line-height:20px; text-align:left;border-bottom:1px dashed #ccc;\">"+
"<p style=\"color:#0088CC;padding:0px;margin-top:0px;margin-bottom:0px;margin-left:0px;margin-right:0px;\"><strong>概况信息</strong></p>"+
"</div>"+
"</td>"+
"</tr>"+
"<tr>"+
"<td>"+
"<table style=\"width:600px; border:0;font-size:12px; margin:0 auto;border-collapse:collapse;border-spacing:0;\">"+
"<tr>"+
"<td width=\"100\" style=\"font-weight:bold;text-align:center;padding:5px 0;border:1px dotted #CBCBCB;background:#eee;\">日期</td>"+
"<td width=\"100\" style=\"font-weight:bold;text-align:center;padding:5px 0;border:1px dotted #CBCBCB;background:#eee;\">PV</td>"+
"<td width=\"100\" style=\"font-weight:bold;text-align:center;padding:5px 0;border:1px dotted #CBCBCB;background:#eee;\">UV</td>"+
"<td width=\"100\" style=\"font-weight:bold;text-align:center;padding:5px 0;border:1px dotted #CBCBCB;background:#eee;\">新UV</td>"+
"<td width=\"100\" style=\"font-weight:bold;text-align:center;padding:5px 0;border:1px dotted #CBCBCB;background:#eee;\">新UV占比</td>"+
"<td width=\"100\" style=\"font-weight:bold;text-align:center;padding:5px 0;border:1px dotted #CBCBCB;background:#eee;\">平均停留时间(s)</td>"+
"</tr>";
List<GeneralInfo> list1 = GAnalyticsAutoManager2.instance().getGeneralInfo();
if(list1 != null){
for(GeneralInfo info1 : list1){
msgBody += "<tr>"+
"<td style=\"text-align:center;padding:5px 0;border:1px dotted #CBCBCB;\">"+info1.getDate()+"</td>"+
"<td style=\"text-align:center;padding:5px 0;border:1px dotted #CBCBCB;\">"+info1.getPv()+"</td>"+
"<td style=\"text-align:center;padding:5px 0;border:1px dotted #CBCBCB;\">"+info1.getUv()+"</td>"+
"<td style=\"text-align:center;padding:5px 0;border:1px dotted #CBCBCB;\">"+info1.getNewuv()+"</td>"+
"<td style=\"text-align:center;padding:5px 0;border:1px dotted #CBCBCB;\">"+info1.getPercentNewUv()+"%</td>"+
"<td style=\"text-align:center;padding:5px 0;border:1px dotted #CBCBCB;\">"+info1.getAvgtime()+"</td>"+
"</tr>";
}
}
msgBody += "</table>"+
"</td>"+
"</tr>"+
"<tr>"+
"<td>"+
"<div style=\"font-size:14px; padding:10px;color:#2C2C2C;line-height:20px; text-align:left;border-bottom:1px dashed #ccc;\">"+
"<p style=\"color:#0088CC;padding:0px;margin-top:0px;margin-bottom:0px;margin-left:0px;margin-right:0px;\"><strong>App概况信息</strong></p>"+
"</div>"+
"</td>"+
"</tr>"+
"<tr>"+
"<td>"+
"<table style=\"width:600px; font-size:12px;border:0; margin:0 auto;border-collapse:collapse;border-spacing:0; \">";
HashMap<String,GeneralInfo> appdata = GAnalyticsAutoManager2.instance().getAppDetailsInfo();
Iterator<String> appdatas = appdata.keySet().iterator();
msgBody += "<tr><td style=\"font-weight:bold;text-align:center;padding:5px 0;border:1px dotted #CBCBCB;background:#eee;\">项目</td>" +
"<td width=\"70\" style=\"font-weight:bold;text-align:center;padding:5px 0;border:1px dotted #CBCBCB;background:#eee;\">PV</td>" +
"<td width=\"70\" style=\"font-weight:bold;text-align:center;padding:5px 0;border:1px dotted #CBCBCB;background:#eee;\">UV</td>" +
"<td width=\"90\" style=\"font-weight:bold;text-align:center;padding:5px 0;border:1px dotted #CBCBCB;background:#eee;\">每次访问页数</td>" +
"<td width=\"70\" style=\"font-weight:bold;text-align:center;padding:5px 0;border:1px dotted #CBCBCB;background:#eee;\">停留时间</td>" +
"<td width=\"70\" style=\"font-weight:bold;text-align:center;padding:5px 0;border:1px dotted #CBCBCB;background:#eee;\">跳出率</td>" +
"<td width=\"70\" style=\"font-weight:bold;text-align:center;padding:5px 0;border:1px dotted #CBCBCB;background:#eee;\">新用户</td>" +
"<td width=\"70\" style=\"font-weight:bold;text-align:center;padding:5px 0;border:1px dotted #CBCBCB;background:#eee;\">新访问占比</td>" +
"</tr>";
GeneralInfo allapp = appdata.get("All");
GeneralInfo picapp = appdata.get("picapp");
GeneralInfo newsapp = appdata.get("newsapp");
GeneralInfo toolsapp = appdata.get("toolsapp");
int totalPv = allapp.getPv();
int totalUv = allapp.getUv();
NumberFormat format = new DecimalFormat("#0.00");
msgBody += "<tr>" +
"<td style=\"text-align:center;padding:5px 0;border:1px dotted #CBCBCB;\">所有</td>" +
"<td style=\"text-align:center;padding:5px 0;border:1px dotted #CBCBCB;\">"+totalPv+"</td>" +
"<td style=\"text-align:center;padding:5px 0;border:1px dotted #CBCBCB;\">"+totalUv+"</td>" +
"<td style=\"text-align:center;padding:5px 0;border:1px dotted #CBCBCB;\">"+allapp.getPerPageUser()+"</td>" +
"<td style=\"text-align:center;padding:5px 0;border:1px dotted #CBCBCB;\">"+allapp.getAvgtime()+"</td>" +
"<td style=\"text-align:center;padding:5px 0;border:1px dotted #CBCBCB;\">"+allapp.getExitRate()+"%</td>" +
"<td style=\"text-align:center;padding:5px 0;border:1px dotted #CBCBCB;\">"+allapp.getNewuv()+"</td>" +
"<td style=\"text-align:center;padding:5px 0;border:1px dotted #CBCBCB;\">"+allapp.getPercentNewUv()+"%</td>" +
"</tr>";
msgBody += "<tr>" +
"<td style=\"text-align:center;padding:5px 0;border:1px dotted #CBCBCB;\">相册App</td>" +
"<td style=\"text-align:center;padding:5px 0;border:1px dotted #CBCBCB;\">"+picapp.getPv()+"("+format.format((double)picapp.getPv()*100/(double)totalPv)+"%)</td>" +
"<td style=\"text-align:center;padding:5px 0;border:1px dotted #CBCBCB;\">"+picapp.getUv()+"("+format.format((double)picapp.getUv()*100/(double)totalUv)+"%)</td>" +
"<td style=\"text-align:center;padding:5px 0;border:1px dotted #CBCBCB;\">"+picapp.getPerPageUser()+"</td>" +
"<td style=\"text-align:center;padding:5px 0;border:1px dotted #CBCBCB;\">"+picapp.getAvgtime()+"</td>" +
"<td style=\"text-align:center;padding:5px 0;border:1px dotted #CBCBCB;\">"+picapp.getExitRate()+"%</td>" +
"<td style=\"text-align:center;padding:5px 0;border:1px dotted #CBCBCB;\">"+picapp.getNewuv()+"</td>" +
"<td style=\"text-align:center;padding:5px 0;border:1px dotted #CBCBCB;\">"+picapp.getPercentNewUv()+"%</td>" +
"</tr>";
msgBody += "<tr>" +
"<td style=\"text-align:center;padding:5px 0;border:1px dotted #CBCBCB;\">资讯App</td>" +
"<td style=\"text-align:center;padding:5px 0;border:1px dotted #CBCBCB;\">"+newsapp.getPv()+"("+format.format((double)newsapp.getPv()*100/(double)totalPv)+"%)</td>" +
"<td style=\"text-align:center;padding:5px 0;border:1px dotted #CBCBCB;\">"+newsapp.getUv()+"("+format.format((double)newsapp.getUv()*100/(double)totalUv)+"%)</td>" +
"<td style=\"text-align:center;padding:5px 0;border:1px dotted #CBCBCB;\">"+newsapp.getPerPageUser()+"</td>" +
"<td style=\"text-align:center;padding:5px 0;border:1px dotted #CBCBCB;\">"+newsapp.getAvgtime()+"</td>" +
"<td style=\"text-align:center;padding:5px 0;border:1px dotted #CBCBCB;\">"+newsapp.getExitRate()+"%</td>" +
"<td style=\"text-align:center;padding:5px 0;border:1px dotted #CBCBCB;\">"+newsapp.getNewuv()+"</td>" +
"<td style=\"text-align:center;padding:5px 0;border:1px dotted #CBCBCB;\">"+newsapp.getPercentNewUv()+"%</td>" +
"</tr>";
msgBody += "<tr>" +
"<td style=\"text-align:center;padding:5px 0;border:1px dotted #CBCBCB;\">装备App</td>" +
"<td style=\"text-align:center;padding:5px 0;border:1px dotted #CBCBCB;\">"+toolsapp.getPv()+"("+format.format((double)toolsapp.getPv()*100/(double)totalPv)+"%)</td>" +
"<td style=\"text-align:center;padding:5px 0;border:1px dotted #CBCBCB;\">"+toolsapp.getUv()+"("+format.format((double)toolsapp.getUv()*100/(double)totalUv)+"%)</td>" +
"<td style=\"text-align:center;padding:5px 0;border:1px dotted #CBCBCB;\">"+toolsapp.getPerPageUser()+"</td>" +
"<td style=\"text-align:center;padding:5px 0;border:1px dotted #CBCBCB;\">"+toolsapp.getAvgtime()+"</td>" +
"<td style=\"text-align:center;padding:5px 0;border:1px dotted #CBCBCB;\">"+toolsapp.getExitRate()+"%</td>" +
"<td style=\"text-align:center;padding:5px 0;border:1px dotted #CBCBCB;\">"+toolsapp.getNewuv()+"</td>" +
"<td style=\"text-align:center;padding:5px 0;border:1px dotted #CBCBCB;\">"+toolsapp.getPercentNewUv()+"%</td>" +
"</tr>";
List<GeneralInfo> appsinfo = new ArrayList<GeneralInfo>();
while(appdatas.hasNext()){
String key = appdatas.next();
if(key.equals("All") || key.equals("picapp") || key.equals("newsapp") || key.equals("toolsapp")) continue;
GeneralInfo tempdata = appdata.get(key);
tempdata.setType(key);
appsinfo.add(tempdata);
}
ComparatorPV comparator=new ComparatorPV();
Collections.sort(appsinfo, comparator);
for(GeneralInfo g : appsinfo){
msgBody += "<tr>" +
"<td style=\"text-align:center;padding:5px 0;border:1px dotted #CBCBCB;\">"+g.getType()+"</td>" +
"<td style=\"text-align:center;padding:5px 0;border:1px dotted #CBCBCB;\">"+g.getPv()+"("+format.format((double)g.getPv()*100/(double)totalPv)+"%)</td>" +
"<td style=\"text-align:center;padding:5px 0;border:1px dotted #CBCBCB;\">"+g.getUv()+"("+format.format((double)g.getUv()*100/(double)totalUv)+"%)</td>" +
"<td style=\"text-align:center;padding:5px 0;border:1px dotted #CBCBCB;\">"+g.getPerPageUser()+"</td>" +
"<td style=\"text-align:center;padding:5px 0;border:1px dotted #CBCBCB;\">"+g.getAvgtime()+"</td>" +
"<td style=\"text-align:center;padding:5px 0;border:1px dotted #CBCBCB;\">"+g.getExitRate()+"%</td>" +
"<td style=\"text-align:center;padding:5px 0;border:1px dotted #CBCBCB;\">"+g.getNewuv()+"</td>" +
"<td style=\"text-align:center;padding:5px 0;border:1px dotted #CBCBCB;\">"+g.getPercentNewUv()+"%</td></tr>";
}
msgBody += "</table>"+
"</td>"+
"</tr>"+
"</table>"+
"</div>";
try {
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress("zhufukc@gmail.com"));
msg.addRecipient(Message.RecipientType.TO, new InternetAddress("zhufukc@gmail.com"));
msg.setSubject(MimeUtility.encodeText("统计日报 【"+date+"】","gb2312","B"));
Multipart mp = new MimeMultipart();
MimeBodyPart htmlPart = new MimeBodyPart();
htmlPart.setContent(msgBody, "text/html");
mp.addBodyPart(htmlPart);
msg.setContent(mp);
Transport.send(msg);
} catch (Exception e) {
e.printStackTrace();
}
return msgBody;
}
public class ComparatorPV implements Comparator<GeneralInfo>{
public int compare(GeneralInfo g1, GeneralInfo g2) {
return g2.getPv() - g1.getPv();
}
}
}
|
zzzhukkcc
|
trunk/src/com/ning/google/SendMailManager2.java
|
Java
|
asf20
| 12,803
|
package com.ning.google;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import com.google.gdata.client.analytics.AnalyticsService;
import com.google.gdata.client.analytics.DataQuery;
import com.google.gdata.data.analytics.DataEntry;
import com.google.gdata.data.analytics.DataFeed;
import com.google.gdata.util.AuthenticationException;
public class GAnalyticsAutoManager2 {
private static final String CLIENT_USERNAME = "zhufukc@gmail.com";
private static final String CLIENT_PASS = "zhufukc74";
private static final String TABLE_ID = "ga:47208457";
private static GAnalyticsAutoManager2 _instance = new GAnalyticsAutoManager2();
public static GAnalyticsAutoManager2 instance() {
return _instance;
}
private final AnalyticsService analyticsService;
public GAnalyticsAutoManager2(){
analyticsService = new AnalyticsService("gaExportAPI_acctSample_v2.0");
try {
analyticsService.setUserCredentials(CLIENT_USERNAME, CLIENT_PASS);
} catch (AuthenticationException e) {
e.printStackTrace();
}
}
public List<GeneralInfo> getGeneralInfo() {
List<GeneralInfo> list = new ArrayList<GeneralInfo>();
try {
DataQuery query = new DataQuery(new URL("https://www.google.com/analytics/feeds/data"));
query.setStartDate(getLastWeekDate());
query.setEndDate(getDate());
query.setDimensions("ga:date");
query.setMetrics("ga:pageviews,ga:visitors,ga:newVisits,ga:avgTimeOnSite,ga:percentNewVisits");
query.setSort("-ga:date");
query.setMaxResults(10);
query.setIds(TABLE_ID);
DataFeed dataFeed = analyticsService.getFeed(query.getUrl(),DataFeed.class);
for (DataEntry entry : dataFeed.getEntries()) {
GeneralInfo infoone = new GeneralInfo();
infoone.setAvgtime((int) (Double.parseDouble(entry
.stringValueOf("ga:avgTimeOnSite"))));
infoone.setNewuv(Integer.parseInt(entry
.stringValueOf("ga:newVisits")));
infoone.setUv(Integer.parseInt(entry
.stringValueOf("ga:visitors")));
infoone.setPv(Integer.parseInt(entry
.stringValueOf("ga:pageviews")));
infoone.setPercentNewUv(Double.parseDouble(entry
.stringValueOf("ga:percentNewVisits")));
infoone.setDate(convertDate(entry.stringValueOf("ga:date")));
list.add(infoone);
}
return list;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public List<SourceInfo> getSourceInfo(boolean isToday) {
List<SourceInfo> list = new ArrayList<SourceInfo>();
try {
DataQuery query = new DataQuery(new URL(
"https://www.google.com/analytics/feeds/data"));
String date = getYesterDayDate();
if(isToday) date = getDate();
query.setStartDate(date);
query.setEndDate(date);
query.setDimensions("ga:date,ga:source");
query.setMetrics("ga:pageviews,ga:visitors,ga:newVisits,ga:percentNewVisits");
query.setSort("-ga:pageviews");
query.setFilters("ga:pageviews>10");
query.setMaxResults(100);
query.setSegment("gaid::-8");
query.setIds(TABLE_ID);
DataFeed dataFeed = analyticsService.getFeed(query.getUrl(),
DataFeed.class);
for (DataEntry entry : dataFeed.getEntries()) {
SourceInfo infotwo = new SourceInfo();
infotwo.setUv(Integer.parseInt(entry
.stringValueOf("ga:visitors")));
infotwo.setPv(Integer.parseInt(entry
.stringValueOf("ga:pageviews")));
infotwo.setDate(convertDate(entry.stringValueOf("ga:date")));
infotwo.setTitle(entry.stringValueOf("ga:source"));
infotwo.setNewUv(Integer.parseInt(entry
.stringValueOf("ga:newVisits")));
infotwo.setPercentNewUv(Double.parseDouble(entry
.stringValueOf("ga:percentNewVisits")));
list.add(infotwo);
}
return list;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public List<SearchInfo> getSearchInfo(boolean isToday) {
List<SearchInfo> list = new ArrayList<SearchInfo>();
try {
DataQuery query = new DataQuery(new URL(
"https://www.google.com/analytics/feeds/data"));
String date = getYesterDayDate();
if(isToday) date = getDate();
query.setStartDate(date);
query.setEndDate(date);
query.setDimensions("ga:date,ga:source");
query.setMetrics("ga:pageviews,ga:visitors,ga:newVisits,ga:percentNewVisits");
query.setSort("-ga:pageviews");
query.setFilters("ga:pageviews>10");
query.setMaxResults(100);
query.setSegment("gaid::-6");
query.setIds(TABLE_ID);
DataFeed dataFeed = analyticsService.getFeed(query.getUrl(),
DataFeed.class);
for (DataEntry entry : dataFeed.getEntries()) {
SearchInfo infotwo = new SearchInfo();
infotwo.setUv(Integer.parseInt(entry
.stringValueOf("ga:visitors")));
infotwo.setPv(Integer.parseInt(entry
.stringValueOf("ga:pageviews")));
infotwo.setDate(convertDate(entry.stringValueOf("ga:date")));
infotwo.setTitle(entry.stringValueOf("ga:source"));
infotwo.setNewUv(Integer.parseInt(entry
.stringValueOf("ga:newVisits")));
infotwo.setPercentNewUv(Double.parseDouble(entry
.stringValueOf("ga:percentNewVisits")));
list.add(infotwo);
}
return list;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public HashMap<String,GeneralInfo> getAppDetailsInfo(){
HashMap<String,GeneralInfo> maps = new HashMap<String,GeneralInfo>();
String[] datas1 = new String[]{"All","WebSelf","QQMail","WebQQ","360Desktop","360SEApp","Tqq","SinAapp","Renren","BaiduApp","TianYaApp","Q+","JiaThis","kaixin001"
,"picapp","t163","cnfol","newsapp","toolsapp","search","mobile"};
String[] datas2 = new String[]{"","gaid::1877811261","gaid::1300005415","gaid::960794372","gaid::2112745087","gaid::1818061867","gaid::1309064845","gaid::571678374","gaid::1338240564","gaid::1510974722","gaid::703110469","gaid::1293097597","gaid::63390337","gaid::34381578"
,"gaid::471702186","gaid::665809246","gaid::1526588065","gaid::2019157341","gaid::529957698","gaid::-6","gaid::-11"};
for(int i=0;i<datas1.length;i++){
try {
DataQuery query = new DataQuery(new URL("https://www.google.com/analytics/feeds/data"));
String date = getDate();
query.setStartDate(date);
query.setEndDate(date);
query.setMetrics("ga:pageviews,ga:visitors,ga:newVisits,ga:avgTimeOnSite,ga:percentNewVisits,ga:pageviewsPerVisit,ga:visitBounceRate");
query.setMaxResults(10);
query.setSegment(datas2[i]);
query.setIds(TABLE_ID);
DataFeed dataFeed = analyticsService.getFeed(query.getUrl(),DataFeed.class);
DataEntry entry = dataFeed.getEntries().get(0);
GeneralInfo infoone = new GeneralInfo();
infoone.setAvgtime((int) (Double.parseDouble(entry
.stringValueOf("ga:avgTimeOnSite"))));
infoone.setNewuv(Integer.parseInt(entry
.stringValueOf("ga:newVisits")));
infoone.setUv(Integer.parseInt(entry
.stringValueOf("ga:visitors")));
infoone.setPv(Integer.parseInt(entry
.stringValueOf("ga:pageviews")));
infoone.setPercentNewUv(Double.parseDouble(entry
.stringValueOf("ga:percentNewVisits")));
infoone.setPerPageUser(Double.parseDouble(entry
.stringValueOf("ga:pageviewsPerVisit")));
infoone.setExitRate(Double.parseDouble(entry
.stringValueOf("ga:visitBounceRate")));
maps.put(datas1[i], infoone);
} catch (Exception e) {
e.printStackTrace();
}
}
return maps;
}
private String getDate() {
Calendar c = Calendar.getInstance();
c.add(Calendar.DATE, -1);
return new SimpleDateFormat("yyyy-MM-dd").format(c.getTime());
}
private String getYesterDayDate() {
Calendar c = Calendar.getInstance();
c.add(Calendar.DATE, -2);
return new SimpleDateFormat("yyyy-MM-dd").format(c.getTime());
}
private String getLastWeekDate() {
Calendar c = Calendar.getInstance();
c.add(Calendar.DATE, -3);
return new SimpleDateFormat("yyyy-MM-dd").format(c.getTime());
}
private String convertDate(String date) {
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMMdd");
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");
try {
return sdf2.format(sdf1.parse(date));
} catch (ParseException e) {
e.printStackTrace();
return null;
}
}
}
|
zzzhukkcc
|
trunk/src/com/ning/google/GAnalyticsAutoManager2.java
|
Java
|
asf20
| 8,492
|
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Test</title>
</head>
<body>
Test
</body>
</html>
|
zzzhukkcc
|
trunk/war/index.html
|
HTML
|
asf20
| 335
|
package com.zz.common.tools;
import java.lang.ref.WeakReference;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
public class WeakReferenceHandler extends Handler {
private WeakReference<Callback> mWeakReferCallBack;
public WeakReferenceHandler(Callback cb) {
super();
mWeakReferCallBack = new WeakReference<Handler.Callback>(cb);
}
public WeakReferenceHandler(Looper looper, Callback cb) {
super(looper);
mWeakReferCallBack = new WeakReference<Handler.Callback>(cb);
}
@Override
public void handleMessage(Message msg) {
Callback cb = mWeakReferCallBack.get();
if(null != cb) {
cb.handleMessage(msg);
}
}
}
|
zzdache
|
trunk/android/Common/sdk/com/zz/common/tools/WeakReferenceHandler.java
|
Java
|
epl
| 700
|
package com.zz.common.tools.box.runner;
public interface IBpRunner {
public interface IBpRunnerStatusChangedListener {
public void onChange(int curStatus, int regionStatus, IBpRunner runner);
}
public void start();
public void stop();
public void pause();
public void resume();
public int getStatus();
public void setOnStatusChangedListener(IBpRunnerStatusChangedListener listener);
}
|
zzdache
|
trunk/android/Common/sdk/com/zz/common/tools/box/runner/IBpRunner.java
|
Java
|
epl
| 409
|
package com.zz.common.tools.box.runner;
import java.util.List;
public interface IBpRunnerManager {
public int startRunner(BpRunner bpRunenr);
public void stopRunner(int runnerId);
public void pauseRunner(int runnerId);
public void resumeRunner(int runnerId);
public void pauseAll();
public void resumeAll();
public void stopAll();
public int getRunnerStatus(int runnerId);
public List<RunnerInfo> getRunnerInfoList(List<Integer> runnerIdList);
}
|
zzdache
|
trunk/android/Common/sdk/com/zz/common/tools/box/runner/IBpRunnerManager.java
|
Java
|
epl
| 477
|
package com.zz.common.tools.box.runner;
public class RunnerInfo {
public static final int STATUS_UNSPCIFIED = -1;
public static final int STATUS_WAITING = 0;
public static final int STATUS_RUNNING = STATUS_WAITING + 1;
public static final int STATUS_STOPED = STATUS_RUNNING + 1;
public static final int STATUS_SUCCEED = STATUS_STOPED + 1;
public static final int STATUS_FAILED = STATUS_SUCCEED + 1;
public int mStatus;
public int mId;
}
|
zzdache
|
trunk/android/Common/sdk/com/zz/common/tools/box/runner/RunnerInfo.java
|
Java
|
epl
| 461
|
package com.zz.common.tools.box.tools;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.URI;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.ProtocolException;
import org.apache.http.client.RedirectHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.protocol.HttpContext;
public class BpClientUrlLoader extends BpFuture implements RedirectHandler {
public interface OnErrorListener {
public void onError(int errCode, BpClientUrlLoader loader);
}
public interface OnReadListener {
public void onRead(byte[] buffer, int readedBytes, BpClientUrlLoader loader);
}
public interface OnResponseListener {
public void onResponse(int respCode, Header[] headers, BpClientUrlLoader loader);
}
public interface OnCompletedListener {
public void onComplete(int respCode, Header[] headers,
byte[] content, BpClientUrlLoader loader);
}
private static final String TAG = "BpClientUrlLoader";
private static final int DEFAULT_CONNECT_TIME_OUT = 60000;
private static final int DEFAULT_READ_TIME_OUT = 300000;
private OnErrorListener mOnErrorListener;
private OnCompletedListener mOnCompletedListener;
private OnReadListener mOnReadListener;
private OnResponseListener mOnResponseListener;
private RedirectHandler mRedirectHandler;
private String mUrl;
private Header[] mHeaders;
private int mConnectionTimeOut;
private int mReadTimeOut;
private String mUserAgent;
private boolean mCancel = false;
private Thread mThread = null;
public BpClientUrlLoader(String url) {
mUrl = url;
mConnectionTimeOut = DEFAULT_CONNECT_TIME_OUT;
mReadTimeOut = DEFAULT_READ_TIME_OUT;
mCancel = false;
}
public String getUrl() {
return mUrl;
}
public void setOnErrorListener(OnErrorListener listener) {
if(null != listener) {
mOnErrorListener = listener;
}
}
public void setOnCompleteListener(OnCompletedListener listener) {
if(null != listener) {
mOnCompletedListener = listener;
}
}
public void setmOnReadListener(OnReadListener listener) {
if(null != listener) {
mOnReadListener = listener;
}
}
public void setOnResponseListener(OnResponseListener l) {
mOnResponseListener = l;
}
public void setRedirectHandler(RedirectHandler h) {
mRedirectHandler = h;
}
public void setTimeOut(int connectionTime, int readTime) {
if(connectionTime > 0) {
mConnectionTimeOut = connectionTime;
}
if(readTime > 0) {
mReadTimeOut = readTime;
}
}
public void setUserAgent(String userAgent) {
mUserAgent = userAgent;
}
public String getHeader(String name) {
if(null == mHeaders || null == name) {
return null;
}
for(int i=0; i<mHeaders.length; i++) {
if(name.equalsIgnoreCase(mHeaders[i].getName())) {
return mHeaders[i].getValue();
}
}
return null;
}
@Override
public void run() {
try {
mThread = Thread.currentThread();
sailing();
} catch (InterruptedException e) {
}
}
@Override
public void cancel() {
super.cancel();
mOnReadListener = null;
mOnResponseListener = null;
mOnErrorListener = null;
mOnCompletedListener = null;
if(null != mThread && !mThread.isInterrupted()) {
mThread.interrupt();
mThread = null;
}
}
@Override
public URI getLocationURI(HttpResponse response, HttpContext context)
throws ProtocolException {
Header[] newUrlList = response.getHeaders("Location");
if(null == newUrlList || newUrlList.length == 0) {
newUrlList = response.getHeaders("location");
}
if(null == newUrlList || newUrlList.length == 0) {
return null;
} else {
String newUrl = newUrlList[0].getValue();
return URI.create(newUrl);
}
}
@Override
public boolean isRedirectRequested(HttpResponse response,
HttpContext context) {
int statusCode = response.getStatusLine().getStatusCode();
switch (statusCode) {
case HttpStatus.SC_MOVED_TEMPORARILY:
case HttpStatus.SC_MOVED_PERMANENTLY:
case HttpStatus.SC_SEE_OTHER:
case HttpStatus.SC_TEMPORARY_REDIRECT:
return true;
default:
break;
}
return false;
}
private void sailing() throws InterruptedException {
if(mCancel) {
return;
}
InputStream is = null;
ByteArrayOutputStream os = null;
try {
DefaultHttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), mConnectionTimeOut);
HttpConnectionParams.setSoTimeout(client.getParams(), mReadTimeOut);
if(null != mRedirectHandler) {
client.setRedirectHandler(mRedirectHandler);
}
HttpGet getter = new HttpGet(mUrl);
if(null != mUserAgent) {
getter.setHeader("User-Agent", mUserAgent);
}
HttpResponse response = client.execute(getter);
if(Thread.interrupted()) {
return;
}
int status = response.getStatusLine().getStatusCode();
mHeaders = response.getAllHeaders();
if(null != mOnResponseListener) {
mOnResponseListener.onResponse(status, mHeaders, this);
}
if(status != HttpStatus.SC_OK) {
if(null != mOnErrorListener) {
mOnErrorListener.onError(-1, this);
}
}
if(status == HttpStatus.SC_OK && !Thread.interrupted()) {
HttpEntity entity = response.getEntity();
is = entity.getContent();
os = new ByteArrayOutputStream();
byte[] buffer = new byte[16*1024];
int len = 0;
if(!Thread.interrupted()) {
len = is.read(buffer);
while(-1 != len && !Thread.interrupted()) {
os.write(buffer, 0, len);
len = is.read(buffer);
if(null != mOnReadListener) {
mOnReadListener.onRead(buffer, len, this);
}
}
}
if(null != mOnCompletedListener) {
mOnCompletedListener.onComplete(status, mHeaders, os.toByteArray(), this);
}
}
} catch(Exception e) {
if(null != mOnErrorListener) {
mOnErrorListener.onError(-1, this);
}
} finally {
if(null != is) {
try {
is.close();
} catch(Exception ex) {
}
}
if(null != os) {
try {
os.close();
} catch(Exception ex) {
}
}
}
}
}
|
zzdache
|
trunk/android/Common/sdk/com/zz/common/tools/box/tools/BpClientUrlLoader.java
|
Java
|
epl
| 6,664
|
package com.zz.common.tools.box.tools;
public interface IBpFuture extends Runnable {
public void cancel();
}
|
zzdache
|
trunk/android/Common/sdk/com/zz/common/tools/box/tools/IBpFuture.java
|
Java
|
epl
| 116
|
package com.zz.common.tools.box.tools;
import org.apache.http.Header;
import android.util.Log;
import com.zz.common.tools.box.tools.BpClientUrlLoader.OnCompletedListener;
import com.zz.common.tools.box.tools.BpClientUrlLoader.OnErrorListener;
public class BpClientDataLoader extends BpFuture{
public interface IBpOnDataLoaderCompleteListener {
public void onComplete(int errCode, Object obj, Header[] headers, BpClientDataLoader loader);
}
public static final int DATA_LOADER_PARSE_ERROR = 1000;
private static final String TAG = "BpDataLoader";
private IBpOnDataLoaderCompleteListener mOnDataLoaderCompleteListener;
private BpClientUrlLoader mUrlLoader;
protected IBpDataLoaderParser mParser;
// protected BpRunner mRunner;
protected int mError = 0;
public BpClientDataLoader(String url, IBpDataLoaderParser parser) {
mParser = parser;
mUrlLoader = new BpClientUrlLoader(url);
mUrlLoader.setOnCompleteListener(new OnCompletedListener() {
@Override
public void onComplete(int respCode, Header[] headers, byte[] content,
BpClientUrlLoader loader) {
Object obj = null;
if(respCode == 200) {
String str = new String(content);
Log.i(TAG, str);
if(null != mParser) {
obj = mParser.parse(content);
mError = mParser.getError();
}
} else {
mError = respCode;
}
if(null != mOnDataLoaderCompleteListener){
mOnDataLoaderCompleteListener.onComplete(mError, obj, headers, BpClientDataLoader.this);
}
}
});
mUrlLoader.setOnErrorListener(new OnErrorListener() {
@Override
public void onError(int errCode, BpClientUrlLoader loader) {
mError = errCode;
if(null != mOnDataLoaderCompleteListener) {
mOnDataLoaderCompleteListener.onComplete(mError, null, null, BpClientDataLoader.this);
}
}
});
}
public void setUserAgent(String userAgent) {
}
@Override
public void run() {
Log.i(TAG, "run------------");
if(null != mUrlLoader){
mUrlLoader.run();
}
}
@Override
public void cancel() {
if(null != mUrlLoader){
mUrlLoader.cancel();
super.cancel();
}
}
public void setBpOnDataLoaderCompleteListener(IBpOnDataLoaderCompleteListener listener) {
if(null != listener){
mOnDataLoaderCompleteListener = listener;
}
}
}
|
zzdache
|
trunk/android/Common/sdk/com/zz/common/tools/box/tools/BpClientDataLoader.java
|
Java
|
epl
| 2,390
|
package com.zz.common.tools.box.tools;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.util.Log;
import com.zz.common.tools.box.tools.BpUrlLoader.IBpOnUrlLoaderCompleteListener;
import com.zz.common.tools.box.tools.BpUrlLoader.IBpOnUrlLoaderErrorListener;
public class BpDataLoader extends BpFuture {
public interface IBpOnDataLoaderCompleteListener {
public void onComplete(int errCode, Object obj, Map<String, List<String>> headers, BpDataLoader loader);
}
public static final int DATA_LOADER_PARSE_ERROR = 1000;
private static final String TAG = "BpDataLoader";
private IBpOnDataLoaderCompleteListener mOnDataLoaderCompleteListener;
private BpUrlLoader mUrlLoader;
protected IBpDataLoaderParser mParser;
// protected BpRunner mRunner;
protected int mError = 0;
public BpDataLoader(String url, String httpMethod, String contentIfPost, IBpDataLoaderParser parser) {
this(url, httpMethod, contentIfPost, null, null,parser);
}
public BpDataLoader(String url, String httpMethod, String contentIfPost, String filePathIfPost, IBpDataLoaderParser parser) {
this(url, httpMethod, contentIfPost, filePathIfPost, null, parser);
}
public BpDataLoader(String url, String httpMethod, String contentIfPost,
String filePathIfPost, HashMap<String, String> httpHeadersIfPost, IBpDataLoaderParser parser) {
mParser = parser;
// mRunner = runner;
mUrlLoader = new BpUrlLoader(url);
mUrlLoader.setBpOnUrlLoaderCompleteListener(new IBpOnUrlLoaderCompleteListener() {
public void onComplete(int respCode, Map<String, List<String>> headers,
byte[] content, BpUrlLoader loader) {
Object obj = null;
if(respCode == 200) {
String str = new String(content);
Log.i(TAG, str);
if(null != mParser) {
obj = mParser.parse(content);
mError = mParser.getError();
}
} else {
mError = respCode;
}
// int status = mError == 0 ? RunnerInfo.STATUS_SUCCEED : RunnerInfo.STATUS_FAILED;
// mRunner.setStatus(status);
if(null != mOnDataLoaderCompleteListener){
mOnDataLoaderCompleteListener.onComplete(mError, obj, headers, BpDataLoader.this);
}
}
});
mUrlLoader.setBpOnUrlLoaderErrorListener(new IBpOnUrlLoaderErrorListener() {
public void onError(int errCode, BpUrlLoader loader) {
mError = errCode;
// mRunner.setStatus(RunnerInfo.STATUS_FAILED);
if(null != mOnDataLoaderCompleteListener) {
mOnDataLoaderCompleteListener.onComplete(mError, null, null, BpDataLoader.this);
}
}
});
mUrlLoader.setHttpMethod(httpMethod, contentIfPost, filePathIfPost, httpHeadersIfPost);
}
@Override
public void run() {
Log.i(TAG, "run------------");
if(null != mUrlLoader){
mUrlLoader.run();
}
}
@Override
public void cancel() {
if(null != mUrlLoader){
mUrlLoader.cancel();
super.cancel();
}
}
public void setBpOnDataLoaderCompleteListener(IBpOnDataLoaderCompleteListener listener) {
if(null != listener){
mOnDataLoaderCompleteListener = listener;
}
}
}
|
zzdache
|
trunk/android/Common/sdk/com/zz/common/tools/box/tools/BpDataLoader.java
|
Java
|
epl
| 3,145
|
package com.zz.common.tools.box.tools;
import java.io.ByteArrayInputStream;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.InputSource;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
public abstract class BpXMLParser extends IBpDataLoaderParser implements ContentHandler{
protected Object mResult;
protected StringBuilder mBuffer = new StringBuilder();
@Override
public final Object parse(byte[] b) {
SAXParserFactory factory=SAXParserFactory.newInstance();
try {
SAXParser parser=factory.newSAXParser();
XMLReader xmlReader=parser.getXMLReader();
xmlReader.setContentHandler(this);
xmlReader.parse(new InputSource(new ByteArrayInputStream(b)));
} catch(Exception ex) {
mErrCode = BpDataLoader.DATA_LOADER_PARSE_ERROR;
mResult = null;
}
return mResult;
}
@Override
public void startDocument () throws SAXException {
}
@Override
public void startElement (String uri, String localName,
String qName, Attributes atts) throws SAXException {
}
@Override
public void characters (char ch[], int start, int length) throws SAXException {
mBuffer.append(ch, start, length);
}
@Override
public void endElement (String uri, String localName,
String qName) throws SAXException {
mBuffer.setLength(0);
}
@Override
public void endDocument() throws SAXException {
}
@Override
public void startPrefixMapping(String prefix, String uri)
throws SAXException {
}
@Override
public void skippedEntity(String name) throws SAXException {
}
@Override
public void setDocumentLocator(Locator locator) {
}
@Override
public void processingInstruction(String target, String data)
throws SAXException {
}
@Override
public void ignorableWhitespace(char[] ch, int start, int length)
throws SAXException {
}
@Override
public void endPrefixMapping(String prefix) throws SAXException {
}
}
|
zzdache
|
trunk/android/Common/sdk/com/zz/common/tools/box/tools/BpXMLParser.java
|
Java
|
epl
| 2,229
|
package com.zz.common.tools.box.tools;
public abstract class IBpDataLoaderParser {
protected int mErrCode;
public int getError() {
return mErrCode;
}
public abstract Object parse(byte []content);
}
|
zzdache
|
trunk/android/Common/sdk/com/zz/common/tools/box/tools/IBpDataLoaderParser.java
|
Java
|
epl
| 219
|
package com.zz.common.tools.box.tools;
import org.json.JSONException;
import org.json.JSONObject;
public abstract class BpJSONParser extends IBpDataLoaderParser {
public abstract Object parseJson(JSONObject obj) throws JSONException;
@Override
public final Object parse(byte[] b) {
String strJson = new String(b);
try {
JSONObject obj = new JSONObject(strJson);
return parseJson(obj);
} catch (JSONException e) {
mErrCode = BpDataLoader.DATA_LOADER_PARSE_ERROR;
return null;
}
}
}
|
zzdache
|
trunk/android/Common/sdk/com/zz/common/tools/box/tools/BpJSONParser.java
|
Java
|
epl
| 534
|
package com.zz.common.tools.box.tools;
public abstract class BpFuture implements IBpFuture {
protected boolean mCancel;
public abstract void run();
public void cancel() {
mCancel = true;
}
public boolean isCanceled() {
return mCancel;
}
}
|
zzdache
|
trunk/android/Common/sdk/com/zz/common/tools/box/tools/BpFuture.java
|
Java
|
epl
| 265
|
package com.zz.common.tools.box.tools;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.net.HttpURLConnection;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Future;
import com.zz.common.tools.box.BpBox;
import com.zz.common.tools.box.runner.RunnerInfo;
import com.zz.common.utils.FileUtil;
import com.zz.common.utils.ZLog;
public class IconBox extends BpBox{
public IconBox() {
super(null, null);
}
public interface OnLoadIconListener{
public void onSuccess(String iconUrl, String localPath, IconBox box);
public void onFailed(String iconUrl, int errCode, IconBox box);
}
private static final String TAG = "IconBox";
private String mIconUrl;
private String mLocalPath;
private OnLoadIconListener mListener;
private BufferedOutputStream mOutputStream;
public int loadIcon(String iconUrl, String filePath, OnLoadIconListener listener) {
// Util.log(TAG, "" + mIconUrl);
mIconUrl = iconUrl;
mListener = listener;
mLocalPath = filePath;
int taskId = 0;
if(mIconUrl.equals(mLocalPath)) {
BpFuture future = new BpFuture() {
@Override
public void run() {
if(FileUtil.isFileExist(mLocalPath)) {
mListener.onSuccess(mIconUrl, mLocalPath, IconBox.this);
setStatus(RunnerInfo.STATUS_SUCCEED);
} else {
mListener.onFailed(mIconUrl, -1, IconBox.this);
setStatus(RunnerInfo.STATUS_FAILED);
}
}
};
setBpFuture(future);
taskId = runBox(this);
} else {
BpUrlLoader urlLoader = new BpUrlLoader(mIconUrl);
// urlLoader.setHttpMethod("GET", null);
urlLoader.setHttpMethod("GET", null, null, null);
urlLoader.setBpOnUrlLoaderCompleteListener(new BpUrlLoader.IBpOnUrlLoaderCompleteListener() {
public void onComplete(int respCode, Map<String, List<String>> headers,
byte[] content, BpUrlLoader loader) {
ZLog.d(TAG, mIconUrl + "\n\t\tCompleted " + mListener);
setStatus(RunnerInfo.STATUS_SUCCEED);
if(null != mOutputStream) {
try {
mOutputStream.close();
mOutputStream = null;
File file = new File(mLocalPath + "~tmp");
file.renameTo(new File(mLocalPath));
} catch(Exception e) {
}
}
if(null != mListener) {
// if(HttpURLConnection.HTTP_OK == respCode && isValidFile(headers)) {
if(HttpURLConnection.HTTP_OK == respCode) {
mListener.onSuccess(mIconUrl, mLocalPath, IconBox.this);
} else {
mListener.onFailed(mIconUrl, respCode, IconBox.this);
}
}
}
});
urlLoader.setBpOnUrlLoaderErrorListener(new BpUrlLoader.IBpOnUrlLoaderErrorListener() {
@Override
public void onError(int errCode, BpUrlLoader loader) {
ZLog.d(TAG, mIconUrl + "\n\t\tFailed " + mListener);
setStatus(RunnerInfo.STATUS_FAILED);
if(null != mOutputStream) {
try {
mOutputStream.close();
mOutputStream = null;
} catch(Exception e) {
}
}
if(null != mListener) {
mListener.onFailed(mIconUrl, errCode, IconBox.this);
}
}
});
urlLoader.setBpOnUrlLoaderReadListener(new BpUrlLoader.IBpOnUrlLoaderReadListener() {
@Override
public void onRead(byte[] buffer, int readedBytes, BpUrlLoader loader) {
try {
if (mOutputStream == null) {
mOutputStream = new BufferedOutputStream(
new FileOutputStream(new File(mLocalPath + "~tmp")));
}
if (null != mOutputStream) {
mOutputStream.write(buffer, 0, readedBytes);
}
} catch (IOException e) {
e.printStackTrace();
loader.cancel();
}
}
});
setBpFuture(urlLoader);
taskId = runBox(this);
}
return taskId;
}
}
|
zzdache
|
trunk/android/Common/sdk/com/zz/common/tools/box/tools/IconBox.java
|
Java
|
epl
| 3,937
|
package com.zz.common.tools.box.tools;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.zz.common.utils.ZLog;
import android.util.Log;
public class BpUrlLoader extends BpFuture {
public interface IBpOnUrlLoaderErrorListener {
public void onError(int errCode, BpUrlLoader loader);
}
public interface IBpOnUrlLoaderReadListener {
public void onRead(byte[] buffer, int readedBytes, BpUrlLoader loader);
}
public interface IBpOnResponseListener {
public void onResponse(int respCode, Map<String, List<String>> headers, BpUrlLoader loader);
}
public interface IBpOnUrlLoaderCompleteListener {
public void onComplete(int respCode, Map<String, List<String>> headers,
byte[] content, BpUrlLoader loader);
}
private static final String TAG = "BpUrlLoader";
private static final int DEFAULT_CONNECT_TIME_OUT = 60000;
private static final int DEFAULT_READ_TIME_OUT = 300000;
private IBpOnUrlLoaderErrorListener mOnErrorListener;
private IBpOnUrlLoaderCompleteListener mOnCompleteListener;
private IBpOnUrlLoaderReadListener mOnReadListener;
private IBpOnResponseListener mOnResponseListener;
private HttpURLConnection mHttpConn;
private String mUrl;
private Map<String, String> mHttpHeaders;
private String mHttpMethod;
private String mPostContent;
private String mPostFilePath;
private int mConnectionTimeOut;
private int mReadTimeOut;
private boolean mCancel = false;
private Thread mThread = null;
public BpUrlLoader(String url) {
mUrl = url;
mHttpMethod = "GET";
mConnectionTimeOut = DEFAULT_CONNECT_TIME_OUT;
mReadTimeOut = DEFAULT_READ_TIME_OUT;
mCancel = false;
mHttpHeaders = new HashMap<String, String>();
}
@Override
public void run() {
Log.i(TAG, "run--------------");
try {
mThread = Thread.currentThread();
sailing();
} catch (InterruptedException e) {
}
}
@Override
public void cancel() {
super.cancel();
mOnReadListener = null;
mOnResponseListener = null;
mOnErrorListener = null;
mOnCompleteListener = null;
if(null != mThread && !mThread.isInterrupted()) {
mThread.interrupt();
mThread = null;
}
}
public void setBpOnUrlLoaderErrorListener(IBpOnUrlLoaderErrorListener listener) {
if(null != listener) {
mOnErrorListener = listener;
}
}
public void setBpOnUrlLoaderCompleteListener(IBpOnUrlLoaderCompleteListener listener) {
if(null != listener) {
mOnCompleteListener = listener;
}
}
public void setBpOnUrlLoaderReadListener(IBpOnUrlLoaderReadListener listener) {
if(null != listener) {
mOnReadListener = listener;
}
}
public void setOnResponseListener(IBpOnResponseListener l) {
mOnResponseListener = l;
}
public void setHttpMethod(String method, String contentIfPost,
String filePathIfPost, HashMap<String, String> httpHeadersIfPost) {
mHttpMethod = method;
mPostContent = contentIfPost;
mPostFilePath = filePathIfPost;
mHttpHeaders = httpHeadersIfPost;
}
public void setTimeOut(int connectionTime, int readTime) {
if(connectionTime > 0) {
mConnectionTimeOut = connectionTime;
}
if(readTime > 0) {
mReadTimeOut = readTime;
}
}
private void sailing() throws InterruptedException {
if(mCancel) {
return;
}
if(!openConnection()) {
if(null != mOnErrorListener && !mCancel) {
mOnErrorListener.onError(-1, this);
}
return;
}
if(mHttpMethod.equals("POST")) {
OutputStream os = null;
try {
os = mHttpConn.getOutputStream();
os.write(mPostContent.getBytes());
if(null != mPostFilePath) {
RandomAccessFile file = new RandomAccessFile(mPostFilePath, "rw");
int len = -1;
byte[] buf = new byte[1024];
len = file.read(buf);
while(-1 != len) {
os.write(buf);
len = file.read(buf);
}
file.close();
}
os.flush();
os.close();
} catch (IOException e) {
closeConnection(null, os);
if(null != mOnErrorListener && !mCancel) {
mOnErrorListener.onError(-1, this);
}
return;
}
}
Map<String, List<String>> headers = null;
int respCode = -1;
InputStream is = null;
byte[] content = null;
ByteArrayOutputStream bos = new ByteArrayOutputStream(1024);
try {
respCode = mHttpConn.getResponseCode();
headers = mHttpConn.getHeaderFields();
if(null != mOnResponseListener) {
mOnResponseListener.onResponse(respCode, headers, this);
}
if(!Thread.interrupted()) {
is = mHttpConn.getInputStream();
long contentLength = mHttpConn.getContentLength();
ZLog.d(TAG, "contentLength = " + contentLength);
int readedBytes = 0;
byte[] b = new byte[16384];
while(!Thread.interrupted() && -1 != (readedBytes = is.read(b))) {
bos.write(b, 0, readedBytes);
if(null != mOnReadListener) {
mOnReadListener.onRead(b, readedBytes, this);
}
Thread.sleep(200);
}
content = bos.toByteArray();
bos.close();
}
} catch (Exception e) {
e.printStackTrace();
closeConnection(is, bos);
if(null != mOnErrorListener && !mCancel) {
mOnErrorListener.onError(-1, this);
}
return;
}
closeConnection(is, null);
if(null != mOnCompleteListener && !mCancel) {
mOnCompleteListener.onComplete(respCode, headers, content, this);
}
}
private boolean openConnection() {
try {
Log.i(TAG, mUrl);
URL url = new URL(mUrl);
mHttpConn = (HttpURLConnection) url.openConnection();
mHttpConn.setDoInput(true);
mHttpConn.setUseCaches(false);
if(null != mHttpHeaders) {
Set<String> keys = mHttpHeaders.keySet();
for(String key : keys) {
mHttpConn.setRequestProperty(key, mHttpHeaders.get(key));
}
}
mHttpConn.setConnectTimeout(mConnectionTimeOut);
mHttpConn.setReadTimeout(mReadTimeOut);
mHttpConn.setRequestMethod(mHttpMethod);
if(mHttpMethod.equals("POST")) {
mHttpConn.setDoOutput(true);
}
} catch (MalformedURLException e) {
closeHttpConnection();
return false;
} catch (IOException e) {
closeHttpConnection();
return false;
}
return true;
}
private void closeHttpConnection() {
if(null != mHttpConn) {
mHttpConn.disconnect();
mHttpConn = null;
}
}
private void closeConnection(InputStream is, OutputStream os) {
if(null != is){
try {
is.close();
} catch (IOException e){
}
}
if(null != os){
try {
os.close();
} catch (IOException e){
}
}
}
}
|
zzdache
|
trunk/android/Common/sdk/com/zz/common/tools/box/tools/BpUrlLoader.java
|
Java
|
epl
| 6,970
|
package com.zz.common.tools.box;
public class BpToken {
public int mRunnerId;
public Object mResult;
public Object mUserData;
}
|
zzdache
|
trunk/android/Common/sdk/com/zz/common/tools/box/BpToken.java
|
Java
|
epl
| 139
|
package com.zz.common.tools.box;
import com.zz.common.tools.box.runner.BpRunner;
import android.os.Handler;
public class BpBox extends BpRunner {
protected Handler mListener;
protected Object mUserData;
protected BpBox(Handler listener, Object userData) {
mListener = listener;
mUserData = userData;
}
public static int runBox(BpBox box){
return BpBoxManager.getInstance().startRunner(box);
}
public static void cancel(int runnerId){
BpBoxManager.getInstance().stopRunner(runnerId);
}
public static void cancelAll() {
BpBoxManager.getInstance().stopAll();
}
@Override
public void stop() {
mUserData = null;
mListener = null;
super.stop();
}
}
|
zzdache
|
trunk/android/Common/sdk/com/zz/common/tools/box/BpBox.java
|
Java
|
epl
| 716
|
package com.zz.common.tools.box;
import com.zz.common.tools.box.runner.BpRunnerManager;
public class BpBoxManager extends BpRunnerManager {
private static BpBoxManager mInstance = null;
private BpBoxManager() {
super();
}
public static BpBoxManager getInstance() {
if(null == mInstance) {
mInstance = new BpBoxManager();
}
return mInstance;
}
}
|
zzdache
|
trunk/android/Common/sdk/com/zz/common/tools/box/BpBoxManager.java
|
Java
|
epl
| 380
|
package com.zz.common.tools;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import com.zz.common.tools.BaseLruCache.BitmapLruCache;
import com.zz.common.tools.box.tools.IconBox;
import com.zz.common.tools.box.tools.IconBox.OnLoadIconListener;
import com.zz.common.utils.FileUtil;
import com.zz.common.utils.ImageUtil;
import com.zz.common.utils.ZLog;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
public class ImageLoader implements Callback {
public static final int ACTION_IMAGE_LOADER = 10086;
public interface IUrlLocalFilePathCreator {
public String createLocalFilePathForUrl(String url);
}
private static final String TAG = "ImageLoader";
private static BitmapLruCache sCache = new BitmapLruCache(2 * 1024 * 1024); //2M���ڼ���ͼƬ
private final WeakReferenceHandler mHandler;
private IUrlLocalFilePathCreator mCreator;
/*
*
*/
public interface OnFinishLoadingListener {
public void onFinish(int errCode, IconFlinger flinger);
}
/*
*
*/
public class IconToken {
public String mUrl;
public Object mUserData;
private Object mListener;
public int mTaskId;
private boolean mIsLocal;
public IconToken(String url, Handler listener, Object userData) {
mUrl = url;
mListener = listener;
mUserData = userData;
setIsLocal();
}
public IconToken(String url, OnFinishLoadingListener listener, Object userData) {
mUrl = url;
mListener = listener;
mUserData = userData;
setIsLocal();
}
private void setIsLocal() {
mIsLocal = (!mUrl.startsWith("http://") && !mUrl.startsWith("https://"));
}
}
/*
*
*/
protected ImageLoader(IUrlLocalFilePathCreator creator) {
mHandler = new WeakReferenceHandler(this);
mCreator = creator;
}
public class IconFlinger {
public Bitmap mIcon;
public IconToken mToken;
public IconFlinger(IconToken token) {
mToken = token;
}
void sendResult(Bitmap bitmap, int errCode) {
Object listener = mToken.mListener;
if(null != listener) {
mIcon = bitmap;
if(Handler.class.isInstance(listener)) {
Message msg = ((Handler)listener).obtainMessage(ACTION_IMAGE_LOADER, errCode, 0, this);
if(String.class.isInstance(mToken.mUserData)) {
Bundle b = new Bundle();
b.putString("userData", (String)mToken.mUserData);
msg.setData(b);
}
msg.sendToTarget();
} else {
mHandler.post(new FlingerRunner(this, errCode));
}
ZLog.d(TAG, "sendResult: " +mIcon + ", "+ mToken.mListener + ", " + mToken.mUserData + ", " + mToken.mUrl);
}
}
}
/*
*
*/
public Map<String, List<IconFlinger>> mFlingers = new Hashtable<String, List<IconFlinger> >();
/*
*
*/
public void cancelLoadIcon(IconToken token) {
if(null == token) {
return;
}
ZLog.d(TAG, "cancelLoadIcon: " + token.mListener + ", " + token.mUserData + ", " + token.mUrl);
synchronized (mFlingers) {
List<IconFlinger> list = mFlingers.get(token.mUrl);
if(null != list) {
int i;
for(i = 0; i<list.size(); ) {
IconFlinger flinger = list.get(i);
if(flinger.mToken == token) {
list.remove(i);
} else {
i++;
}
}
if(0 == list.size()) {
mFlingers.remove(token.mUrl);
IconBox.cancel(token.mTaskId);
}
}
}
}
public void cancelAll() {
synchronized (mFlingers) {
Iterator<List<IconFlinger>> temp = mFlingers.values().iterator();
while(temp.hasNext()) {
List<IconFlinger> list = temp.next();
IconBox.cancel(list.get(0).mToken.mTaskId);
}
mFlingers.clear();
}
}
public Bitmap getIconFromCache(String iconUrl) {
Bitmap map = getIconFromLocalCache(iconUrl, true);
return map;
}
public IconToken loadIcon(String url, Handler listener, Object userData) {
return loadIcon(new IconToken(url, listener, userData), true);
}
public IconToken loadIcon(String url, OnFinishLoadingListener listener, Object userData) {
return loadIcon(new IconToken(url, listener, userData), false);
}
@Override //Handler.Callback
public boolean handleMessage(Message msg) {
return false;
}
private IconToken loadIcon(IconToken token, boolean includeSDCard) {
ZLog.d(TAG, "loadIcon: " + token.mUrl + ", " + token.mUserData + ", " + token.mListener);
String url = token.mUrl;
if(null == url) {
return null;
}
//��RAM�������
IconFlinger flinger = new IconFlinger(token);
Bitmap b = getIconFromLocalCache(url, includeSDCard);
if(null != b) {
flinger.sendResult(b, 0);
return flinger.mToken;
}
String localPath = null;
if(token.mIsLocal) {
localPath = token.mUrl;
} else {
localPath = mCreator.createLocalFilePathForUrl(url);
}
//�ӷ�������ȡ
synchronized (mFlingers) {
List<IconFlinger> flingerList = mFlingers.get(url);
if(null == flingerList) {
flingerList = new ArrayList<IconFlinger>();
mFlingers.put(url, flingerList);
IconBox box = new IconBox();
flinger.mToken.mTaskId = box.loadIcon(url, localPath, new OnLoadIconListener() {
@Override
public void onFailed(String iconUrl, int errCode,
IconBox box) {
ZLog.d(TAG, "failed loadIcon: " + iconUrl);
List<IconFlinger> list = mFlingers.get(iconUrl);
if(null != list) {
for(IconFlinger flinger: list) {
flinger.sendResult(null, errCode);
}
}
mFlingers.remove(iconUrl);
}
@Override
public void onSuccess(String iconUrl, String localPath,
IconBox box) {
ZLog.d(TAG, "success loadIcon: " + iconUrl);
List<IconFlinger> list = mFlingers.get(iconUrl);
Bitmap b = ImageUtil.decodeLocalFile(localPath, 0);
int errCode = -1;
if(null != b) {
errCode = 0;
addToCache(iconUrl, b);
}
if(null != list) {
for(IconFlinger flinger: list) {
flinger.sendResult(b, errCode);
}
}
mFlingers.remove(iconUrl);
}
});
} else {
flinger.mToken.mTaskId = flingerList.get(0).mToken.mTaskId;
}
flingerList.add(flinger);
}
return flinger.mToken;
}
private Bitmap getIconFromLocalCache(String iconUrl, boolean includeSDCard) {
if(null == iconUrl) {
return null;
}
Bitmap map = sCache.get(iconUrl);
return map;
}
private void addToCache(String iconUrl, Bitmap b) {
sCache.put(iconUrl, b);
}
private class FlingerRunner implements Runnable {
private IconFlinger mFlinger;
private int mErrCode;
private FlingerRunner(IconFlinger flinger, int errCode) {
mFlinger = flinger;
mErrCode = errCode;
}
@Override
public void run() {
((OnFinishLoadingListener)mFlinger.mToken.mListener).onFinish(mErrCode, mFlinger);
mFlinger = null;
}
}
}
|
zzdache
|
trunk/android/Common/sdk/com/zz/common/tools/ImageLoader.java
|
Java
|
epl
| 7,198
|