Merge branch 'reformat'

This commit is contained in:
Bernd Ahlers 2014-10-21 17:05:58 +02:00
commit 7380b94581
101 changed files with 9165 additions and 8926 deletions

View File

@ -14,305 +14,305 @@ import org.graylog2.syslog4j.util.SyslogUtility;
/**
* This class provides a Singleton interface for Syslog4j client implementations.
*
* <p/>
* <p>Usage examples:</p>
*
* <p/>
* <b>Direct</b>
* <pre>
* Syslog.getInstance("udp").info("log message");
* </pre>
*
* <p/>
* <b>Via Instance</b>
* <pre>
* SyslogIF syslog = Syslog.getInstance("udp");
* syslog.info();
* </pre>
*
* <p/>
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: Syslog.java,v 1.23 2011/01/23 20:49:12 cvs Exp $
*/
public final class Syslog implements SyslogConstants {
private static final long serialVersionUID = -4662318148650646144L;
private static boolean SUPPRESS_RUNTIME_EXCEPTIONS = false;
protected static final Map instances = new Hashtable();
static {
initialize();
}
/**
* Syslog is a singleton.
*/
private Syslog() {
//
}
/**
* @return Returns the current version identifier for Syslog4j.
*/
public static final String getVersion() {
return Syslog4jVersion.VERSION;
}
/**
* @param suppress - true to suppress throwing SyslogRuntimeException in many methods of this class, false to throw exceptions (default)
*/
public static void setSuppressRuntimeExceptions(boolean suppress) {
SUPPRESS_RUNTIME_EXCEPTIONS = suppress;
}
/**
* @return Returns whether or not to suppress throwing SyslogRuntimeException in many methods of this class.
*/
public static boolean getSuppressRuntimeExceptions() {
return SUPPRESS_RUNTIME_EXCEPTIONS;
}
/**
* Throws SyslogRuntimeException unless it has been suppressed via setSuppressRuntimeException(boolean).
*
* @param message
* @throws SyslogRuntimeException
*/
private static void throwRuntimeException(String message) throws SyslogRuntimeException {
if (SUPPRESS_RUNTIME_EXCEPTIONS) {
return;
} else {
throw new SyslogRuntimeException(message.toString());
}
}
private static final long serialVersionUID = -4662318148650646144L;
/**
* Use getInstance(protocol) as the starting point for Syslog4j.
*
* @param protocol - the Syslog protocol to use, e.g. "udp", "tcp", "unix_syslog", "unix_socket", or a custom protocol
* @return Returns an instance of SyslogIF.
* @throws SyslogRuntimeException
*/
public static final SyslogIF getInstance(String protocol) throws SyslogRuntimeException {
String _protocol = protocol.toLowerCase();
if (instances.containsKey(_protocol)) {
return (SyslogIF) instances.get(_protocol);
} else {
StringBuffer message = new StringBuffer("Syslog protocol \"" + protocol + "\" not defined; call Syslogger.createSyslogInstance(protocol,config) first");
if (instances.size() > 0) {
message.append(" or use one of the following instances: ");
Iterator i = instances.keySet().iterator();
while (i.hasNext()) {
String k = (String) i.next();
message.append(k);
if (i.hasNext()) {
message.append(' ');
}
}
}
throwRuntimeException(message.toString());
return null;
}
}
/**
* Use createInstance(protocol,config) to create your own Syslog instance.
*
* <p>First, create an implementation of SyslogConfigIF, such as UdpNetSyslogConfig.</p>
*
* <p>Second, configure that configuration instance.</p>
*
* <p>Third, call createInstance(protocol,config) using a short &amp; simple
* String for the protocol argument.</p>
*
* <p>Fourth, either use the returned instance of SyslogIF, or in later code
* call getInstance(protocol) with the protocol chosen in the previous step.</p>
*
* @param protocol
* @param config
* @return Returns an instance of SyslogIF.
* @throws SyslogRuntimeException
*/
public static final SyslogIF createInstance(String protocol, SyslogConfigIF config) throws SyslogRuntimeException {
if (protocol == null || "".equals(protocol.trim())) {
throwRuntimeException("Instance protocol cannot be null or empty");
return null;
}
if (config == null) {
throwRuntimeException("SyslogConfig cannot be null");
return null;
}
String syslogProtocol = protocol.toLowerCase();
SyslogIF syslog = null;
synchronized(instances) {
if (instances.containsKey(syslogProtocol)) {
throwRuntimeException("Syslog protocol \"" + protocol + "\" already defined");
return null;
}
try {
Class syslogClass = config.getSyslogClass();
syslog = (SyslogIF) syslogClass.newInstance();
} catch (ClassCastException cse) {
if (!config.isThrowExceptionOnInitialize()) {
throw new SyslogRuntimeException(cse);
} else {
return null;
}
} catch (IllegalAccessException iae) {
if (!config.isThrowExceptionOnInitialize()) {
throw new SyslogRuntimeException(iae);
} else {
return null;
}
} catch (InstantiationException ie) {
if (!config.isThrowExceptionOnInitialize()) {
throw new SyslogRuntimeException(ie);
} else {
return null;
}
}
syslog.initialize(syslogProtocol,config);
instances.put(syslogProtocol,syslog);
}
private static boolean SUPPRESS_RUNTIME_EXCEPTIONS = false;
return syslog;
}
protected static final Map instances = new Hashtable();
/**
* initialize() sets up the default TCP and UDP Syslog protocols, as
* well as UNIX_SYSLOG and UNIX_SOCKET (if running on a Unix-based system).
*/
public synchronized static final void initialize() {
createInstance(UDP,new UDPNetSyslogConfig());
createInstance(TCP,new TCPNetSyslogConfig());
if (OSDetectUtility.isUnix() && SyslogUtility.isClassExists(JNA_NATIVE_CLASS)) {
createInstance(UNIX_SYSLOG,new UnixSyslogConfig());
createInstance(UNIX_SOCKET,new UnixSocketSyslogConfig());
}
}
/**
* @param protocol - Syslog protocol
* @return Returns whether the protocol has been previously defined.
*/
public static final boolean exists(String protocol) {
if (protocol == null || "".equals(protocol.trim())) {
return false;
}
return instances.containsKey(protocol.toLowerCase());
}
/**
* shutdown() gracefully shuts down all defined Syslog protocols,
* which includes flushing all queues and connections and finally
* clearing all instances (including those initialized by default).
*/
public synchronized static final void shutdown() {
Set protocols = instances.keySet();
if (protocols.size() > 0) {
Iterator i = protocols.iterator();
SyslogUtility.sleep(SyslogConstants.THREAD_LOOP_INTERVAL_DEFAULT);
while(i.hasNext()) {
String protocol = (String) i.next();
SyslogIF syslog = (SyslogIF) instances.get(protocol);
syslog.shutdown();
}
static {
initialize();
}
instances.clear();
}
}
/**
* Syslog is a singleton.
*/
private Syslog() {
//
}
/**
* destroyInstance() gracefully shuts down the specified Syslog protocol and
* removes the instance from Syslog4j.
*
* @param protocol - the Syslog protocol to destroy
* @throws SyslogRuntimeException
*/
public synchronized static final void destroyInstance(String protocol) throws SyslogRuntimeException {
if (protocol == null || "".equals(protocol.trim())) {
return;
}
String _protocol = protocol.toLowerCase();
if (instances.containsKey(_protocol)) {
SyslogUtility.sleep(SyslogConstants.THREAD_LOOP_INTERVAL_DEFAULT);
SyslogIF syslog = (SyslogIF) instances.get(_protocol);
/**
* @return Returns the current version identifier for Syslog4j.
*/
public static final String getVersion() {
return Syslog4jVersion.VERSION;
}
try {
syslog.shutdown();
} finally {
instances.remove(_protocol);
}
} else {
throwRuntimeException("Cannot destroy protocol \"" + protocol + "\" instance; call shutdown instead");
return;
}
}
/**
* @param suppress - true to suppress throwing SyslogRuntimeException in many methods of this class, false to throw exceptions (default)
*/
public static void setSuppressRuntimeExceptions(boolean suppress) {
SUPPRESS_RUNTIME_EXCEPTIONS = suppress;
}
/**
* destroyInstance() gracefully shuts down the specified Syslog instance and
* removes it from Syslog4j.
*
* @param syslog - the Syslog instance to destroy
* @throws SyslogRuntimeException
*/
public synchronized static final void destroyInstance(SyslogIF syslog) throws SyslogRuntimeException {
if (syslog == null) {
return;
}
String protocol = syslog.getProtocol().toLowerCase();
if (instances.containsKey(protocol)) {
try {
syslog.shutdown();
} finally {
instances.remove(protocol);
}
} else {
throwRuntimeException("Cannot destroy protocol \"" + protocol + "\" instance; call shutdown instead");
return;
}
}
/**
* @return Returns whether or not to suppress throwing SyslogRuntimeException in many methods of this class.
*/
public static boolean getSuppressRuntimeExceptions() {
return SUPPRESS_RUNTIME_EXCEPTIONS;
}
public static void main(String[] args) throws Exception {
SyslogMain.main(args);
}
/**
* Throws SyslogRuntimeException unless it has been suppressed via setSuppressRuntimeException(boolean).
*
* @param message
* @throws SyslogRuntimeException
*/
private static void throwRuntimeException(String message) throws SyslogRuntimeException {
if (SUPPRESS_RUNTIME_EXCEPTIONS) {
return;
} else {
throw new SyslogRuntimeException(message.toString());
}
}
/**
* Use getInstance(protocol) as the starting point for Syslog4j.
*
* @param protocol - the Syslog protocol to use, e.g. "udp", "tcp", "unix_syslog", "unix_socket", or a custom protocol
* @return Returns an instance of SyslogIF.
* @throws SyslogRuntimeException
*/
public static final SyslogIF getInstance(String protocol) throws SyslogRuntimeException {
String _protocol = protocol.toLowerCase();
if (instances.containsKey(_protocol)) {
return (SyslogIF) instances.get(_protocol);
} else {
StringBuffer message = new StringBuffer("Syslog protocol \"" + protocol + "\" not defined; call Syslogger.createSyslogInstance(protocol,config) first");
if (instances.size() > 0) {
message.append(" or use one of the following instances: ");
Iterator i = instances.keySet().iterator();
while (i.hasNext()) {
String k = (String) i.next();
message.append(k);
if (i.hasNext()) {
message.append(' ');
}
}
}
throwRuntimeException(message.toString());
return null;
}
}
/**
* Use createInstance(protocol,config) to create your own Syslog instance.
* <p/>
* <p>First, create an implementation of SyslogConfigIF, such as UdpNetSyslogConfig.</p>
* <p/>
* <p>Second, configure that configuration instance.</p>
* <p/>
* <p>Third, call createInstance(protocol,config) using a short &amp; simple
* String for the protocol argument.</p>
* <p/>
* <p>Fourth, either use the returned instance of SyslogIF, or in later code
* call getInstance(protocol) with the protocol chosen in the previous step.</p>
*
* @param protocol
* @param config
* @return Returns an instance of SyslogIF.
* @throws SyslogRuntimeException
*/
public static final SyslogIF createInstance(String protocol, SyslogConfigIF config) throws SyslogRuntimeException {
if (protocol == null || "".equals(protocol.trim())) {
throwRuntimeException("Instance protocol cannot be null or empty");
return null;
}
if (config == null) {
throwRuntimeException("SyslogConfig cannot be null");
return null;
}
String syslogProtocol = protocol.toLowerCase();
SyslogIF syslog = null;
synchronized (instances) {
if (instances.containsKey(syslogProtocol)) {
throwRuntimeException("Syslog protocol \"" + protocol + "\" already defined");
return null;
}
try {
Class syslogClass = config.getSyslogClass();
syslog = (SyslogIF) syslogClass.newInstance();
} catch (ClassCastException cse) {
if (!config.isThrowExceptionOnInitialize()) {
throw new SyslogRuntimeException(cse);
} else {
return null;
}
} catch (IllegalAccessException iae) {
if (!config.isThrowExceptionOnInitialize()) {
throw new SyslogRuntimeException(iae);
} else {
return null;
}
} catch (InstantiationException ie) {
if (!config.isThrowExceptionOnInitialize()) {
throw new SyslogRuntimeException(ie);
} else {
return null;
}
}
syslog.initialize(syslogProtocol, config);
instances.put(syslogProtocol, syslog);
}
return syslog;
}
/**
* initialize() sets up the default TCP and UDP Syslog protocols, as
* well as UNIX_SYSLOG and UNIX_SOCKET (if running on a Unix-based system).
*/
public synchronized static final void initialize() {
createInstance(UDP, new UDPNetSyslogConfig());
createInstance(TCP, new TCPNetSyslogConfig());
if (OSDetectUtility.isUnix() && SyslogUtility.isClassExists(JNA_NATIVE_CLASS)) {
createInstance(UNIX_SYSLOG, new UnixSyslogConfig());
createInstance(UNIX_SOCKET, new UnixSocketSyslogConfig());
}
}
/**
* @param protocol - Syslog protocol
* @return Returns whether the protocol has been previously defined.
*/
public static final boolean exists(String protocol) {
if (protocol == null || "".equals(protocol.trim())) {
return false;
}
return instances.containsKey(protocol.toLowerCase());
}
/**
* shutdown() gracefully shuts down all defined Syslog protocols,
* which includes flushing all queues and connections and finally
* clearing all instances (including those initialized by default).
*/
public synchronized static final void shutdown() {
Set protocols = instances.keySet();
if (protocols.size() > 0) {
Iterator i = protocols.iterator();
SyslogUtility.sleep(SyslogConstants.THREAD_LOOP_INTERVAL_DEFAULT);
while (i.hasNext()) {
String protocol = (String) i.next();
SyslogIF syslog = (SyslogIF) instances.get(protocol);
syslog.shutdown();
}
instances.clear();
}
}
/**
* destroyInstance() gracefully shuts down the specified Syslog protocol and
* removes the instance from Syslog4j.
*
* @param protocol - the Syslog protocol to destroy
* @throws SyslogRuntimeException
*/
public synchronized static final void destroyInstance(String protocol) throws SyslogRuntimeException {
if (protocol == null || "".equals(protocol.trim())) {
return;
}
String _protocol = protocol.toLowerCase();
if (instances.containsKey(_protocol)) {
SyslogUtility.sleep(SyslogConstants.THREAD_LOOP_INTERVAL_DEFAULT);
SyslogIF syslog = (SyslogIF) instances.get(_protocol);
try {
syslog.shutdown();
} finally {
instances.remove(_protocol);
}
} else {
throwRuntimeException("Cannot destroy protocol \"" + protocol + "\" instance; call shutdown instead");
return;
}
}
/**
* destroyInstance() gracefully shuts down the specified Syslog instance and
* removes it from Syslog4j.
*
* @param syslog - the Syslog instance to destroy
* @throws SyslogRuntimeException
*/
public synchronized static final void destroyInstance(SyslogIF syslog) throws SyslogRuntimeException {
if (syslog == null) {
return;
}
String protocol = syslog.getProtocol().toLowerCase();
if (instances.containsKey(protocol)) {
try {
syslog.shutdown();
} finally {
instances.remove(protocol);
}
} else {
throwRuntimeException("Cannot destroy protocol \"" + protocol + "\" instance; call shutdown instead");
return;
}
}
public static void main(String[] args) throws Exception {
SyslogMain.main(args);
}
}

View File

@ -1,16 +1,16 @@
package org.graylog2.syslog4j;
/**
* Syslog4jVersion provides a unique version identifier that is created during
* the build process.
*
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: Syslog4jVersion.java,v 1.2 2008/10/28 01:07:06 cvs Exp $
*/
* Syslog4jVersion provides a unique version identifier that is created during
* the build process.
* <p/>
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: Syslog4jVersion.java,v 1.2 2008/10/28 01:07:06 cvs Exp $
*/
public final class Syslog4jVersion {
public static final String VERSION = "Syslog4j-graylog2 0.9.48 kroepke";
public static final String VERSION = "Syslog4j-graylog2 0.9.48 kroepke";
}

View File

@ -1,51 +1,51 @@
package org.graylog2.syslog4j;
/**
* SyslogBackLogHandlerIF provides a last-chance mechanism to log messages that fail
* (for whatever reason) within the rest of Syslog.
*
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* <p>Implementing the down(SyslogIF) method is an excellent way to add some sort of notification to
* your application when a Syslog service is unavailable.</p>
*
* <p>Implementing the up(SyslogIF) method can be used to notify your application when a Syslog
* service has returned.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: SyslogBackLogHandlerIF.java,v 1.2 2009/01/28 15:13:52 cvs Exp $
*/
* SyslogBackLogHandlerIF provides a last-chance mechanism to log messages that fail
* (for whatever reason) within the rest of Syslog.
* <p/>
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
* <p/>
* <p>Implementing the down(SyslogIF) method is an excellent way to add some sort of notification to
* your application when a Syslog service is unavailable.</p>
* <p/>
* <p>Implementing the up(SyslogIF) method can be used to notify your application when a Syslog
* service has returned.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: SyslogBackLogHandlerIF.java,v 1.2 2009/01/28 15:13:52 cvs Exp $
*/
public interface SyslogBackLogHandlerIF {
/**
* Implement initialize() to handle one-time set-up for this backLog handler.
*
* @throws SyslogRuntimeException
*/
public void initialize() throws SyslogRuntimeException;
/**
* Implement down(syslog,reason) to notify/log when the syslog protocol is unavailable.
*
* @param syslog - SyslogIF instance causing this down condition
* @param reason - reason given for the down condition
*/
public void down(SyslogIF syslog, String reason);
/**
* Implement initialize() to handle one-time set-up for this backLog handler.
*
* @throws SyslogRuntimeException
*/
public void initialize() throws SyslogRuntimeException;
/**
* Implement up(syslog) to notify/log when the syslog protocol becomes available after a down condition.
*
* @param syslog - SyslogIF instance which is now available
*/
public void up(SyslogIF syslog);
/**
* Implement down(syslog,reason) to notify/log when the syslog protocol is unavailable.
*
* @param syslog - SyslogIF instance causing this down condition
* @param reason - reason given for the down condition
*/
public void down(SyslogIF syslog, String reason);
/**
* @param syslog - SyslogIF instance which cannot handle this log event
* @param level - message level
* @param message - message (in String form)
* @param reason - reason given for why this message could not be handled
* @throws SyslogRuntimeException - throwing this Exception activates the next backlogHandler in the chain
*/
public void log(SyslogIF syslog, int level, String message, String reason) throws SyslogRuntimeException;
/**
* Implement up(syslog) to notify/log when the syslog protocol becomes available after a down condition.
*
* @param syslog - SyslogIF instance which is now available
*/
public void up(SyslogIF syslog);
/**
* @param syslog - SyslogIF instance which cannot handle this log event
* @param level - message level
* @param message - message (in String form)
* @param reason - reason given for why this message could not be handled
* @throws SyslogRuntimeException - throwing this Exception activates the next backlogHandler in the chain
*/
public void log(SyslogIF syslog, int level, String message, String reason) throws SyslogRuntimeException;
}

View File

@ -3,17 +3,18 @@ package org.graylog2.syslog4j;
import java.io.Serializable;
/**
* SyslogCharSetIF provides control of the encoding character set within
* several class of Syslog4j.
*
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: SyslogCharSetIF.java,v 1.3 2008/11/07 15:15:41 cvs Exp $
*/
* SyslogCharSetIF provides control of the encoding character set within
* several class of Syslog4j.
* <p/>
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: SyslogCharSetIF.java,v 1.3 2008/11/07 15:15:41 cvs Exp $
*/
public interface SyslogCharSetIF extends Serializable {
public String getCharSet();
public void setCharSet(String charSet);
public String getCharSet();
public void setCharSet(String charSet);
}

View File

@ -1,69 +1,90 @@
package org.graylog2.syslog4j;
/**
* SyslogConfigIF provides a common, extensible configuration interface for all
* implementations of SyslogIF.
*
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: SyslogConfigIF.java,v 1.19 2010/11/28 04:15:18 cvs Exp $
*/
* SyslogConfigIF provides a common, extensible configuration interface for all
* implementations of SyslogIF.
* <p/>
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: SyslogConfigIF.java,v 1.19 2010/11/28 04:15:18 cvs Exp $
*/
public interface SyslogConfigIF extends SyslogConstants, SyslogCharSetIF {
public Class getSyslogClass();
public int getFacility();
public void setFacility(int facility);
public void setFacility(String facilityName);
public int getPort();
public void setPort(int port) throws SyslogRuntimeException;
public Class getSyslogClass();
public String getLocalName();
public void setLocalName(String localName) throws SyslogRuntimeException;
public int getFacility();
public String getHost();
public void setHost(String host) throws SyslogRuntimeException;
public String getIdent();
public void setIdent(String ident);
public String getCharSet();
public void setCharSet(String charSet);
public boolean isIncludeIdentInMessageModifier();
public void setIncludeIdentInMessageModifier(boolean throwExceptionOnInitialize);
public void setFacility(int facility);
public boolean isThrowExceptionOnInitialize();
public void setThrowExceptionOnInitialize(boolean throwExceptionOnInitialize);
public void setFacility(String facilityName);
public boolean isThrowExceptionOnWrite();
public void setThrowExceptionOnWrite(boolean throwExceptionOnWrite);
public int getPort();
public boolean isSendLocalTimestamp();
public void setSendLocalTimestamp(boolean sendLocalTimestamp);
public boolean isSendLocalName();
public void setSendLocalName(boolean sendLocalName);
public boolean isTruncateMessage();
public void setTruncateMessage(boolean truncateMessage);
public boolean isUseStructuredData();
public void setUseStructuredData(boolean useStructuredData);
public int getMaxMessageLength();
public void setMaxMessageLength(int maxMessageLength);
public void addMessageModifier(SyslogMessageModifierIF messageModifier);
public void insertMessageModifier(int index, SyslogMessageModifierIF messageModifier);
public void removeMessageModifier(SyslogMessageModifierIF messageModifier);
public void removeAllMessageModifiers();
public void setPort(int port) throws SyslogRuntimeException;
public void addBackLogHandler(SyslogBackLogHandlerIF backLogHandler);
public void insertBackLogHandler(int index, SyslogBackLogHandlerIF backLogHandler);
public void removeBackLogHandler(SyslogBackLogHandlerIF backLogHandler);
public void removeAllBackLogHandlers();
public String getLocalName();
public void setLocalName(String localName) throws SyslogRuntimeException;
public String getHost();
public void setHost(String host) throws SyslogRuntimeException;
public String getIdent();
public void setIdent(String ident);
public String getCharSet();
public void setCharSet(String charSet);
public boolean isIncludeIdentInMessageModifier();
public void setIncludeIdentInMessageModifier(boolean throwExceptionOnInitialize);
public boolean isThrowExceptionOnInitialize();
public void setThrowExceptionOnInitialize(boolean throwExceptionOnInitialize);
public boolean isThrowExceptionOnWrite();
public void setThrowExceptionOnWrite(boolean throwExceptionOnWrite);
public boolean isSendLocalTimestamp();
public void setSendLocalTimestamp(boolean sendLocalTimestamp);
public boolean isSendLocalName();
public void setSendLocalName(boolean sendLocalName);
public boolean isTruncateMessage();
public void setTruncateMessage(boolean truncateMessage);
public boolean isUseStructuredData();
public void setUseStructuredData(boolean useStructuredData);
public int getMaxMessageLength();
public void setMaxMessageLength(int maxMessageLength);
public void addMessageModifier(SyslogMessageModifierIF messageModifier);
public void insertMessageModifier(int index, SyslogMessageModifierIF messageModifier);
public void removeMessageModifier(SyslogMessageModifierIF messageModifier);
public void removeAllMessageModifiers();
public void addBackLogHandler(SyslogBackLogHandlerIF backLogHandler);
public void insertBackLogHandler(int index, SyslogBackLogHandlerIF backLogHandler);
public void removeBackLogHandler(SyslogBackLogHandlerIF backLogHandler);
public void removeAllBackLogHandlers();
}

View File

@ -3,162 +3,162 @@ package org.graylog2.syslog4j;
import java.io.Serializable;
/**
* SyslogConstants provides several global constant values for several
* classes within Syslog4j.
*
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: SyslogConstants.java,v 1.33 2011/01/11 05:11:13 cvs Exp $
*/
* SyslogConstants provides several global constant values for several
* classes within Syslog4j.
* <p/>
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: SyslogConstants.java,v 1.33 2011/01/11 05:11:13 cvs Exp $
*/
public interface SyslogConstants extends Serializable {
public static final String SYSLOG_PATH_DEFAULT = "/dev/log";
public static final String SYSLOG_HOST_DEFAULT = "localhost";
public static final int SYSLOG_PORT_DEFAULT = 514;
public static final int SYSLOG_BUFFER_SIZE = 1024;
public static final int SERVER_SOCKET_BACKLOG_DEFAULT = 50;
public static final String SYSLOG_DATEFORMAT = "MMM dd HH:mm:ss ";
public static final String STRUCTURED_DATA_NILVALUE = "-";
public static final String STRUCTURED_DATA_EMPTY_VALUE = "[0@0]";
public static final String SYSLOG_PATH_DEFAULT = "/dev/log";
public static final String SYSLOG_HOST_DEFAULT = "localhost";
public static final int SYSLOG_PORT_DEFAULT = 514;
public static final int SYSLOG_BUFFER_SIZE = 1024;
public static final int SERVER_SOCKET_BACKLOG_DEFAULT = 50;
public static final String CHAR_SET_DEFAULT = "UTF-8";
public static final String SYSLOG_DATEFORMAT = "MMM dd HH:mm:ss ";
public static final byte[] LF = "\n".getBytes();
public static final byte[] CRLF = "\r\n".getBytes();
public static final byte[] TCP_DELIMITER_SEQUENCE_DEFAULT = LF;
public static final boolean THREADED_DEFAULT = true;
public static final long THREAD_LOOP_INTERVAL_DEFAULT = 500;
public static final String STRUCTURED_DATA_NILVALUE = "-";
public static final String STRUCTURED_DATA_EMPTY_VALUE = "[0@0]";
public static final boolean SEND_LOCAL_NAME_DEFAULT = true;
public static final boolean SEND_LOCAL_TIMESTAMP_DEFAULT = true;
public static final boolean CACHE_HOST_ADDRESS_DEFAULT = true;
public static final int MAX_MESSAGE_LENGTH_DEFAULT = 1024;
public static final boolean INCLUDE_IDENT_IN_MESSAGE_MODIFIER_DEFAULT = false;
public static final boolean THROW_EXCEPTION_ON_INITIALIZE_DEFAULT = true;
public static final boolean THROW_EXCEPTION_ON_WRITE_DEFAULT = false;
public static final boolean USE_STRUCTURED_DATA_DEFAULT = false;
public static final String STRUCTURED_DATA_APP_NAME_DEFAULT_VALUE = "unknown";
public static final String STRUCTURED_DATA_PROCESS_ID_DEFAULT_VALUE = STRUCTURED_DATA_NILVALUE;
public static final boolean USE_DAEMON_THREAD_DEFAULT = true;
public static final int THREAD_PRIORITY_DEFAULT = -1;
public static final boolean TRUNCATE_MESSAGE_DEFAULT = false;
public static final String SPLIT_MESSAGE_BEGIN_TEXT_DEFAULT = "...";
public static final String SPLIT_MESSAGE_END_TEXT_DEFAULT = "...";
public static final String CHAR_SET_DEFAULT = "UTF-8";
public static final String SEND_LOCAL_NAME_DEFAULT_VALUE = "unknown";
public static final byte[] LF = "\n".getBytes();
public static final byte[] CRLF = "\r\n".getBytes();
public static final String TCP = "tcp";
public static final String UDP = "udp";
public static final String UNIX_SYSLOG = "unix_syslog";
public static final String UNIX_SOCKET = "unix_socket";
public static final boolean TCP_PERSISTENT_CONNECTION_DEFAULT = true;
public static final boolean TCP_SO_LINGER_DEFAULT = true;
public static final int TCP_SO_LINGER_SECONDS_DEFAULT = 1;
public static final boolean TCP_KEEP_ALIVE_DEFAULT = true;
public static final boolean TCP_REUSE_ADDRESS_DEFAULT = true;
public static final boolean TCP_SET_BUFFER_SIZE_DEFAULT = true;
public static final int TCP_FRESH_CONNECTION_INTERVAL_DEFAULT = -1;
public static final int TCP_MAX_ACTIVE_SOCKETS_DEFAULT = 0;
public static final byte TCP_MAX_ACTIVE_SOCKETS_BEHAVIOR_DEFAULT = 0;
public static final byte[] TCP_DELIMITER_SEQUENCE_DEFAULT = LF;
public static final int FACILITY_KERN = 0;
public static final int FACILITY_USER = 1<<3;
public static final int FACILITY_MAIL = 2<<3;
public static final int FACILITY_DAEMON = 3<<3;
public static final int FACILITY_AUTH = 4<<3;
public static final int FACILITY_SYSLOG = 5<<3;
public static final boolean THREADED_DEFAULT = true;
public static final long THREAD_LOOP_INTERVAL_DEFAULT = 500;
public static final int FACILITY_LPR = 6<<3;
public static final int FACILITY_NEWS = 7<<3;
public static final int FACILITY_UUCP = 8<<3;
public static final int FACILITY_CRON = 9<<3;
public static final int FACILITY_AUTHPRIV = 10<<3;
public static final int FACILITY_FTP = 11<<3;
public static final boolean SEND_LOCAL_NAME_DEFAULT = true;
public static final boolean SEND_LOCAL_TIMESTAMP_DEFAULT = true;
public static final boolean CACHE_HOST_ADDRESS_DEFAULT = true;
public static final int FACILITY_LOCAL0 = 16<<3;
public static final int FACILITY_LOCAL1 = 17<<3;
public static final int FACILITY_LOCAL2 = 18<<3;
public static final int FACILITY_LOCAL3 = 19<<3;
public static final int FACILITY_LOCAL4 = 20<<3;
public static final int FACILITY_LOCAL5 = 21<<3;
public static final int FACILITY_LOCAL6 = 22<<3;
public static final int FACILITY_LOCAL7 = 23<<3;
public static final int MAX_MESSAGE_LENGTH_DEFAULT = 1024;
public static final int SYSLOG_FACILITY_DEFAULT = FACILITY_USER;
public static final boolean INCLUDE_IDENT_IN_MESSAGE_MODIFIER_DEFAULT = false;
public static final boolean THROW_EXCEPTION_ON_INITIALIZE_DEFAULT = true;
public static final boolean THROW_EXCEPTION_ON_WRITE_DEFAULT = false;
public static final boolean USE_STRUCTURED_DATA_DEFAULT = false;
public static final String STRUCTURED_DATA_APP_NAME_DEFAULT_VALUE = "unknown";
public static final String STRUCTURED_DATA_PROCESS_ID_DEFAULT_VALUE = STRUCTURED_DATA_NILVALUE;
public static final int LEVEL_DEBUG = 7;
public static final int LEVEL_INFO = 6;
public static final int LEVEL_NOTICE = 5;
public static final int LEVEL_WARN = 4;
public static final int LEVEL_ERROR = 3;
public static final int LEVEL_CRITICAL = 2;
public static final int LEVEL_ALERT = 1;
public static final int LEVEL_EMERGENCY = 0;
public static final int OPTION_NONE = 0;
public static final int OPTION_LOG_CONS = 1;
public static final int OPTION_LOG_NDELAY = 2;
public static final int OPTION_LOG_NOWAIT = 4;
public static final int OPTION_LOG_ODELAY = 8;
public static final int OPTION_LOG_PERROR = 16;
public static final int OPTION_LOG_PID = 32;
public static final boolean USE_DAEMON_THREAD_DEFAULT = true;
public static final int THREAD_PRIORITY_DEFAULT = -1;
public static final int SOCK_STREAM = 1;
public static final int SOCK_DGRAM = 2;
public static final boolean TRUNCATE_MESSAGE_DEFAULT = false;
public static final short AF_UNIX = 1;
public static final int WRITE_RETRIES_DEFAULT = 2;
public static final int MAX_SHUTDOWN_WAIT_DEFAULT = 30000;
public static final long SHUTDOWN_INTERVAL = 100;
public static final int MAX_QUEUE_SIZE_DEFAULT = -1;
public static final long SERVER_SHUTDOWN_WAIT_DEFAULT = 500;
public static final String SYSLOG_LIBRARY_DEFAULT = "c";
public static final int SYSLOG_SOCKET_TYPE_DEFAULT = SOCK_DGRAM;
public static final short SYSLOG_SOCKET_FAMILY_DEFAULT = AF_UNIX;
public static final String SYSLOG_SOCKET_LIBRARY_DEFAULT = "c";
public static final int SYSLOG_SOCKET_PROTOCOL_DEFAULT = 0;
public static final String SYSLOG_SOCKET_PATH_DEFAULT = "/dev/log";
public static final String JNA_NATIVE_CLASS = "com.sun.jna.Native";
public static final String IDENT_SUFFIX_DEFAULT = ": ";
public static final String SYSLOG_MESSAGE_MODIFIER_PREFIX_DEFAULT = " {";
public static final String SYSLOG_MESSAGE_MODIFIER_SUFFIX_DEFAULT = "}";
public static final String SPLIT_MESSAGE_BEGIN_TEXT_DEFAULT = "...";
public static final String SPLIT_MESSAGE_END_TEXT_DEFAULT = "...";
public static final String SYSLOG_SEQUENTIAL_MESSAGE_MODIFIER_PREFIX_DEFAULT = " #";
public static final String SYSLOG_SEQUENTIAL_MESSAGE_MODIFIER_SUFFIX_DEFAULT = "";
public static final long SYSLOG_SEQUENTIAL_MESSAGE_MODIFIER_FIRST_NUMBER_DEFAULT = 0;
public static final long SYSLOG_SEQUENTIAL_MESSAGE_MODIFIER_LAST_NUMBER_DEFAULT = 9999;
public static final char SYSLOG_SEQUENTIAL_MESSAGE_MODIFIER_PAD_CHAR_DEFAULT = '0';
public static final boolean SYSLOG_SEQUENTIAL_MESSAGE_MODIFIER_USE_PADDING_DEFAULT = true;
public static final int SYSLOG_POOL_CONFIG_MAX_ACTIVE_DEFAULT = 4;
public static final int SYSLOG_POOL_CONFIG_MAX_IDLE_DEFAULT = 4;
public static final int SYSLOG_POOL_CONFIG_MAX_WAIT_DEFAULT = 1000;
public static final int SYSLOG_POOL_CONFIG_NUM_TESTS_PER_EVICTION_RUN_DEFAULT = 0;
public static final int SYSLOG_POOL_CONFIG_MIN_IDLE_DEFAULT = 4;
public static final int SYSLOG_POOL_CONFIG_MIN_EVICTABLE_IDLE_TIME_MILLIS_DEFAULT = 0;
public static final int SYSLOG_POOL_CONFIG_SOFT_MIN_EVICTABLE_IDLE_TIME_MILLIS_DEFAULT = 0;
public static final int SYSLOG_POOL_CONFIG_TIME_BETWEEN_EVICTION_RUNS_MILLIS_DEFAULT = 0;
public static final boolean SYSLOG_POOL_CONFIG_TEST_ON_BORROW_DEFAULT = false;
public static final boolean SYSLOG_POOL_CONFIG_TEST_ON_RETURN_DEFAULT = false;
public static final boolean SYSLOG_POOL_CONFIG_TEST_WHILE_IDLE_DEFAULT = false;
public static final String SEND_LOCAL_NAME_DEFAULT_VALUE = "unknown";
public static final String TCP = "tcp";
public static final String UDP = "udp";
public static final String UNIX_SYSLOG = "unix_syslog";
public static final String UNIX_SOCKET = "unix_socket";
public static final boolean TCP_PERSISTENT_CONNECTION_DEFAULT = true;
public static final boolean TCP_SO_LINGER_DEFAULT = true;
public static final int TCP_SO_LINGER_SECONDS_DEFAULT = 1;
public static final boolean TCP_KEEP_ALIVE_DEFAULT = true;
public static final boolean TCP_REUSE_ADDRESS_DEFAULT = true;
public static final boolean TCP_SET_BUFFER_SIZE_DEFAULT = true;
public static final int TCP_FRESH_CONNECTION_INTERVAL_DEFAULT = -1;
public static final int TCP_MAX_ACTIVE_SOCKETS_DEFAULT = 0;
public static final byte TCP_MAX_ACTIVE_SOCKETS_BEHAVIOR_DEFAULT = 0;
public static final int FACILITY_KERN = 0;
public static final int FACILITY_USER = 1 << 3;
public static final int FACILITY_MAIL = 2 << 3;
public static final int FACILITY_DAEMON = 3 << 3;
public static final int FACILITY_AUTH = 4 << 3;
public static final int FACILITY_SYSLOG = 5 << 3;
public static final int FACILITY_LPR = 6 << 3;
public static final int FACILITY_NEWS = 7 << 3;
public static final int FACILITY_UUCP = 8 << 3;
public static final int FACILITY_CRON = 9 << 3;
public static final int FACILITY_AUTHPRIV = 10 << 3;
public static final int FACILITY_FTP = 11 << 3;
public static final int FACILITY_LOCAL0 = 16 << 3;
public static final int FACILITY_LOCAL1 = 17 << 3;
public static final int FACILITY_LOCAL2 = 18 << 3;
public static final int FACILITY_LOCAL3 = 19 << 3;
public static final int FACILITY_LOCAL4 = 20 << 3;
public static final int FACILITY_LOCAL5 = 21 << 3;
public static final int FACILITY_LOCAL6 = 22 << 3;
public static final int FACILITY_LOCAL7 = 23 << 3;
public static final int SYSLOG_FACILITY_DEFAULT = FACILITY_USER;
public static final int LEVEL_DEBUG = 7;
public static final int LEVEL_INFO = 6;
public static final int LEVEL_NOTICE = 5;
public static final int LEVEL_WARN = 4;
public static final int LEVEL_ERROR = 3;
public static final int LEVEL_CRITICAL = 2;
public static final int LEVEL_ALERT = 1;
public static final int LEVEL_EMERGENCY = 0;
public static final int OPTION_NONE = 0;
public static final int OPTION_LOG_CONS = 1;
public static final int OPTION_LOG_NDELAY = 2;
public static final int OPTION_LOG_NOWAIT = 4;
public static final int OPTION_LOG_ODELAY = 8;
public static final int OPTION_LOG_PERROR = 16;
public static final int OPTION_LOG_PID = 32;
public static final int SOCK_STREAM = 1;
public static final int SOCK_DGRAM = 2;
public static final short AF_UNIX = 1;
public static final int WRITE_RETRIES_DEFAULT = 2;
public static final int MAX_SHUTDOWN_WAIT_DEFAULT = 30000;
public static final long SHUTDOWN_INTERVAL = 100;
public static final int MAX_QUEUE_SIZE_DEFAULT = -1;
public static final long SERVER_SHUTDOWN_WAIT_DEFAULT = 500;
public static final String SYSLOG_LIBRARY_DEFAULT = "c";
public static final int SYSLOG_SOCKET_TYPE_DEFAULT = SOCK_DGRAM;
public static final short SYSLOG_SOCKET_FAMILY_DEFAULT = AF_UNIX;
public static final String SYSLOG_SOCKET_LIBRARY_DEFAULT = "c";
public static final int SYSLOG_SOCKET_PROTOCOL_DEFAULT = 0;
public static final String SYSLOG_SOCKET_PATH_DEFAULT = "/dev/log";
public static final String JNA_NATIVE_CLASS = "com.sun.jna.Native";
public static final String IDENT_SUFFIX_DEFAULT = ": ";
public static final String SYSLOG_MESSAGE_MODIFIER_PREFIX_DEFAULT = " {";
public static final String SYSLOG_MESSAGE_MODIFIER_SUFFIX_DEFAULT = "}";
public static final String SYSLOG_SEQUENTIAL_MESSAGE_MODIFIER_PREFIX_DEFAULT = " #";
public static final String SYSLOG_SEQUENTIAL_MESSAGE_MODIFIER_SUFFIX_DEFAULT = "";
public static final long SYSLOG_SEQUENTIAL_MESSAGE_MODIFIER_FIRST_NUMBER_DEFAULT = 0;
public static final long SYSLOG_SEQUENTIAL_MESSAGE_MODIFIER_LAST_NUMBER_DEFAULT = 9999;
public static final char SYSLOG_SEQUENTIAL_MESSAGE_MODIFIER_PAD_CHAR_DEFAULT = '0';
public static final boolean SYSLOG_SEQUENTIAL_MESSAGE_MODIFIER_USE_PADDING_DEFAULT = true;
public static final int SYSLOG_POOL_CONFIG_MAX_ACTIVE_DEFAULT = 4;
public static final int SYSLOG_POOL_CONFIG_MAX_IDLE_DEFAULT = 4;
public static final int SYSLOG_POOL_CONFIG_MAX_WAIT_DEFAULT = 1000;
public static final int SYSLOG_POOL_CONFIG_NUM_TESTS_PER_EVICTION_RUN_DEFAULT = 0;
public static final int SYSLOG_POOL_CONFIG_MIN_IDLE_DEFAULT = 4;
public static final int SYSLOG_POOL_CONFIG_MIN_EVICTABLE_IDLE_TIME_MILLIS_DEFAULT = 0;
public static final int SYSLOG_POOL_CONFIG_SOFT_MIN_EVICTABLE_IDLE_TIME_MILLIS_DEFAULT = 0;
public static final int SYSLOG_POOL_CONFIG_TIME_BETWEEN_EVICTION_RUNS_MILLIS_DEFAULT = 0;
public static final boolean SYSLOG_POOL_CONFIG_TEST_ON_BORROW_DEFAULT = false;
public static final boolean SYSLOG_POOL_CONFIG_TEST_ON_RETURN_DEFAULT = false;
public static final boolean SYSLOG_POOL_CONFIG_TEST_WHILE_IDLE_DEFAULT = false;
}

View File

@ -1,52 +1,71 @@
package org.graylog2.syslog4j;
/**
* SyslogIF provides a common interface for all Syslog4j client implementations.
*
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: SyslogIF.java,v 1.9 2010/02/11 04:59:22 cvs Exp $
*/
* SyslogIF provides a common interface for all Syslog4j client implementations.
* <p/>
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: SyslogIF.java,v 1.9 2010/02/11 04:59:22 cvs Exp $
*/
public interface SyslogIF extends SyslogConstants {
public void initialize(String protocol, SyslogConfigIF config) throws SyslogRuntimeException;
public String getProtocol();
public SyslogConfigIF getConfig();
public void backLog(int level, String message, Throwable reasonThrowable);
public void backLog(int level, String message, String reason);
public void log(int level, String message);
public void debug(String message);
public void info(String message);
public void notice(String message);
public void warn(String message);
public void error(String message);
public void critical(String message);
public void alert(String message);
public void emergency(String message);
public void initialize(String protocol, SyslogConfigIF config) throws SyslogRuntimeException;
public void log(int level, SyslogMessageIF message);
public void debug(SyslogMessageIF message);
public void info(SyslogMessageIF message);
public void notice(SyslogMessageIF message);
public void warn(SyslogMessageIF message);
public void error(SyslogMessageIF message);
public void critical(SyslogMessageIF message);
public void alert(SyslogMessageIF message);
public void emergency(SyslogMessageIF message);
public String getProtocol();
public void flush() throws SyslogRuntimeException;
public void shutdown() throws SyslogRuntimeException;
public void setMessageProcessor(SyslogMessageProcessorIF messageProcessor);
public SyslogMessageProcessorIF getMessageProcessor();
public SyslogConfigIF getConfig();
public void setStructuredMessageProcessor(SyslogMessageProcessorIF messageProcessor);
public SyslogMessageProcessorIF getStructuredMessageProcessor();
public void backLog(int level, String message, Throwable reasonThrowable);
public void backLog(int level, String message, String reason);
public void log(int level, String message);
public void debug(String message);
public void info(String message);
public void notice(String message);
public void warn(String message);
public void error(String message);
public void critical(String message);
public void alert(String message);
public void emergency(String message);
public void log(int level, SyslogMessageIF message);
public void debug(SyslogMessageIF message);
public void info(SyslogMessageIF message);
public void notice(SyslogMessageIF message);
public void warn(SyslogMessageIF message);
public void error(SyslogMessageIF message);
public void critical(SyslogMessageIF message);
public void alert(SyslogMessageIF message);
public void emergency(SyslogMessageIF message);
public void flush() throws SyslogRuntimeException;
public void shutdown() throws SyslogRuntimeException;
public void setMessageProcessor(SyslogMessageProcessorIF messageProcessor);
public SyslogMessageProcessorIF getMessageProcessor();
public void setStructuredMessageProcessor(SyslogMessageProcessorIF messageProcessor);
public SyslogMessageProcessorIF getStructuredMessageProcessor();
}

View File

@ -10,189 +10,235 @@ import java.io.InputStreamReader;
/**
* This class provides a command-line interface for Syslog4j
* server implementations.
*
* <p/>
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: SyslogMain.java,v 1.4 2010/11/28 01:38:08 cvs Exp $
*/
public class SyslogMain {
public static boolean CALL_SYSTEM_EXIT_ON_FAILURE = true;
public static class Options {
public String host = null;
public String port = null;
public String level = "INFO";
public String facility = "USER";
public String protocol = null;
public String message = null;
public String fileName = null;
public boolean quiet = false;
public static boolean CALL_SYSTEM_EXIT_ON_FAILURE = true;
public String usage = null;
}
public static void usage(String problem) {
if (problem != null) {
System.out.println("Error: " + problem);
System.out.println();
}
System.out.println("Usage:");
System.out.println();
System.out.println("Syslog [-h <host>] [-p <port>] [-l <level>] [-f <facility>]");
System.out.println(" <protocol>");
System.out.println();
System.out.println("Syslog [-h <host>] [-p <port>] [-l <level>] [-f <facility>]");
System.out.println(" <protocol> [message...]");
System.out.println();
System.out.println("Syslog [-h <host>] [-p <port>] [-l <level>] [-f <facility>]");
System.out.println(" -i <file> <protocol>");
System.out.println();
System.out.println("-h <host> host or IP to send message (default: localhost)");
System.out.println("-p <port> port to send message (default: 514)");
System.out.println("-l <level> syslog level to use (default: INFO)");
System.out.println("-f <facility> syslog facility to use (default: USER)");
System.out.println("-i <file> input taken from the specified file");
System.out.println();
System.out.println("-q do not write anything to standard out");
System.out.println();
System.out.println("protocol Syslog4j protocol implementation");
System.out.println("message syslog message text");
System.out.println();
System.out.println("Notes:");
System.out.println();
System.out.println("Additional message arguments will be concatenated into the same");
System.out.println("syslog message; calling SyslogMain will only send one message per call.");
System.out.println();
System.out.println("If the message argument is ommited, lines will be taken from the");
System.out.println("standard input.");
}
public static Options parseOptions(String[] args) {
Options options = new Options();
int i = 0;
while(i < args.length) {
String arg = args[i++];
boolean match = false;
if ("-h".equals(arg)) { if (i == args.length) { options.usage = "Must specify host with -h"; return options; } match = true; options.host = args[i++]; }
if ("-p".equals(arg)) { if (i == args.length) { options.usage = "Must specify port with -p"; return options; } match = true; options.port = args[i++]; }
if ("-l".equals(arg)) { if (i == args.length) { options.usage = "Must specify level with -l"; return options; } match = true; options.level = args[i++]; }
if ("-f".equals(arg)) { if (i == args.length) { options.usage = "Must specify facility with -f"; return options; } match = true; options.facility = args[i++]; }
if ("-i".equals(arg)) { if (i == args.length) { options.usage = "Must specify file with -i"; return options; } match = true; options.fileName = args[i++]; }
if ("-q".equals(arg)) { match = true; options.quiet = true; }
if (options.protocol == null && !match) {
match = true;
options.protocol = arg;
}
public static class Options {
public String host = null;
public String port = null;
public String level = "INFO";
public String facility = "USER";
public String protocol = null;
public String message = null;
public String fileName = null;
if (!match) {
if (options.message == null) {
options.message = arg;
} else {
options.message += " " + arg;
}
}
}
if (options.protocol == null) {
options.usage = "Must specify protocol";
return options;
}
if (options.message != null && options.fileName != null) {
options.usage = "Must specify either -i <file> or <message>, not both";
return options;
}
public boolean quiet = false;
return options;
}
public static void main(String[] args) throws Exception {
main(args,true);
}
public static void main(String[] args, boolean shutdown) throws Exception {
Options options = parseOptions(args);
public String usage = null;
}
if (options.usage != null) {
usage(options.usage);
if (CALL_SYSTEM_EXIT_ON_FAILURE) { System.exit(1); } else { return; }
}
if (!options.quiet) {
System.out.println("Syslog " + Syslog.getVersion());
}
if (!Syslog.exists(options.protocol)) {
usage("Protocol \"" + options.protocol + "\" not supported");
if (CALL_SYSTEM_EXIT_ON_FAILURE) { System.exit(1); } else { return; }
}
SyslogIF syslog = Syslog.getInstance(options.protocol);
SyslogConfigIF syslogConfig = syslog.getConfig();
if (options.host != null) {
syslogConfig.setHost(options.host);
if (!options.quiet) {
System.out.println("Sending to host: " + options.host);
}
}
public static void usage(String problem) {
if (problem != null) {
System.out.println("Error: " + problem);
System.out.println();
}
if (options.port != null) {
syslogConfig.setPort(Integer.parseInt(options.port));
if (!options.quiet) {
System.out.println("Sending to port: " + options.port);
}
}
int level = SyslogUtility.getLevel(options.level);
syslogConfig.setFacility(options.facility);
if (options.message != null) {
if (!options.quiet) {
System.out.println("Sending " + options.facility + "." + options.level + " message \"" + options.message + "\"");
}
syslog.log(level,options.message);
} else {
InputStream is = null;
if (options.fileName != null) {
is = new FileInputStream(options.fileName);
} else {
is = System.in;
}
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line = br.readLine();
while(line != null && line.length() > 0) {
if (!options.quiet) {
System.out.println("Sending " + options.facility + "." + options.level + " message \"" + line + "\"");
}
syslog.log(level,line);
line = br.readLine();
}
}
System.out.println("Usage:");
System.out.println();
System.out.println("Syslog [-h <host>] [-p <port>] [-l <level>] [-f <facility>]");
System.out.println(" <protocol>");
System.out.println();
System.out.println("Syslog [-h <host>] [-p <port>] [-l <level>] [-f <facility>]");
System.out.println(" <protocol> [message...]");
System.out.println();
System.out.println("Syslog [-h <host>] [-p <port>] [-l <level>] [-f <facility>]");
System.out.println(" -i <file> <protocol>");
System.out.println();
System.out.println("-h <host> host or IP to send message (default: localhost)");
System.out.println("-p <port> port to send message (default: 514)");
System.out.println("-l <level> syslog level to use (default: INFO)");
System.out.println("-f <facility> syslog facility to use (default: USER)");
System.out.println("-i <file> input taken from the specified file");
System.out.println();
System.out.println("-q do not write anything to standard out");
System.out.println();
System.out.println("protocol Syslog4j protocol implementation");
System.out.println("message syslog message text");
System.out.println();
System.out.println("Notes:");
System.out.println();
System.out.println("Additional message arguments will be concatenated into the same");
System.out.println("syslog message; calling SyslogMain will only send one message per call.");
System.out.println();
System.out.println("If the message argument is ommited, lines will be taken from the");
System.out.println("standard input.");
}
if (shutdown) {
Syslog.shutdown();
}
}
public static Options parseOptions(String[] args) {
Options options = new Options();
int i = 0;
while (i < args.length) {
String arg = args[i++];
boolean match = false;
if ("-h".equals(arg)) {
if (i == args.length) {
options.usage = "Must specify host with -h";
return options;
}
match = true;
options.host = args[i++];
}
if ("-p".equals(arg)) {
if (i == args.length) {
options.usage = "Must specify port with -p";
return options;
}
match = true;
options.port = args[i++];
}
if ("-l".equals(arg)) {
if (i == args.length) {
options.usage = "Must specify level with -l";
return options;
}
match = true;
options.level = args[i++];
}
if ("-f".equals(arg)) {
if (i == args.length) {
options.usage = "Must specify facility with -f";
return options;
}
match = true;
options.facility = args[i++];
}
if ("-i".equals(arg)) {
if (i == args.length) {
options.usage = "Must specify file with -i";
return options;
}
match = true;
options.fileName = args[i++];
}
if ("-q".equals(arg)) {
match = true;
options.quiet = true;
}
if (options.protocol == null && !match) {
match = true;
options.protocol = arg;
}
if (!match) {
if (options.message == null) {
options.message = arg;
} else {
options.message += " " + arg;
}
}
}
if (options.protocol == null) {
options.usage = "Must specify protocol";
return options;
}
if (options.message != null && options.fileName != null) {
options.usage = "Must specify either -i <file> or <message>, not both";
return options;
}
return options;
}
public static void main(String[] args) throws Exception {
main(args, true);
}
public static void main(String[] args, boolean shutdown) throws Exception {
Options options = parseOptions(args);
if (options.usage != null) {
usage(options.usage);
if (CALL_SYSTEM_EXIT_ON_FAILURE) {
System.exit(1);
} else {
return;
}
}
if (!options.quiet) {
System.out.println("Syslog " + Syslog.getVersion());
}
if (!Syslog.exists(options.protocol)) {
usage("Protocol \"" + options.protocol + "\" not supported");
if (CALL_SYSTEM_EXIT_ON_FAILURE) {
System.exit(1);
} else {
return;
}
}
SyslogIF syslog = Syslog.getInstance(options.protocol);
SyslogConfigIF syslogConfig = syslog.getConfig();
if (options.host != null) {
syslogConfig.setHost(options.host);
if (!options.quiet) {
System.out.println("Sending to host: " + options.host);
}
}
if (options.port != null) {
syslogConfig.setPort(Integer.parseInt(options.port));
if (!options.quiet) {
System.out.println("Sending to port: " + options.port);
}
}
int level = SyslogUtility.getLevel(options.level);
syslogConfig.setFacility(options.facility);
if (options.message != null) {
if (!options.quiet) {
System.out.println("Sending " + options.facility + "." + options.level + " message \"" + options.message + "\"");
}
syslog.log(level, options.message);
} else {
InputStream is = null;
if (options.fileName != null) {
is = new FileInputStream(options.fileName);
} else {
is = System.in;
}
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line = br.readLine();
while (line != null && line.length() > 0) {
if (!options.quiet) {
System.out.println("Sending " + options.facility + "." + options.level + " message \"" + line + "\"");
}
syslog.log(level, line);
line = br.readLine();
}
}
if (shutdown) {
Syslog.shutdown();
}
}
}

View File

@ -3,15 +3,15 @@ package org.graylog2.syslog4j;
import java.io.Serializable;
/**
* SyslogMessageIF provides a common interface for all Syslog4j event implementations.
*
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: SyslogMessageIF.java,v 1.1 2008/11/10 04:38:37 cvs Exp $
*/
* SyslogMessageIF provides a common interface for all Syslog4j event implementations.
* <p/>
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: SyslogMessageIF.java,v 1.1 2008/11/10 04:38:37 cvs Exp $
*/
public interface SyslogMessageIF extends Serializable {
public String createMessage();
public String createMessage();
}

View File

@ -1,20 +1,22 @@
package org.graylog2.syslog4j;
/**
* SyslogMessageModifierConfigIF provides a common configuration interface for all
* Syslog4j message modifier implementations.
*
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: SyslogMessageModifierConfigIF.java,v 1.3 2010/10/28 05:10:57 cvs Exp $
*/
* SyslogMessageModifierConfigIF provides a common configuration interface for all
* Syslog4j message modifier implementations.
* <p/>
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: SyslogMessageModifierConfigIF.java,v 1.3 2010/10/28 05:10:57 cvs Exp $
*/
public interface SyslogMessageModifierConfigIF extends SyslogConstants, SyslogCharSetIF {
public String getPrefix();
public void setPrefix(String prefix);
public String getPrefix();
public String getSuffix();
public void setSuffix(String suffix);
public void setPrefix(String prefix);
public String getSuffix();
public void setSuffix(String suffix);
}

View File

@ -1,17 +1,18 @@
package org.graylog2.syslog4j;
/**
* SyslogMessageModifierIF provides a common interface for all
* Syslog4j message modifier implementations.
*
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: SyslogMessageModifierIF.java,v 1.4 2010/10/28 05:10:57 cvs Exp $
*/
* SyslogMessageModifierIF provides a common interface for all
* Syslog4j message modifier implementations.
* <p/>
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: SyslogMessageModifierIF.java,v 1.4 2010/10/28 05:10:57 cvs Exp $
*/
public interface SyslogMessageModifierIF extends SyslogConstants {
public String modify(SyslogIF syslog, int facility, int level, String message);
public boolean verify(String message);
public String modify(SyslogIF syslog, int facility, int level, String message);
public boolean verify(String message);
}

View File

@ -3,20 +3,20 @@ package org.graylog2.syslog4j;
import java.io.Serializable;
/**
* SyslogMessageProcessorIF provides an extensible interface for writing custom
* Syslog4j message processors.
*
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: SyslogMessageProcessorIF.java,v 1.4 2010/11/28 04:15:18 cvs Exp $
*/
* SyslogMessageProcessorIF provides an extensible interface for writing custom
* Syslog4j message processors.
* <p/>
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: SyslogMessageProcessorIF.java,v 1.4 2010/11/28 04:15:18 cvs Exp $
*/
public interface SyslogMessageProcessorIF extends Serializable {
public String createSyslogHeader(int facility, int level, String localName, boolean sendLocalTimestamp, boolean sendLocalName);
public String createSyslogHeader(int facility, int level, String localName, boolean sendLocalTimestamp, boolean sendLocalName);
public byte[] createPacketData(byte[] header, byte[] message, int start, int length);
public byte[] createPacketData(byte[] header, byte[] message, int start, int length);
public byte[] createPacketData(byte[] header, byte[] message, int start, int length, byte[] splitBeginText, byte[] splitEndText);
public byte[] createPacketData(byte[] header, byte[] message, int start, int length, byte[] splitBeginText, byte[] splitEndText);
}

View File

@ -3,50 +3,62 @@ package org.graylog2.syslog4j;
import java.io.Serializable;
/**
* SyslogPoolConfigIF is an interface which provides configuration support
* for the Apache Commons Pool.
*
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: SyslogPoolConfigIF.java,v 1.2 2009/03/29 17:38:58 cvs Exp $
*/
* SyslogPoolConfigIF is an interface which provides configuration support
* for the Apache Commons Pool.
* <p/>
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: SyslogPoolConfigIF.java,v 1.2 2009/03/29 17:38:58 cvs Exp $
*/
public interface SyslogPoolConfigIF extends Serializable {
public int getMaxActive();
public void setMaxActive(int maxActive);
public int getMaxIdle();
public void setMaxIdle(int maxIdle);
public long getMaxWait();
public void setMaxWait(long maxWait);
public long getMinEvictableIdleTimeMillis();
public void setMinEvictableIdleTimeMillis(long minEvictableIdleTimeMillis);
public int getMinIdle();
public void setMinIdle(int minIdle);
public int getNumTestsPerEvictionRun();
public void setNumTestsPerEvictionRun(int numTestsPerEvictionRun);
public long getSoftMinEvictableIdleTimeMillis();
public void setSoftMinEvictableIdleTimeMillis(long softMinEvictableIdleTimeMillis);
public boolean isTestOnBorrow();
public void setTestOnBorrow(boolean testOnBorrow);
public boolean isTestOnReturn();
public void setTestOnReturn(boolean testOnReturn);
public boolean isTestWhileIdle();
public void setTestWhileIdle(boolean testWhileIdle);
public long getTimeBetweenEvictionRunsMillis();
public void setTimeBetweenEvictionRunsMillis(long timeBetweenEvictionRunsMillis);
public byte getWhenExhaustedAction();
public void setWhenExhaustedAction(byte whenExhaustedAction);
public int getMaxActive();
public void setMaxActive(int maxActive);
public int getMaxIdle();
public void setMaxIdle(int maxIdle);
public long getMaxWait();
public void setMaxWait(long maxWait);
public long getMinEvictableIdleTimeMillis();
public void setMinEvictableIdleTimeMillis(long minEvictableIdleTimeMillis);
public int getMinIdle();
public void setMinIdle(int minIdle);
public int getNumTestsPerEvictionRun();
public void setNumTestsPerEvictionRun(int numTestsPerEvictionRun);
public long getSoftMinEvictableIdleTimeMillis();
public void setSoftMinEvictableIdleTimeMillis(long softMinEvictableIdleTimeMillis);
public boolean isTestOnBorrow();
public void setTestOnBorrow(boolean testOnBorrow);
public boolean isTestOnReturn();
public void setTestOnReturn(boolean testOnReturn);
public boolean isTestWhileIdle();
public void setTestWhileIdle(boolean testWhileIdle);
public long getTimeBetweenEvictionRunsMillis();
public void setTimeBetweenEvictionRunsMillis(long timeBetweenEvictionRunsMillis);
public byte getWhenExhaustedAction();
public void setWhenExhaustedAction(byte whenExhaustedAction);
}

View File

@ -1,24 +1,24 @@
package org.graylog2.syslog4j;
/**
* SyslogRuntimeException provides an extension of RuntimeException thrown
* by the majority of the classes within Syslog4j.
*
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: SyslogRuntimeException.java,v 1.3 2008/11/13 14:48:36 cvs Exp $
*/
* SyslogRuntimeException provides an extension of RuntimeException thrown
* by the majority of the classes within Syslog4j.
* <p/>
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: SyslogRuntimeException.java,v 1.3 2008/11/13 14:48:36 cvs Exp $
*/
public class SyslogRuntimeException extends RuntimeException {
private static final long serialVersionUID = 7278123987654320379L;
private static final long serialVersionUID = 7278123987654320379L;
public SyslogRuntimeException(String arg0) {
super(arg0);
}
public SyslogRuntimeException(String arg0) {
super(arg0);
}
public SyslogRuntimeException(Throwable arg0) {
super(arg0);
}
public SyslogRuntimeException(Throwable arg0) {
super(arg0);
}
}

View File

@ -17,378 +17,378 @@ import org.graylog2.syslog4j.impl.message.structured.StructuredSyslogMessageIF;
import org.graylog2.syslog4j.util.SyslogUtility;
/**
* AbstractSyslog provides a base abstract implementation of the SyslogIF.
*
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: AbstractSyslog.java,v 1.29 2011/01/11 04:58:52 cvs Exp $
*/
* AbstractSyslog provides a base abstract implementation of the SyslogIF.
* <p/>
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: AbstractSyslog.java,v 1.29 2011/01/11 04:58:52 cvs Exp $
*/
public abstract class AbstractSyslog implements SyslogIF {
private static final long serialVersionUID = 2632017043774808264L;
private static final long serialVersionUID = 2632017043774808264L;
protected String syslogProtocol = null;
protected AbstractSyslogConfigIF syslogConfig = null;
protected SyslogMessageProcessorIF syslogMessageProcessor = null;
protected SyslogMessageProcessorIF structuredSyslogMessageProcessor = null;
protected Object backLogStatusSyncObject = new Object();
protected boolean backLogStatus = false;
protected List notifiedBackLogHandlers = new ArrayList();
protected boolean getBackLogStatus() {
synchronized(this.backLogStatusSyncObject) {
return this.backLogStatus;
}
}
protected String syslogProtocol = null;
/**
* @param backLogStatus - true if in a "down" backLog state, false if in an "up" (operational) non-backLog state
*/
public void setBackLogStatus(boolean backLogStatus) {
if (this.backLogStatus != backLogStatus) {
synchronized(this.backLogStatusSyncObject) {
if (!backLogStatus) {
for(int i=0; i<this.notifiedBackLogHandlers.size(); i++) {
SyslogBackLogHandlerIF backLogHandler = (SyslogBackLogHandlerIF) this.notifiedBackLogHandlers.get(i);
backLogHandler.up(this);
}
this.notifiedBackLogHandlers.clear();
}
this.backLogStatus = backLogStatus;
}
}
}
protected AbstractSyslogConfigIF syslogConfig = null;
public void initialize(String protocol, SyslogConfigIF config) throws SyslogRuntimeException {
this.syslogProtocol = protocol;
protected SyslogMessageProcessorIF syslogMessageProcessor = null;
protected SyslogMessageProcessorIF structuredSyslogMessageProcessor = null;
try {
this.syslogConfig = (AbstractSyslogConfigIF) config;
} catch (ClassCastException cce) {
throw new SyslogRuntimeException("provided config must implement AbstractSyslogConfigIF");
}
initialize();
}
public SyslogMessageProcessorIF getMessageProcessor() {
if (this.syslogMessageProcessor == null) {
this.syslogMessageProcessor = SyslogMessageProcessor.getDefault();
}
return this.syslogMessageProcessor;
}
protected Object backLogStatusSyncObject = new Object();
public SyslogMessageProcessorIF getStructuredMessageProcessor() {
if (this.structuredSyslogMessageProcessor == null) {
this.structuredSyslogMessageProcessor = StructuredSyslogMessageProcessor.getDefault();
}
return this.structuredSyslogMessageProcessor;
}
protected boolean backLogStatus = false;
protected List notifiedBackLogHandlers = new ArrayList();
public void setMessageProcessor(SyslogMessageProcessorIF messageProcessor) {
this.syslogMessageProcessor = messageProcessor;
}
protected boolean getBackLogStatus() {
synchronized (this.backLogStatusSyncObject) {
return this.backLogStatus;
}
}
public void setStructuredMessageProcessor(SyslogMessageProcessorIF messageProcessor) {
this.structuredSyslogMessageProcessor = messageProcessor;
}
/**
* @param backLogStatus - true if in a "down" backLog state, false if in an "up" (operational) non-backLog state
*/
public void setBackLogStatus(boolean backLogStatus) {
if (this.backLogStatus != backLogStatus) {
synchronized (this.backLogStatusSyncObject) {
if (!backLogStatus) {
for (int i = 0; i < this.notifiedBackLogHandlers.size(); i++) {
SyslogBackLogHandlerIF backLogHandler = (SyslogBackLogHandlerIF) this.notifiedBackLogHandlers.get(i);
public String getProtocol() {
return this.syslogProtocol;
}
public SyslogConfigIF getConfig() {
return this.syslogConfig;
}
backLogHandler.up(this);
}
public void log(int level, String message) {
if (this.syslogConfig.isUseStructuredData()) {
StructuredSyslogMessageIF structuredMessage = new StructuredSyslogMessage(null,null,message);
log(getStructuredMessageProcessor(),level,structuredMessage.createMessage());
} else {
log(getMessageProcessor(),level,message);
}
}
this.notifiedBackLogHandlers.clear();
}
public void log(int level, SyslogMessageIF message) {
if (message instanceof StructuredSyslogMessageIF) {
if (getMessageProcessor() instanceof StructuredSyslogMessageProcessor) {
log(getMessageProcessor(),level,message.createMessage());
} else {
log(getStructuredMessageProcessor(),level,message.createMessage());
}
} else {
log(getMessageProcessor(),level,message.createMessage());
}
}
this.backLogStatus = backLogStatus;
}
}
}
public void debug(String message) {
log(LEVEL_DEBUG,message);
}
public void initialize(String protocol, SyslogConfigIF config) throws SyslogRuntimeException {
this.syslogProtocol = protocol;
public void notice(String message) {
log(LEVEL_NOTICE,message);
}
try {
this.syslogConfig = (AbstractSyslogConfigIF) config;
public void info(String message) {
log(LEVEL_INFO,message);
}
} catch (ClassCastException cce) {
throw new SyslogRuntimeException("provided config must implement AbstractSyslogConfigIF");
}
public void warn(String message) {
log(LEVEL_WARN,message);
}
public void error(String message) {
log(LEVEL_ERROR,message);
}
initialize();
}
public void critical(String message) {
log(LEVEL_CRITICAL,message);
}
public SyslogMessageProcessorIF getMessageProcessor() {
if (this.syslogMessageProcessor == null) {
this.syslogMessageProcessor = SyslogMessageProcessor.getDefault();
}
public void alert(String message) {
log(LEVEL_ALERT,message);
}
return this.syslogMessageProcessor;
}
public void emergency(String message) {
log(LEVEL_EMERGENCY,message);
}
public void debug(SyslogMessageIF message) {
log(LEVEL_DEBUG,message);
}
public SyslogMessageProcessorIF getStructuredMessageProcessor() {
if (this.structuredSyslogMessageProcessor == null) {
this.structuredSyslogMessageProcessor = StructuredSyslogMessageProcessor.getDefault();
}
public void notice(SyslogMessageIF message) {
log(LEVEL_NOTICE,message);
}
return this.structuredSyslogMessageProcessor;
}
public void info(SyslogMessageIF message) {
log(LEVEL_INFO,message);
}
public void setMessageProcessor(SyslogMessageProcessorIF messageProcessor) {
this.syslogMessageProcessor = messageProcessor;
}
public void warn(SyslogMessageIF message) {
log(LEVEL_WARN,message);
}
public void error(SyslogMessageIF message) {
log(LEVEL_ERROR,message);
}
public void setStructuredMessageProcessor(SyslogMessageProcessorIF messageProcessor) {
this.structuredSyslogMessageProcessor = messageProcessor;
}
public void critical(SyslogMessageIF message) {
log(LEVEL_CRITICAL,message);
}
public String getProtocol() {
return this.syslogProtocol;
}
public void alert(SyslogMessageIF message) {
log(LEVEL_ALERT,message);
}
public SyslogConfigIF getConfig() {
return this.syslogConfig;
}
public void emergency(SyslogMessageIF message) {
log(LEVEL_EMERGENCY,message);
}
protected String prefixMessage(String message, String suffix) {
String ident = this.syslogConfig.getIdent();
String _message = ((ident == null || "".equals(ident.trim())) ? "" : (ident + suffix)) + message;
return _message;
}
public void log(SyslogMessageProcessorIF messageProcessor, int level, String message) {
String _message = null;
if (this.syslogConfig.isIncludeIdentInMessageModifier()) {
_message = prefixMessage(message,IDENT_SUFFIX_DEFAULT);
_message = modifyMessage(level,_message);
} else {
_message = modifyMessage(level,message);
_message = prefixMessage(_message,IDENT_SUFFIX_DEFAULT);
}
try {
write(messageProcessor, level,_message);
} catch (SyslogRuntimeException sre) {
if (sre.getCause() != null) {
backLog(level,_message,sre.getCause());
} else {
backLog(level,_message,sre);
}
if (this.syslogConfig.isThrowExceptionOnWrite()) {
throw sre;
}
}
}
public void log(int level, String message) {
if (this.syslogConfig.isUseStructuredData()) {
StructuredSyslogMessageIF structuredMessage = new StructuredSyslogMessage(null, null, message);
protected void write(SyslogMessageProcessorIF messageProcessor, int level, String message) throws SyslogRuntimeException {
String header = messageProcessor.createSyslogHeader(this.syslogConfig.getFacility(),level,this.syslogConfig.getLocalName(),this.syslogConfig.isSendLocalTimestamp(),this.syslogConfig.isSendLocalName());
log(getStructuredMessageProcessor(), level, structuredMessage.createMessage());
byte[] h = SyslogUtility.getBytes(this.syslogConfig,header);
byte[] m = SyslogUtility.getBytes(this.syslogConfig,message);
int mLength = m.length;
} else {
log(getMessageProcessor(), level, message);
}
}
int availableLen = this.syslogConfig.getMaxMessageLength() - h.length;
public void log(int level, SyslogMessageIF message) {
if (message instanceof StructuredSyslogMessageIF) {
if (getMessageProcessor() instanceof StructuredSyslogMessageProcessor) {
log(getMessageProcessor(), level, message.createMessage());
if (this.syslogConfig.isTruncateMessage()) {
if (availableLen > 0 && mLength > availableLen) {
mLength = availableLen;
}
}
} else {
log(getStructuredMessageProcessor(), level, message.createMessage());
}
if (mLength <= availableLen) {
byte[] data = messageProcessor.createPacketData(h,m,0,mLength);
write(level,data);
} else {
byte[] splitBeginText = this.syslogConfig.getSplitMessageBeginText();
byte[] splitEndText = this.syslogConfig.getSplitMessageEndText();
int pos = 0;
int left = mLength;
while(left > 0) {
boolean firstTime = (pos == 0);
boolean doSplitBeginText = splitBeginText != null && !firstTime;
boolean doSplitEndText = splitBeginText != null && (firstTime || (left > (availableLen - splitBeginText.length)));
int actualAvailableLen = availableLen;
actualAvailableLen -= (splitBeginText != null && doSplitBeginText) ? splitBeginText.length : 0;
actualAvailableLen -= (splitEndText != null && doSplitEndText) ? splitEndText.length : 0;
if (actualAvailableLen > left) {
actualAvailableLen = left;
}
if (actualAvailableLen < 0) {
throw new SyslogRuntimeException("Message length < 0; recommendation: increase the size of maxMessageLength");
}
byte[] data = messageProcessor.createPacketData(h,m,pos,actualAvailableLen,doSplitBeginText ? splitBeginText : null,doSplitEndText ? splitEndText : null);
write(level,data);
pos += actualAvailableLen;
left -= actualAvailableLen;
}
}
}
} else {
log(getMessageProcessor(), level, message.createMessage());
}
}
protected abstract void initialize() throws SyslogRuntimeException;
protected abstract void write(int level, byte[] message) throws SyslogRuntimeException;
protected String modifyMessage(int level, String message) {
List _messageModifiers = this.syslogConfig.getMessageModifiers();
if (_messageModifiers == null || _messageModifiers.size() < 1) {
return message;
}
String _message = message;
int facility = this.syslogConfig.getFacility();
for(int i=0; i<_messageModifiers.size(); i++) {
SyslogMessageModifierIF messageModifier = (SyslogMessageModifierIF) _messageModifiers.get(i);
_message = messageModifier.modify(this, facility, level, _message);
}
return _message;
}
public void backLog(int level, String message, Throwable reasonThrowable) {
backLog(level,message,reasonThrowable != null ? reasonThrowable.toString() : "UNKNOWN");
}
public void backLog(int level, String message, String reason) {
boolean status = getBackLogStatus();
if (!status) {
setBackLogStatus(true);
}
List backLogHandlers = this.syslogConfig.getBackLogHandlers();
for(int i=0; i<backLogHandlers.size(); i++) {
SyslogBackLogHandlerIF backLogHandler = (SyslogBackLogHandlerIF) backLogHandlers.get(i);
try {
if (!status) {
backLogHandler.down(this, reason);
this.notifiedBackLogHandlers.add(backLogHandler);
}
backLogHandler.log(this,level,message,reason);
break;
} catch (Exception e) {
// Ignore this Exception and go onto next backLogHandler
}
}
}
public abstract AbstractSyslogWriter getWriter();
public abstract void returnWriter(AbstractSyslogWriter syslogWriter);
public Thread createWriterThread(AbstractSyslogWriter syslogWriter) {
Thread newWriterThread = new Thread(syslogWriter);
newWriterThread.setName("SyslogWriter: " + getProtocol());
newWriterThread.setDaemon(syslogConfig.isUseDaemonThread());
if (syslogConfig.getThreadPriority() > -1) {
newWriterThread.setPriority(syslogConfig.getThreadPriority());
}
syslogWriter.setThread(newWriterThread);
newWriterThread.start();
return newWriterThread;
}
public void debug(String message) {
log(LEVEL_DEBUG, message);
}
public AbstractSyslogWriter createWriter(){
Class clazz = this.syslogConfig.getSyslogWriterClass();
AbstractSyslogWriter newWriter = null;
try {
newWriter = (AbstractSyslogWriter) clazz.newInstance();
newWriter.initialize(this);
} catch (InstantiationException ie) {
if (this.syslogConfig.isThrowExceptionOnInitialize()) {
throw new SyslogRuntimeException(ie);
}
} catch (IllegalAccessException iae) {
if (this.syslogConfig.isThrowExceptionOnInitialize()) {
throw new SyslogRuntimeException(iae);
}
}
public void notice(String message) {
log(LEVEL_NOTICE, message);
}
return newWriter;
}
public void info(String message) {
log(LEVEL_INFO, message);
}
public void warn(String message) {
log(LEVEL_WARN, message);
}
public void error(String message) {
log(LEVEL_ERROR, message);
}
public void critical(String message) {
log(LEVEL_CRITICAL, message);
}
public void alert(String message) {
log(LEVEL_ALERT, message);
}
public void emergency(String message) {
log(LEVEL_EMERGENCY, message);
}
public void debug(SyslogMessageIF message) {
log(LEVEL_DEBUG, message);
}
public void notice(SyslogMessageIF message) {
log(LEVEL_NOTICE, message);
}
public void info(SyslogMessageIF message) {
log(LEVEL_INFO, message);
}
public void warn(SyslogMessageIF message) {
log(LEVEL_WARN, message);
}
public void error(SyslogMessageIF message) {
log(LEVEL_ERROR, message);
}
public void critical(SyslogMessageIF message) {
log(LEVEL_CRITICAL, message);
}
public void alert(SyslogMessageIF message) {
log(LEVEL_ALERT, message);
}
public void emergency(SyslogMessageIF message) {
log(LEVEL_EMERGENCY, message);
}
protected String prefixMessage(String message, String suffix) {
String ident = this.syslogConfig.getIdent();
String _message = ((ident == null || "".equals(ident.trim())) ? "" : (ident + suffix)) + message;
return _message;
}
public void log(SyslogMessageProcessorIF messageProcessor, int level, String message) {
String _message = null;
if (this.syslogConfig.isIncludeIdentInMessageModifier()) {
_message = prefixMessage(message, IDENT_SUFFIX_DEFAULT);
_message = modifyMessage(level, _message);
} else {
_message = modifyMessage(level, message);
_message = prefixMessage(_message, IDENT_SUFFIX_DEFAULT);
}
try {
write(messageProcessor, level, _message);
} catch (SyslogRuntimeException sre) {
if (sre.getCause() != null) {
backLog(level, _message, sre.getCause());
} else {
backLog(level, _message, sre);
}
if (this.syslogConfig.isThrowExceptionOnWrite()) {
throw sre;
}
}
}
protected void write(SyslogMessageProcessorIF messageProcessor, int level, String message) throws SyslogRuntimeException {
String header = messageProcessor.createSyslogHeader(this.syslogConfig.getFacility(), level, this.syslogConfig.getLocalName(), this.syslogConfig.isSendLocalTimestamp(), this.syslogConfig.isSendLocalName());
byte[] h = SyslogUtility.getBytes(this.syslogConfig, header);
byte[] m = SyslogUtility.getBytes(this.syslogConfig, message);
int mLength = m.length;
int availableLen = this.syslogConfig.getMaxMessageLength() - h.length;
if (this.syslogConfig.isTruncateMessage()) {
if (availableLen > 0 && mLength > availableLen) {
mLength = availableLen;
}
}
if (mLength <= availableLen) {
byte[] data = messageProcessor.createPacketData(h, m, 0, mLength);
write(level, data);
} else {
byte[] splitBeginText = this.syslogConfig.getSplitMessageBeginText();
byte[] splitEndText = this.syslogConfig.getSplitMessageEndText();
int pos = 0;
int left = mLength;
while (left > 0) {
boolean firstTime = (pos == 0);
boolean doSplitBeginText = splitBeginText != null && !firstTime;
boolean doSplitEndText = splitBeginText != null && (firstTime || (left > (availableLen - splitBeginText.length)));
int actualAvailableLen = availableLen;
actualAvailableLen -= (splitBeginText != null && doSplitBeginText) ? splitBeginText.length : 0;
actualAvailableLen -= (splitEndText != null && doSplitEndText) ? splitEndText.length : 0;
if (actualAvailableLen > left) {
actualAvailableLen = left;
}
if (actualAvailableLen < 0) {
throw new SyslogRuntimeException("Message length < 0; recommendation: increase the size of maxMessageLength");
}
byte[] data = messageProcessor.createPacketData(h, m, pos, actualAvailableLen, doSplitBeginText ? splitBeginText : null, doSplitEndText ? splitEndText : null);
write(level, data);
pos += actualAvailableLen;
left -= actualAvailableLen;
}
}
}
protected abstract void initialize() throws SyslogRuntimeException;
protected abstract void write(int level, byte[] message) throws SyslogRuntimeException;
protected String modifyMessage(int level, String message) {
List _messageModifiers = this.syslogConfig.getMessageModifiers();
if (_messageModifiers == null || _messageModifiers.size() < 1) {
return message;
}
String _message = message;
int facility = this.syslogConfig.getFacility();
for (int i = 0; i < _messageModifiers.size(); i++) {
SyslogMessageModifierIF messageModifier = (SyslogMessageModifierIF) _messageModifiers.get(i);
_message = messageModifier.modify(this, facility, level, _message);
}
return _message;
}
public void backLog(int level, String message, Throwable reasonThrowable) {
backLog(level, message, reasonThrowable != null ? reasonThrowable.toString() : "UNKNOWN");
}
public void backLog(int level, String message, String reason) {
boolean status = getBackLogStatus();
if (!status) {
setBackLogStatus(true);
}
List backLogHandlers = this.syslogConfig.getBackLogHandlers();
for (int i = 0; i < backLogHandlers.size(); i++) {
SyslogBackLogHandlerIF backLogHandler = (SyslogBackLogHandlerIF) backLogHandlers.get(i);
try {
if (!status) {
backLogHandler.down(this, reason);
this.notifiedBackLogHandlers.add(backLogHandler);
}
backLogHandler.log(this, level, message, reason);
break;
} catch (Exception e) {
// Ignore this Exception and go onto next backLogHandler
}
}
}
public abstract AbstractSyslogWriter getWriter();
public abstract void returnWriter(AbstractSyslogWriter syslogWriter);
public Thread createWriterThread(AbstractSyslogWriter syslogWriter) {
Thread newWriterThread = new Thread(syslogWriter);
newWriterThread.setName("SyslogWriter: " + getProtocol());
newWriterThread.setDaemon(syslogConfig.isUseDaemonThread());
if (syslogConfig.getThreadPriority() > -1) {
newWriterThread.setPriority(syslogConfig.getThreadPriority());
}
syslogWriter.setThread(newWriterThread);
newWriterThread.start();
return newWriterThread;
}
public AbstractSyslogWriter createWriter() {
Class clazz = this.syslogConfig.getSyslogWriterClass();
AbstractSyslogWriter newWriter = null;
try {
newWriter = (AbstractSyslogWriter) clazz.newInstance();
newWriter.initialize(this);
} catch (InstantiationException ie) {
if (this.syslogConfig.isThrowExceptionOnInitialize()) {
throw new SyslogRuntimeException(ie);
}
} catch (IllegalAccessException iae) {
if (this.syslogConfig.isThrowExceptionOnInitialize()) {
throw new SyslogRuntimeException(iae);
}
}
return newWriter;
}
}

View File

@ -10,369 +10,369 @@ import org.graylog2.syslog4j.impl.backlog.printstream.SystemErrSyslogBackLogHand
import org.graylog2.syslog4j.util.SyslogUtility;
/**
* AbstractSyslog provides a base abstract implementation of the SyslogConfigIF
* configuration interface.
*
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: AbstractSyslogConfig.java,v 1.24 2010/11/28 04:43:31 cvs Exp $
*/
* AbstractSyslog provides a base abstract implementation of the SyslogConfigIF
* configuration interface.
* <p/>
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: AbstractSyslogConfig.java,v 1.24 2010/11/28 04:43:31 cvs Exp $
*/
public abstract class AbstractSyslogConfig implements AbstractSyslogConfigIF {
private static final long serialVersionUID = -3728308557871358111L;
protected final static List defaultBackLogHandlers = new ArrayList();
static {
defaultBackLogHandlers.add(new SystemErrSyslogBackLogHandler());
}
protected int facility = SYSLOG_FACILITY_DEFAULT;
protected String charSet = CHAR_SET_DEFAULT;
protected String ident = "";
private static final long serialVersionUID = -3728308557871358111L;
protected String localName = null;
protected final static List defaultBackLogHandlers = new ArrayList();
protected boolean sendLocalTimestamp = SEND_LOCAL_TIMESTAMP_DEFAULT;
protected boolean sendLocalName = SEND_LOCAL_NAME_DEFAULT;
protected boolean includeIdentInMessageModifier = INCLUDE_IDENT_IN_MESSAGE_MODIFIER_DEFAULT;
protected boolean throwExceptionOnWrite = THROW_EXCEPTION_ON_WRITE_DEFAULT;
protected boolean throwExceptionOnInitialize = THROW_EXCEPTION_ON_INITIALIZE_DEFAULT;
protected int maxMessageLength = MAX_MESSAGE_LENGTH_DEFAULT;
protected byte[] splitMessageBeginText = SPLIT_MESSAGE_BEGIN_TEXT_DEFAULT.getBytes();
protected byte[] splitMessageEndText = SPLIT_MESSAGE_END_TEXT_DEFAULT.getBytes();
protected List messageModifiers = null;
protected List backLogHandlers = null;
static {
defaultBackLogHandlers.add(new SystemErrSyslogBackLogHandler());
}
protected boolean threaded = THREADED_DEFAULT;
protected boolean useDaemonThread = USE_DAEMON_THREAD_DEFAULT;
protected int threadPriority = THREAD_PRIORITY_DEFAULT;
protected long threadLoopInterval = THREAD_LOOP_INTERVAL_DEFAULT;
protected int writeRetries = WRITE_RETRIES_DEFAULT;
protected long maxShutdownWait = MAX_SHUTDOWN_WAIT_DEFAULT;
protected boolean truncateMessage = TRUNCATE_MESSAGE_DEFAULT;
protected boolean useStructuredData = USE_STRUCTURED_DATA_DEFAULT;
protected int facility = SYSLOG_FACILITY_DEFAULT;
public abstract Class getSyslogClass();
public String getCharSet() {
return this.charSet;
}
protected String charSet = CHAR_SET_DEFAULT;
public void setCharSet(String charSet) {
this.charSet = charSet;
}
protected String ident = "";
public String getLocalName() {
return localName;
}
protected String localName = null;
public void setLocalName(String localName) {
this.localName = localName;
}
protected boolean sendLocalTimestamp = SEND_LOCAL_TIMESTAMP_DEFAULT;
protected boolean sendLocalName = SEND_LOCAL_NAME_DEFAULT;
public boolean isThrowExceptionOnWrite() {
return this.throwExceptionOnWrite;
}
protected boolean includeIdentInMessageModifier = INCLUDE_IDENT_IN_MESSAGE_MODIFIER_DEFAULT;
protected boolean throwExceptionOnWrite = THROW_EXCEPTION_ON_WRITE_DEFAULT;
protected boolean throwExceptionOnInitialize = THROW_EXCEPTION_ON_INITIALIZE_DEFAULT;
public void setThrowExceptionOnWrite(boolean throwExceptionOnWrite) {
this.throwExceptionOnWrite = throwExceptionOnWrite;
}
protected int maxMessageLength = MAX_MESSAGE_LENGTH_DEFAULT;
protected byte[] splitMessageBeginText = SPLIT_MESSAGE_BEGIN_TEXT_DEFAULT.getBytes();
protected byte[] splitMessageEndText = SPLIT_MESSAGE_END_TEXT_DEFAULT.getBytes();
public boolean isThrowExceptionOnInitialize() {
return this.throwExceptionOnInitialize;
}
protected List messageModifiers = null;
protected List backLogHandlers = null;
public void setThrowExceptionOnInitialize(boolean throwExceptionOnInitialize) {
this.throwExceptionOnInitialize = throwExceptionOnInitialize;
}
protected boolean threaded = THREADED_DEFAULT;
protected boolean useDaemonThread = USE_DAEMON_THREAD_DEFAULT;
protected int threadPriority = THREAD_PRIORITY_DEFAULT;
protected long threadLoopInterval = THREAD_LOOP_INTERVAL_DEFAULT;
public byte[] getSplitMessageBeginText() {
return this.splitMessageBeginText;
}
protected int writeRetries = WRITE_RETRIES_DEFAULT;
protected long maxShutdownWait = MAX_SHUTDOWN_WAIT_DEFAULT;
public void setSplitMessageBeginText(byte[] splitMessageBeginText) {
this.splitMessageBeginText = splitMessageBeginText;
}
protected boolean truncateMessage = TRUNCATE_MESSAGE_DEFAULT;
protected boolean useStructuredData = USE_STRUCTURED_DATA_DEFAULT;
public void setSplitMessageBeginText(String splitMessageBeginText) throws SyslogRuntimeException {
this.splitMessageBeginText = SyslogUtility.getBytes(this,splitMessageBeginText);
}
public abstract Class getSyslogClass();
public byte[] getSplitMessageEndText() {
return this.splitMessageEndText;
}
public String getCharSet() {
return this.charSet;
}
public void setSplitMessageEndText(byte[] splitMessageEndText) {
this.splitMessageEndText = splitMessageEndText;
}
public void setCharSet(String charSet) {
this.charSet = charSet;
}
public void setSplitMessageEndText(String splitMessageEndText) throws SyslogRuntimeException {
this.splitMessageEndText = SyslogUtility.getBytes(this,splitMessageEndText);
}
public String getLocalName() {
return localName;
}
public int getMaxMessageLength() {
return this.maxMessageLength;
}
public void setLocalName(String localName) {
this.localName = localName;
}
public void setMaxMessageLength(int maxMessageLength) {
this.maxMessageLength = maxMessageLength;
}
public boolean isThrowExceptionOnWrite() {
return this.throwExceptionOnWrite;
}
public boolean isSendLocalTimestamp() {
return this.sendLocalTimestamp;
}
public void setThrowExceptionOnWrite(boolean throwExceptionOnWrite) {
this.throwExceptionOnWrite = throwExceptionOnWrite;
}
public void setSendLocalTimestamp(boolean sendLocalTimestamp) {
this.sendLocalTimestamp = sendLocalTimestamp;
}
public boolean isThrowExceptionOnInitialize() {
return this.throwExceptionOnInitialize;
}
public boolean isSendLocalName() {
return this.sendLocalName;
}
public void setThrowExceptionOnInitialize(boolean throwExceptionOnInitialize) {
this.throwExceptionOnInitialize = throwExceptionOnInitialize;
}
public void setSendLocalName(boolean sendLocalName) {
this.sendLocalName = sendLocalName;
}
public int getFacility() {
return this.facility;
}
public byte[] getSplitMessageBeginText() {
return this.splitMessageBeginText;
}
public void setFacility(int facility) {
this.facility = facility;
}
public void setSplitMessageBeginText(byte[] splitMessageBeginText) {
this.splitMessageBeginText = splitMessageBeginText;
}
public void setFacility(String facilityName) {
this.facility = SyslogUtility.getFacility(facilityName);
}
public String getIdent() {
return this.ident;
}
public void setIdent(String ident) {
this.ident = ident;
}
public void setSplitMessageBeginText(String splitMessageBeginText) throws SyslogRuntimeException {
this.splitMessageBeginText = SyslogUtility.getBytes(this, splitMessageBeginText);
}
protected synchronized List _getMessageModifiers() {
if (this.messageModifiers == null) {
this.messageModifiers = new ArrayList();
}
return this.messageModifiers;
}
public void addMessageModifier(SyslogMessageModifierIF messageModifier) {
if (messageModifier == null) {
return;
}
List _messageModifiers = _getMessageModifiers();
synchronized(_messageModifiers) {
_messageModifiers.add(messageModifier);
}
}
public byte[] getSplitMessageEndText() {
return this.splitMessageEndText;
}
public void insertMessageModifier(int index, SyslogMessageModifierIF messageModifier) {
if (messageModifier == null) {
return;
}
List _messageModifiers = _getMessageModifiers();
synchronized(_messageModifiers) {
try {
_messageModifiers.add(index,messageModifier);
} catch (IndexOutOfBoundsException ioobe) {
throw new SyslogRuntimeException(ioobe);
}
}
}
public void setSplitMessageEndText(byte[] splitMessageEndText) {
this.splitMessageEndText = splitMessageEndText;
}
public void removeMessageModifier(SyslogMessageModifierIF messageModifier) {
if (messageModifier == null) {
return;
}
List _messageModifiers = _getMessageModifiers();
synchronized(_messageModifiers) {
_messageModifiers.remove(messageModifier);
}
}
public void setSplitMessageEndText(String splitMessageEndText) throws SyslogRuntimeException {
this.splitMessageEndText = SyslogUtility.getBytes(this, splitMessageEndText);
}
public List getMessageModifiers() {
return this.messageModifiers;
}
public int getMaxMessageLength() {
return this.maxMessageLength;
}
public void setMessageModifiers(List messageModifiers) {
this.messageModifiers = messageModifiers;
}
public void removeAllMessageModifiers() {
if (this.messageModifiers == null || this.messageModifiers.isEmpty()) {
return;
}
this.messageModifiers.clear();
}
public void setMaxMessageLength(int maxMessageLength) {
this.maxMessageLength = maxMessageLength;
}
protected synchronized List _getBackLogHandlers() {
if (this.backLogHandlers == null) {
this.backLogHandlers = new ArrayList();
}
return this.backLogHandlers;
}
public void addBackLogHandler(SyslogBackLogHandlerIF backLogHandler) {
if (backLogHandler == null) {
return;
}
List _backLogHandlers = _getBackLogHandlers();
synchronized(_backLogHandlers) {
backLogHandler.initialize();
_backLogHandlers.add(backLogHandler);
}
}
public boolean isSendLocalTimestamp() {
return this.sendLocalTimestamp;
}
public void insertBackLogHandler(int index, SyslogBackLogHandlerIF backLogHandler) {
if (backLogHandler == null) {
return;
}
List _backLogHandlers = _getBackLogHandlers();
synchronized(_backLogHandlers) {
try {
backLogHandler.initialize();
_backLogHandlers.add(index,backLogHandler);
} catch (IndexOutOfBoundsException ioobe) {
throw new SyslogRuntimeException(ioobe);
}
}
}
public void setSendLocalTimestamp(boolean sendLocalTimestamp) {
this.sendLocalTimestamp = sendLocalTimestamp;
}
public void removeBackLogHandler(SyslogBackLogHandlerIF backLogHandler) {
if (backLogHandler == null) {
return;
}
List _backLogHandlers = _getBackLogHandlers();
synchronized(_backLogHandlers) {
_backLogHandlers.remove(backLogHandler);
}
}
public boolean isSendLocalName() {
return this.sendLocalName;
}
public List getBackLogHandlers() {
if (this.backLogHandlers == null || this.backLogHandlers.size() < 1) {
return defaultBackLogHandlers;
}
return this.backLogHandlers;
}
public void setSendLocalName(boolean sendLocalName) {
this.sendLocalName = sendLocalName;
}
public void setBackLogHandlers(List backLogHandlers) {
this.backLogHandlers = backLogHandlers;
}
public void removeAllBackLogHandlers() {
if (this.backLogHandlers == null || this.backLogHandlers.isEmpty()) {
return;
}
this.backLogHandlers.clear();
}
public int getFacility() {
return this.facility;
}
public boolean isIncludeIdentInMessageModifier() {
return this.includeIdentInMessageModifier;
}
public void setFacility(int facility) {
this.facility = facility;
}
public void setIncludeIdentInMessageModifier(boolean includeIdentInMessageModifier) {
this.includeIdentInMessageModifier = includeIdentInMessageModifier;
}
public void setFacility(String facilityName) {
this.facility = SyslogUtility.getFacility(facilityName);
}
public boolean isThreaded() {
return this.threaded;
}
public String getIdent() {
return this.ident;
}
public void setThreaded(boolean threaded) {
this.threaded = threaded;
}
public void setIdent(String ident) {
this.ident = ident;
}
public boolean isUseDaemonThread() {
return useDaemonThread;
}
protected synchronized List _getMessageModifiers() {
if (this.messageModifiers == null) {
this.messageModifiers = new ArrayList();
}
public void setUseDaemonThread(boolean useDaemonThread) {
this.useDaemonThread = useDaemonThread;
}
return this.messageModifiers;
}
public int getThreadPriority() {
return threadPriority;
}
public void addMessageModifier(SyslogMessageModifierIF messageModifier) {
if (messageModifier == null) {
return;
}
public void setThreadPriority(int threadPriority) {
this.threadPriority = threadPriority;
}
List _messageModifiers = _getMessageModifiers();
public long getThreadLoopInterval() {
return this.threadLoopInterval;
}
synchronized (_messageModifiers) {
_messageModifiers.add(messageModifier);
}
}
public void setThreadLoopInterval(long threadLoopInterval) {
this.threadLoopInterval = threadLoopInterval;
}
public long getMaxShutdownWait() {
return this.maxShutdownWait;
}
public void insertMessageModifier(int index, SyslogMessageModifierIF messageModifier) {
if (messageModifier == null) {
return;
}
public void setMaxShutdownWait(long maxShutdownWait) {
this.maxShutdownWait = maxShutdownWait;
}
List _messageModifiers = _getMessageModifiers();
public int getWriteRetries() {
return this.writeRetries;
}
synchronized (_messageModifiers) {
try {
_messageModifiers.add(index, messageModifier);
public void setWriteRetries(int writeRetries) {
this.writeRetries = writeRetries;
}
} catch (IndexOutOfBoundsException ioobe) {
throw new SyslogRuntimeException(ioobe);
}
}
}
public boolean isTruncateMessage() {
return this.truncateMessage;
}
public void removeMessageModifier(SyslogMessageModifierIF messageModifier) {
if (messageModifier == null) {
return;
}
public void setTruncateMessage(boolean truncateMessage) {
this.truncateMessage = truncateMessage;
}
List _messageModifiers = _getMessageModifiers();
public boolean isUseStructuredData() {
return this.useStructuredData;
}
synchronized (_messageModifiers) {
_messageModifiers.remove(messageModifier);
}
}
public void setUseStructuredData(boolean useStructuredData) {
this.useStructuredData = useStructuredData;
}
public List getMessageModifiers() {
return this.messageModifiers;
}
public Class getSyslogWriterClass() {
return null;
}
public void setMessageModifiers(List messageModifiers) {
this.messageModifiers = messageModifiers;
}
public void removeAllMessageModifiers() {
if (this.messageModifiers == null || this.messageModifiers.isEmpty()) {
return;
}
this.messageModifiers.clear();
}
protected synchronized List _getBackLogHandlers() {
if (this.backLogHandlers == null) {
this.backLogHandlers = new ArrayList();
}
return this.backLogHandlers;
}
public void addBackLogHandler(SyslogBackLogHandlerIF backLogHandler) {
if (backLogHandler == null) {
return;
}
List _backLogHandlers = _getBackLogHandlers();
synchronized (_backLogHandlers) {
backLogHandler.initialize();
_backLogHandlers.add(backLogHandler);
}
}
public void insertBackLogHandler(int index, SyslogBackLogHandlerIF backLogHandler) {
if (backLogHandler == null) {
return;
}
List _backLogHandlers = _getBackLogHandlers();
synchronized (_backLogHandlers) {
try {
backLogHandler.initialize();
_backLogHandlers.add(index, backLogHandler);
} catch (IndexOutOfBoundsException ioobe) {
throw new SyslogRuntimeException(ioobe);
}
}
}
public void removeBackLogHandler(SyslogBackLogHandlerIF backLogHandler) {
if (backLogHandler == null) {
return;
}
List _backLogHandlers = _getBackLogHandlers();
synchronized (_backLogHandlers) {
_backLogHandlers.remove(backLogHandler);
}
}
public List getBackLogHandlers() {
if (this.backLogHandlers == null || this.backLogHandlers.size() < 1) {
return defaultBackLogHandlers;
}
return this.backLogHandlers;
}
public void setBackLogHandlers(List backLogHandlers) {
this.backLogHandlers = backLogHandlers;
}
public void removeAllBackLogHandlers() {
if (this.backLogHandlers == null || this.backLogHandlers.isEmpty()) {
return;
}
this.backLogHandlers.clear();
}
public boolean isIncludeIdentInMessageModifier() {
return this.includeIdentInMessageModifier;
}
public void setIncludeIdentInMessageModifier(boolean includeIdentInMessageModifier) {
this.includeIdentInMessageModifier = includeIdentInMessageModifier;
}
public boolean isThreaded() {
return this.threaded;
}
public void setThreaded(boolean threaded) {
this.threaded = threaded;
}
public boolean isUseDaemonThread() {
return useDaemonThread;
}
public void setUseDaemonThread(boolean useDaemonThread) {
this.useDaemonThread = useDaemonThread;
}
public int getThreadPriority() {
return threadPriority;
}
public void setThreadPriority(int threadPriority) {
this.threadPriority = threadPriority;
}
public long getThreadLoopInterval() {
return this.threadLoopInterval;
}
public void setThreadLoopInterval(long threadLoopInterval) {
this.threadLoopInterval = threadLoopInterval;
}
public long getMaxShutdownWait() {
return this.maxShutdownWait;
}
public void setMaxShutdownWait(long maxShutdownWait) {
this.maxShutdownWait = maxShutdownWait;
}
public int getWriteRetries() {
return this.writeRetries;
}
public void setWriteRetries(int writeRetries) {
this.writeRetries = writeRetries;
}
public boolean isTruncateMessage() {
return this.truncateMessage;
}
public void setTruncateMessage(boolean truncateMessage) {
this.truncateMessage = truncateMessage;
}
public boolean isUseStructuredData() {
return this.useStructuredData;
}
public void setUseStructuredData(boolean useStructuredData) {
this.useStructuredData = useStructuredData;
}
public Class getSyslogWriterClass() {
return null;
}
}

View File

@ -5,52 +5,61 @@ import java.util.List;
import org.graylog2.syslog4j.SyslogConfigIF;
/**
* AbstractSyslogConfigIF provides an interface for all Abstract Syslog
* configuration implementations.
*
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: AbstractSyslogConfigIF.java,v 1.7 2010/10/29 03:14:20 cvs Exp $
*/
* AbstractSyslogConfigIF provides an interface for all Abstract Syslog
* configuration implementations.
* <p/>
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: AbstractSyslogConfigIF.java,v 1.7 2010/10/29 03:14:20 cvs Exp $
*/
public interface AbstractSyslogConfigIF extends SyslogConfigIF {
public Class getSyslogWriterClass();
public List getBackLogHandlers();
public List getMessageModifiers();
public Class getSyslogWriterClass();
public byte[] getSplitMessageBeginText();
public void setSplitMessageBeginText(byte[] beginText);
public byte[] getSplitMessageEndText();
public void setSplitMessageEndText(byte[] endText);
public List getBackLogHandlers();
public boolean isThreaded();
public void setThreaded(boolean threaded);
public boolean isUseDaemonThread();
public void setUseDaemonThread(boolean useDaemonThread);
public int getThreadPriority();
public void setThreadPriority(int threadPriority);
public long getThreadLoopInterval();
public void setThreadLoopInterval(long threadLoopInterval);
public long getMaxShutdownWait();
public void setMaxShutdownWait(long maxShutdownWait);
public int getWriteRetries();
public void setWriteRetries(int writeRetries);
public int getMaxQueueSize();
/**
* Use the (default) value of -1 to allow for a queue of indefinite depth (size).
*
* @param maxQueueSize
*/
public void setMaxQueueSize(int maxQueueSize);
public List getMessageModifiers();
public byte[] getSplitMessageBeginText();
public void setSplitMessageBeginText(byte[] beginText);
public byte[] getSplitMessageEndText();
public void setSplitMessageEndText(byte[] endText);
public boolean isThreaded();
public void setThreaded(boolean threaded);
public boolean isUseDaemonThread();
public void setUseDaemonThread(boolean useDaemonThread);
public int getThreadPriority();
public void setThreadPriority(int threadPriority);
public long getThreadLoopInterval();
public void setThreadLoopInterval(long threadLoopInterval);
public long getMaxShutdownWait();
public void setMaxShutdownWait(long maxShutdownWait);
public int getWriteRetries();
public void setWriteRetries(int writeRetries);
public int getMaxQueueSize();
/**
* Use the (default) value of -1 to allow for a queue of indefinite depth (size).
*
* @param maxQueueSize
*/
public void setMaxQueueSize(int maxQueueSize);
}

View File

@ -9,101 +9,101 @@ import org.graylog2.syslog4j.SyslogRuntimeException;
import org.graylog2.syslog4j.util.SyslogUtility;
/**
* AbstractSyslogWriter is an implementation of Runnable that supports sending
* syslog messages within a separate Thread or an object pool.
*
* <p>When used in "threaded" mode (see TCPNetSyslogConfig for the option),
* a queuing mechanism is used (via LinkedList).</p>
*
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: AbstractSyslogWriter.java,v 1.9 2010/10/25 03:50:25 cvs Exp $
*/
* AbstractSyslogWriter is an implementation of Runnable that supports sending
* syslog messages within a separate Thread or an object pool.
* <p/>
* <p>When used in "threaded" mode (see TCPNetSyslogConfig for the option),
* a queuing mechanism is used (via LinkedList).</p>
* <p/>
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: AbstractSyslogWriter.java,v 1.9 2010/10/25 03:50:25 cvs Exp $
*/
public abstract class AbstractSyslogWriter implements Runnable, Serializable {
private static final long serialVersionUID = 836468466009035847L;
protected AbstractSyslog syslog = null;
private static final long serialVersionUID = 836468466009035847L;
protected List queuedMessages = null;
protected Thread thread = null;
protected AbstractSyslog syslog = null;
protected AbstractSyslogConfigIF syslogConfig = null;
protected List queuedMessages = null;
protected boolean shutdown = false;
public void initialize(AbstractSyslog abstractSyslog) {
this.syslog = abstractSyslog;
protected Thread thread = null;
try {
this.syslogConfig = (AbstractSyslogConfigIF) this.syslog.getConfig();
} catch (ClassCastException cce) {
throw new SyslogRuntimeException("config must implement interface AbstractSyslogConfigIF");
}
if (this.syslogConfig.isThreaded()) {
this.queuedMessages = new LinkedList();
}
}
public void queue(int level, byte[] message) {
synchronized(this.queuedMessages) {
if (this.syslogConfig.getMaxQueueSize() == -1 || this.queuedMessages.size() < this.syslogConfig.getMaxQueueSize()) {
this.queuedMessages.add(message);
} else {
this.syslog.backLog(level,SyslogUtility.newString(syslogConfig,message),"MaxQueueSize (" + this.syslogConfig.getMaxQueueSize() + ") reached");
}
}
}
public void setThread(Thread thread) {
this.thread = thread;
}
public boolean hasThread() {
return this.thread != null && this.thread.isAlive();
}
protected AbstractSyslogConfigIF syslogConfig = null;
public abstract void write(byte[] message);
public abstract void flush();
public abstract void shutdown();
protected abstract void runCompleted();
protected boolean shutdown = false;
public void run() {
while(!this.shutdown || !this.queuedMessages.isEmpty()) {
List queuedMessagesCopy = null;
synchronized(this.queuedMessages) {
queuedMessagesCopy = new LinkedList(this.queuedMessages);
this.queuedMessages.clear();
}
if (queuedMessagesCopy != null) {
while(!queuedMessagesCopy.isEmpty()) {
byte[] message = (byte[]) queuedMessagesCopy.remove(0);
try {
write(message);
this.syslog.setBackLogStatus(false);
} catch (SyslogRuntimeException sre) {
this.syslog.backLog(SyslogConstants.LEVEL_INFO,SyslogUtility.newString(this.syslog.getConfig(),message),sre);
}
}
}
SyslogUtility.sleep(this.syslogConfig.getThreadLoopInterval());
}
runCompleted();
}
public void initialize(AbstractSyslog abstractSyslog) {
this.syslog = abstractSyslog;
try {
this.syslogConfig = (AbstractSyslogConfigIF) this.syslog.getConfig();
} catch (ClassCastException cce) {
throw new SyslogRuntimeException("config must implement interface AbstractSyslogConfigIF");
}
if (this.syslogConfig.isThreaded()) {
this.queuedMessages = new LinkedList();
}
}
public void queue(int level, byte[] message) {
synchronized (this.queuedMessages) {
if (this.syslogConfig.getMaxQueueSize() == -1 || this.queuedMessages.size() < this.syslogConfig.getMaxQueueSize()) {
this.queuedMessages.add(message);
} else {
this.syslog.backLog(level, SyslogUtility.newString(syslogConfig, message), "MaxQueueSize (" + this.syslogConfig.getMaxQueueSize() + ") reached");
}
}
}
public void setThread(Thread thread) {
this.thread = thread;
}
public boolean hasThread() {
return this.thread != null && this.thread.isAlive();
}
public abstract void write(byte[] message);
public abstract void flush();
public abstract void shutdown();
protected abstract void runCompleted();
public void run() {
while (!this.shutdown || !this.queuedMessages.isEmpty()) {
List queuedMessagesCopy = null;
synchronized (this.queuedMessages) {
queuedMessagesCopy = new LinkedList(this.queuedMessages);
this.queuedMessages.clear();
}
if (queuedMessagesCopy != null) {
while (!queuedMessagesCopy.isEmpty()) {
byte[] message = (byte[]) queuedMessagesCopy.remove(0);
try {
write(message);
this.syslog.setBackLogStatus(false);
} catch (SyslogRuntimeException sre) {
this.syslog.backLog(SyslogConstants.LEVEL_INFO, SyslogUtility.newString(this.syslog.getConfig(), message), sre);
}
}
}
SyslogUtility.sleep(this.syslogConfig.getThreadLoopInterval());
}
runCompleted();
}
}

View File

@ -5,32 +5,32 @@ import org.graylog2.syslog4j.SyslogIF;
import org.graylog2.syslog4j.util.SyslogUtility;
/**
* AbstractSyslogBackLogHandler is an implementation of SyslogBackLogHandlerIF
* that mainly provides the helpful "combine" method for handling the "reason"
* why a BackLog has occurred.
*
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: AbstractSyslogBackLogHandler.java,v 1.1 2009/01/24 22:00:18 cvs Exp $
*/
* AbstractSyslogBackLogHandler is an implementation of SyslogBackLogHandlerIF
* that mainly provides the helpful "combine" method for handling the "reason"
* why a BackLog has occurred.
* <p/>
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: AbstractSyslogBackLogHandler.java,v 1.1 2009/01/24 22:00:18 cvs Exp $
*/
public abstract class AbstractSyslogBackLogHandler implements SyslogBackLogHandlerIF {
protected boolean appendReason = true;
protected boolean appendReason = true;
protected String combine(SyslogIF syslog, int level, String message, String reason) {
// Note: syslog is explicitly ignored by default
String _message = message != null ? message : "UNKNOWN";
String _reason = reason != null ? reason : "UNKNOWN";
String combinedMessage = SyslogUtility.getLevelString(level) + " " + _message;
if (this.appendReason) {
combinedMessage += " [" + _reason + "]";
}
return combinedMessage;
}
protected String combine(SyslogIF syslog, int level, String message, String reason) {
// Note: syslog is explicitly ignored by default
String _message = message != null ? message : "UNKNOWN";
String _reason = reason != null ? reason : "UNKNOWN";
String combinedMessage = SyslogUtility.getLevelString(level) + " " + _message;
if (this.appendReason) {
combinedMessage += " [" + _reason + "]";
}
return combinedMessage;
}
}

View File

@ -4,32 +4,32 @@ import org.graylog2.syslog4j.SyslogBackLogHandlerIF;
import org.graylog2.syslog4j.SyslogIF;
/**
* NullSyslogBackLogHandler can be used if there's no need for a last-chance
* logging mechanism whenever the Syslog protocol fails.
*
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: NullSyslogBackLogHandler.java,v 1.2 2010/10/25 03:50:25 cvs Exp $
*/
* NullSyslogBackLogHandler can be used if there's no need for a last-chance
* logging mechanism whenever the Syslog protocol fails.
* <p/>
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: NullSyslogBackLogHandler.java,v 1.2 2010/10/25 03:50:25 cvs Exp $
*/
public class NullSyslogBackLogHandler implements SyslogBackLogHandlerIF {
public static final NullSyslogBackLogHandler INSTANCE = new NullSyslogBackLogHandler();
public void initialize() {
//
}
public static final NullSyslogBackLogHandler INSTANCE = new NullSyslogBackLogHandler();
public void down(SyslogIF syslog, String reason) {
//
}
public void initialize() {
//
}
public void up(SyslogIF syslog) {
//
}
public void down(SyslogIF syslog, String reason) {
//
}
public void log(SyslogIF syslog, int level, String message, String reason) {
//
}
public void up(SyslogIF syslog) {
//
}
public void log(SyslogIF syslog, int level, String message, String reason) {
//
}
}

View File

@ -6,62 +6,62 @@ import org.graylog2.syslog4j.SyslogIF;
import org.graylog2.syslog4j.SyslogRuntimeException;
/**
* Syslog4jBackLogHandler is used to send Syslog backLog messages to
* another Syslog4j protocol whenever the main Syslog protocol fails.
*
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: Syslog4jBackLogHandler.java,v 1.1 2009/07/25 18:42:47 cvs Exp $
*/
* Syslog4jBackLogHandler is used to send Syslog backLog messages to
* another Syslog4j protocol whenever the main Syslog protocol fails.
* <p/>
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: Syslog4jBackLogHandler.java,v 1.1 2009/07/25 18:42:47 cvs Exp $
*/
public class Syslog4jBackLogHandler extends AbstractSyslogBackLogHandler {
protected SyslogIF syslog = null;
protected int downLevel = SyslogConstants.LEVEL_WARN;
protected int upLevel = SyslogConstants.LEVEL_WARN;
protected SyslogIF syslog = null;
protected int downLevel = SyslogConstants.LEVEL_WARN;
protected int upLevel = SyslogConstants.LEVEL_WARN;
public Syslog4jBackLogHandler(String protocol) {
this.syslog = Syslog.getInstance(protocol);
}
public Syslog4jBackLogHandler(String protocol, boolean appendReason) {
this.syslog = Syslog.getInstance(protocol);
this.appendReason = appendReason;
}
public Syslog4jBackLogHandler(SyslogIF syslog) {
this.syslog = syslog;
}
public Syslog4jBackLogHandler(SyslogIF syslog, boolean appendReason) {
this.syslog = syslog;
this.appendReason = appendReason;
}
public void initialize() throws SyslogRuntimeException {
// NO-OP
}
public Syslog4jBackLogHandler(String protocol) {
this.syslog = Syslog.getInstance(protocol);
}
public void log(SyslogIF syslog, int level, String message, String reason) throws SyslogRuntimeException {
if (this.syslog.getProtocol().equals(syslog.getProtocol())) {
throw new SyslogRuntimeException("Ignoring this log entry since the backLog protocol \"" + this.syslog.getProtocol() + "\" is the same as the main protocol");
}
String combinedMessage = combine(syslog,level,message,reason);
this.syslog.log(level,combinedMessage);
}
public Syslog4jBackLogHandler(String protocol, boolean appendReason) {
this.syslog = Syslog.getInstance(protocol);
this.appendReason = appendReason;
}
public void down(SyslogIF syslog, String reason) {
if (!this.syslog.getProtocol().equals(syslog.getProtocol())) {
this.syslog.log(this.downLevel,"Syslog protocol \"" + syslog.getProtocol() + "\" is down: " + reason);
}
}
public Syslog4jBackLogHandler(SyslogIF syslog) {
this.syslog = syslog;
}
public void up(SyslogIF syslog) {
if (!this.syslog.getProtocol().equals(syslog.getProtocol())) {
this.syslog.log(this.downLevel,"Syslog protocol \"" + syslog.getProtocol() + "\" is up");
}
}
public Syslog4jBackLogHandler(SyslogIF syslog, boolean appendReason) {
this.syslog = syslog;
this.appendReason = appendReason;
}
public void initialize() throws SyslogRuntimeException {
// NO-OP
}
public void log(SyslogIF syslog, int level, String message, String reason) throws SyslogRuntimeException {
if (this.syslog.getProtocol().equals(syslog.getProtocol())) {
throw new SyslogRuntimeException("Ignoring this log entry since the backLog protocol \"" + this.syslog.getProtocol() + "\" is the same as the main protocol");
}
String combinedMessage = combine(syslog, level, message, reason);
this.syslog.log(level, combinedMessage);
}
public void down(SyslogIF syslog, String reason) {
if (!this.syslog.getProtocol().equals(syslog.getProtocol())) {
this.syslog.log(this.downLevel, "Syslog protocol \"" + syslog.getProtocol() + "\" is down: " + reason);
}
}
public void up(SyslogIF syslog) {
if (!this.syslog.getProtocol().equals(syslog.getProtocol())) {
this.syslog.log(this.downLevel, "Syslog protocol \"" + syslog.getProtocol() + "\" is up");
}
}
}

View File

@ -9,140 +9,148 @@ import org.graylog2.syslog4j.SyslogRuntimeException;
import org.graylog2.syslog4j.impl.backlog.AbstractSyslogBackLogHandler;
/**
* Log4jSyslogBackLogHandler is used to send Syslog backLog messages to
* Log4j whenever the Syslog protocol fails.
*
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: Log4jSyslogBackLogHandler.java,v 1.2 2009/07/22 15:54:23 cvs Exp $
*/
* Log4jSyslogBackLogHandler is used to send Syslog backLog messages to
* Log4j whenever the Syslog protocol fails.
* <p/>
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: Log4jSyslogBackLogHandler.java,v 1.2 2009/07/22 15:54:23 cvs Exp $
*/
public class Log4jSyslogBackLogHandler extends AbstractSyslogBackLogHandler {
protected Logger logger = null;
protected Level downLevel = Level.WARN;
protected Level upLevel = Level.WARN;
public Log4jSyslogBackLogHandler(Logger logger) throws SyslogRuntimeException {
this.logger = logger;
initialize();
}
protected Logger logger = null;
protected Level downLevel = Level.WARN;
protected Level upLevel = Level.WARN;
public Log4jSyslogBackLogHandler(Logger logger, boolean appendReason) {
this.logger = logger;
this.appendReason = appendReason;
public Log4jSyslogBackLogHandler(Logger logger) throws SyslogRuntimeException {
this.logger = logger;
initialize();
}
initialize();
}
public Log4jSyslogBackLogHandler(Class loggerClass) {
if (loggerClass == null) {
throw new SyslogRuntimeException("loggerClass cannot be null");
}
this.logger = Logger.getLogger(loggerClass);
initialize();
}
public Log4jSyslogBackLogHandler(Logger logger, boolean appendReason) {
this.logger = logger;
this.appendReason = appendReason;
public Log4jSyslogBackLogHandler(Class loggerClass, boolean appendReason) {
if (loggerClass == null) {
throw new SyslogRuntimeException("loggerClass cannot be null");
}
this.logger = Logger.getLogger(loggerClass);
this.appendReason = appendReason;
initialize();
}
initialize();
}
public Log4jSyslogBackLogHandler(String loggerName) {
if (loggerName == null) {
throw new SyslogRuntimeException("loggerName cannot be null");
}
this.logger = Logger.getLogger(loggerName);
public Log4jSyslogBackLogHandler(Class loggerClass) {
if (loggerClass == null) {
throw new SyslogRuntimeException("loggerClass cannot be null");
}
initialize();
}
this.logger = Logger.getLogger(loggerClass);
public Log4jSyslogBackLogHandler(String loggerName, boolean appendReason) {
if (loggerName == null) {
throw new SyslogRuntimeException("loggerName cannot be null");
}
this.logger = Logger.getLogger(loggerName);
this.appendReason = appendReason;
initialize();
}
initialize();
}
public Log4jSyslogBackLogHandler(Class loggerClass, boolean appendReason) {
if (loggerClass == null) {
throw new SyslogRuntimeException("loggerClass cannot be null");
}
public Log4jSyslogBackLogHandler(String loggerName, LoggerFactory loggerFactory) {
if (loggerName == null) {
throw new SyslogRuntimeException("loggerName cannot be null");
}
if (loggerFactory == null) {
throw new SyslogRuntimeException("loggerFactory cannot be null");
}
this.logger = Logger.getLogger(loggerName,loggerFactory);
this.logger = Logger.getLogger(loggerClass);
this.appendReason = appendReason;
initialize();
}
public Log4jSyslogBackLogHandler(String loggerName, LoggerFactory loggerFactory, boolean appendReason) {
if (loggerName == null) {
throw new SyslogRuntimeException("loggerName cannot be null");
}
if (loggerFactory == null) {
throw new SyslogRuntimeException("loggerFactory cannot be null");
}
this.logger = Logger.getLogger(loggerName,loggerFactory);
this.appendReason = appendReason;
initialize();
}
initialize();
}
public Log4jSyslogBackLogHandler(String loggerName) {
if (loggerName == null) {
throw new SyslogRuntimeException("loggerName cannot be null");
}
public void initialize() throws SyslogRuntimeException {
if (this.logger == null) {
throw new SyslogRuntimeException("logger cannot be null");
}
}
protected static Level getLog4jLevel(int level) {
switch(level) {
case SyslogConstants.LEVEL_DEBUG: return Level.DEBUG;
case SyslogConstants.LEVEL_INFO: return Level.INFO;
case SyslogConstants.LEVEL_NOTICE: return Level.INFO;
case SyslogConstants.LEVEL_WARN: return Level.WARN;
case SyslogConstants.LEVEL_ERROR: return Level.ERROR;
case SyslogConstants.LEVEL_CRITICAL: return Level.ERROR;
case SyslogConstants.LEVEL_ALERT: return Level.ERROR;
case SyslogConstants.LEVEL_EMERGENCY: return Level.FATAL;
default:
return Level.WARN;
}
}
public void down(SyslogIF syslog, String reason) {
this.logger.log(this.downLevel,"Syslog protocol \"" + syslog.getProtocol() + "\" is down: " + reason);
}
this.logger = Logger.getLogger(loggerName);
public void up(SyslogIF syslog) {
this.logger.log(this.upLevel,"Syslog protocol \"" + syslog.getProtocol() + "\" is up");
}
initialize();
}
public void log(SyslogIF syslog, int level, String message, String reason) throws SyslogRuntimeException {
Level log4jLevel = getLog4jLevel(level);
String combinedMessage = combine(syslog,level,message,reason);
this.logger.log(log4jLevel,combinedMessage);
}
public Log4jSyslogBackLogHandler(String loggerName, boolean appendReason) {
if (loggerName == null) {
throw new SyslogRuntimeException("loggerName cannot be null");
}
this.logger = Logger.getLogger(loggerName);
this.appendReason = appendReason;
initialize();
}
public Log4jSyslogBackLogHandler(String loggerName, LoggerFactory loggerFactory) {
if (loggerName == null) {
throw new SyslogRuntimeException("loggerName cannot be null");
}
if (loggerFactory == null) {
throw new SyslogRuntimeException("loggerFactory cannot be null");
}
this.logger = Logger.getLogger(loggerName, loggerFactory);
initialize();
}
public Log4jSyslogBackLogHandler(String loggerName, LoggerFactory loggerFactory, boolean appendReason) {
if (loggerName == null) {
throw new SyslogRuntimeException("loggerName cannot be null");
}
if (loggerFactory == null) {
throw new SyslogRuntimeException("loggerFactory cannot be null");
}
this.logger = Logger.getLogger(loggerName, loggerFactory);
this.appendReason = appendReason;
initialize();
}
public void initialize() throws SyslogRuntimeException {
if (this.logger == null) {
throw new SyslogRuntimeException("logger cannot be null");
}
}
protected static Level getLog4jLevel(int level) {
switch (level) {
case SyslogConstants.LEVEL_DEBUG:
return Level.DEBUG;
case SyslogConstants.LEVEL_INFO:
return Level.INFO;
case SyslogConstants.LEVEL_NOTICE:
return Level.INFO;
case SyslogConstants.LEVEL_WARN:
return Level.WARN;
case SyslogConstants.LEVEL_ERROR:
return Level.ERROR;
case SyslogConstants.LEVEL_CRITICAL:
return Level.ERROR;
case SyslogConstants.LEVEL_ALERT:
return Level.ERROR;
case SyslogConstants.LEVEL_EMERGENCY:
return Level.FATAL;
default:
return Level.WARN;
}
}
public void down(SyslogIF syslog, String reason) {
this.logger.log(this.downLevel, "Syslog protocol \"" + syslog.getProtocol() + "\" is down: " + reason);
}
public void up(SyslogIF syslog) {
this.logger.log(this.upLevel, "Syslog protocol \"" + syslog.getProtocol() + "\" is up");
}
public void log(SyslogIF syslog, int level, String message, String reason) throws SyslogRuntimeException {
Level log4jLevel = getLog4jLevel(level);
String combinedMessage = combine(syslog, level, message, reason);
this.logger.log(log4jLevel, combinedMessage);
}
}

View File

@ -7,63 +7,63 @@ import org.graylog2.syslog4j.SyslogRuntimeException;
import org.graylog2.syslog4j.impl.backlog.AbstractSyslogBackLogHandler;
/**
* PrintStreamSyslogBackLogHandler provides a last-chance mechanism to log messages that fail
* (for whatever reason) within the rest of Syslog to a PrintStream.
*
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: PrintStreamSyslogBackLogHandler.java,v 1.1 2009/01/24 22:00:18 cvs Exp $
*/
* PrintStreamSyslogBackLogHandler provides a last-chance mechanism to log messages that fail
* (for whatever reason) within the rest of Syslog to a PrintStream.
* <p/>
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: PrintStreamSyslogBackLogHandler.java,v 1.1 2009/01/24 22:00:18 cvs Exp $
*/
public class PrintStreamSyslogBackLogHandler extends AbstractSyslogBackLogHandler {
protected PrintStream printStream = null;
protected boolean appendLinefeed = false;
public PrintStreamSyslogBackLogHandler(PrintStream printStream) {
this.printStream = printStream;
initialize();
}
protected PrintStream printStream = null;
protected boolean appendLinefeed = false;
public PrintStreamSyslogBackLogHandler(PrintStream printStream, boolean appendLinefeed) {
this.printStream = printStream;
this.appendLinefeed = appendLinefeed;
initialize();
}
public PrintStreamSyslogBackLogHandler(PrintStream printStream) {
this.printStream = printStream;
public PrintStreamSyslogBackLogHandler(PrintStream printStream, boolean appendLinefeed, boolean appendReason) {
this.printStream = printStream;
this.appendLinefeed = appendLinefeed;
this.appendReason = appendReason;
initialize();
}
initialize();
}
public void initialize() throws SyslogRuntimeException {
if (this.printStream == null) {
throw new SyslogRuntimeException("PrintStream cannot be null");
}
}
public PrintStreamSyslogBackLogHandler(PrintStream printStream, boolean appendLinefeed) {
this.printStream = printStream;
this.appendLinefeed = appendLinefeed;
public void down(SyslogIF syslog, String reason) {
this.printStream.println(syslog.getProtocol() + ": DOWN" + (reason != null && !"".equals(reason.trim()) ? " (" + reason + ")" : ""));
}
initialize();
}
public void up(SyslogIF syslog) {
this.printStream.println(syslog.getProtocol() + ": UP");
}
public PrintStreamSyslogBackLogHandler(PrintStream printStream, boolean appendLinefeed, boolean appendReason) {
this.printStream = printStream;
this.appendLinefeed = appendLinefeed;
this.appendReason = appendReason;
public void log(SyslogIF syslog, int level, String message, String reason) {
String combinedMessage = combine(syslog,level,message,reason);
if (this.appendLinefeed) {
this.printStream.println(combinedMessage);
} else {
this.printStream.print(combinedMessage);
}
}
initialize();
}
public void initialize() throws SyslogRuntimeException {
if (this.printStream == null) {
throw new SyslogRuntimeException("PrintStream cannot be null");
}
}
public void down(SyslogIF syslog, String reason) {
this.printStream.println(syslog.getProtocol() + ": DOWN" + (reason != null && !"".equals(reason.trim()) ? " (" + reason + ")" : ""));
}
public void up(SyslogIF syslog) {
this.printStream.println(syslog.getProtocol() + ": UP");
}
public void log(SyslogIF syslog, int level, String message, String reason) {
String combinedMessage = combine(syslog, level, message, reason);
if (this.appendLinefeed) {
this.printStream.println(combinedMessage);
} else {
this.printStream.print(combinedMessage);
}
}
}

View File

@ -3,25 +3,26 @@ package org.graylog2.syslog4j.impl.backlog.printstream;
import org.graylog2.syslog4j.SyslogBackLogHandlerIF;
/**
* SystemErrSyslogBackLogHandler provides a last-chance mechanism to log messages that fail
* (for whatever reason) within the rest of Syslog to System.err.
*
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: SystemErrSyslogBackLogHandler.java,v 1.2 2009/03/29 17:38:59 cvs Exp $
*/
* SystemErrSyslogBackLogHandler provides a last-chance mechanism to log messages that fail
* (for whatever reason) within the rest of Syslog to System.err.
* <p/>
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: SystemErrSyslogBackLogHandler.java,v 1.2 2009/03/29 17:38:59 cvs Exp $
*/
public class SystemErrSyslogBackLogHandler extends PrintStreamSyslogBackLogHandler {
public static final SyslogBackLogHandlerIF create() {
return new SystemErrSyslogBackLogHandler();
}
public SystemErrSyslogBackLogHandler() {
super(System.err,true);
}
public SystemErrSyslogBackLogHandler(boolean appendReason) {
super(System.err,true,appendReason);
}
public static final SyslogBackLogHandlerIF create() {
return new SystemErrSyslogBackLogHandler();
}
public SystemErrSyslogBackLogHandler() {
super(System.err, true);
}
public SystemErrSyslogBackLogHandler(boolean appendReason) {
super(System.err, true, appendReason);
}
}

View File

@ -3,25 +3,26 @@ package org.graylog2.syslog4j.impl.backlog.printstream;
import org.graylog2.syslog4j.SyslogBackLogHandlerIF;
/**
* SystemOutSyslogBackLogHandler provides a last-chance mechanism to log messages that fail
* (for whatever reason) within the rest of Syslog to System.out.
*
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: SystemOutSyslogBackLogHandler.java,v 1.2 2009/03/29 17:38:59 cvs Exp $
*/
* SystemOutSyslogBackLogHandler provides a last-chance mechanism to log messages that fail
* (for whatever reason) within the rest of Syslog to System.out.
* <p/>
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: SystemOutSyslogBackLogHandler.java,v 1.2 2009/03/29 17:38:59 cvs Exp $
*/
public class SystemOutSyslogBackLogHandler extends PrintStreamSyslogBackLogHandler {
public static final SyslogBackLogHandlerIF create() {
return new SystemOutSyslogBackLogHandler();
}
public SystemOutSyslogBackLogHandler() {
super(System.out,true);
}
public SystemOutSyslogBackLogHandler(boolean appendReason) {
super(System.out,true,appendReason);
}
public static final SyslogBackLogHandlerIF create() {
return new SystemOutSyslogBackLogHandler();
}
public SystemOutSyslogBackLogHandler() {
super(System.out, true);
}
public SystemOutSyslogBackLogHandler(boolean appendReason) {
super(System.out, true, appendReason);
}
}

View File

@ -4,76 +4,76 @@ import org.apache.log4j.helpers.LogLog;
/**
* Syslog4jAppender provides a Log4j Appender wrapper for Syslog4j.
*
* <p/>
* <p>Note: Syslog4jAppender does NOT extend Log4j's SyslogAppender.</p>
*
* <p/>
* <p>Example log4j.xml configuration:</p>
*
* <p/>
* <pre>
* <code>
&lt;appender name="Syslog4j" class="org.graylog2.syslog4j.impl.log4j.Syslog4jAppender"&gt;
&lt;param name="Facility" value="user"/&gt;
&lt;param name="Protocol" value="tcp"/&gt;
&lt;param name="Host" value="192.168.0.1"/&gt;
&lt;layout class="org.apache.log4j.PatternLayout"&gt;
&lt;param name="ConversionPattern" value="%d{ABSOLUTE} %-5p [%c{1}] %m"/&gt;
&lt;/layout&gt;
&lt;/appender&gt;
* &lt;appender name="Syslog4j" class="org.graylog2.syslog4j.impl.log4j.Syslog4jAppender"&gt;
* &lt;param name="Facility" value="user"/&gt;
* &lt;param name="Protocol" value="tcp"/&gt;
* &lt;param name="Host" value="192.168.0.1"/&gt;
* &lt;layout class="org.apache.log4j.PatternLayout"&gt;
* &lt;param name="ConversionPattern" value="%d{ABSOLUTE} %-5p [%c{1}] %m"/&gt;
* &lt;/layout&gt;
* &lt;/appender&gt;
* </code>
* </pre>
*
* <p/>
* <p>All available parameters are:</p>
*
* <p/>
* <ul>
* <li>ident</li>
* <li>localName</li>
* <li>protocol</li>
* <li>facility</li>
* <li>host</li>
* <li>port</li>
* <li>charSet</li>
* <li>threaded</li>
* <li>threadLoopInterval</li>
* <li>splitMessageBeginText</li>
* <li>splitMessageEndText</li>
* <li>maxMessageLength</li>
* <li>maxShutdownWait</li>
* <li>writeRetries</li>
* <li>truncateMessage</li>
* <li>useStructuredData</li>
* <li>ident</li>
* <li>localName</li>
* <li>protocol</li>
* <li>facility</li>
* <li>host</li>
* <li>port</li>
* <li>charSet</li>
* <li>threaded</li>
* <li>threadLoopInterval</li>
* <li>splitMessageBeginText</li>
* <li>splitMessageEndText</li>
* <li>maxMessageLength</li>
* <li>maxShutdownWait</li>
* <li>writeRetries</li>
* <li>truncateMessage</li>
* <li>useStructuredData</li>
* </ul>
*
* <p/>
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: Syslog4jAppender.java,v 1.2 2011/01/23 20:49:12 cvs Exp $
*/
public class Syslog4jAppender extends Syslog4jAppenderSkeleton {
private static final long serialVersionUID = -6072552977605816670L;
public String initialize() {
if (this.protocol == null) {
this.protocol = UDP;
}
return this.protocol;
}
private static final long serialVersionUID = -6072552977605816670L;
public boolean getHeader() {
return false;
}
public void setHeader(boolean header) {
LogLog.warn("Syslog4jAppender ignores the \"Header\" parameter.");
}
public String initialize() {
if (this.protocol == null) {
this.protocol = UDP;
}
public String getSyslogHost() {
return this.host;
}
return this.protocol;
}
public void setSyslogHost(String host) {
this.host = host;
}
public boolean getHeader() {
return false;
}
public void setHeader(boolean header) {
LogLog.warn("Syslog4jAppender ignores the \"Header\" parameter.");
}
public String getSyslogHost() {
return this.host;
}
public void setSyslogHost(String host) {
this.host = host;
}
}

View File

@ -12,320 +12,320 @@ import org.graylog2.syslog4j.util.SyslogUtility;
/**
* Syslog4jAppenderSkeleton provides an extensible Log4j Appender wrapper for Syslog4j.
*
* <p/>
* <p>Classes which inherit Syslog4jAppenderSkeleton must implement the "initialize()" method,
* which sets up Syslog4j for use by the Log4j Appender.</p>
*
* <p/>
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: Syslog4jAppenderSkeleton.java,v 1.8 2011/01/23 20:49:12 cvs Exp $
*/
public abstract class Syslog4jAppenderSkeleton extends AppenderSkeleton implements SyslogConstants {
private static final long serialVersionUID = 5520555788232095628L;
private static final long serialVersionUID = 5520555788232095628L;
protected SyslogIF syslog = null;
protected String ident = null;
protected String localName = null;
protected String protocol = null;
protected String facility = null;
protected String host = null;
protected String port = null;
protected String charSet = null;
protected String threaded = null;
protected String threadLoopInterval = null;
protected String splitMessageBeginText = null;
protected String splitMessageEndText = null;
protected String maxMessageLength = null;
protected String maxShutdownWait = null;
protected String writeRetries = null;
protected String truncateMessage = null;
protected String useStructuredData = null;
protected boolean initialized = false;
public abstract String initialize() throws SyslogRuntimeException;
protected static boolean isTrueOrOn(String value) {
boolean trueOrOn = false;
if (value != null) {
if ("true".equalsIgnoreCase(value.trim()) || "on".equalsIgnoreCase(value.trim())) {
trueOrOn = true;
} else if ("false".equalsIgnoreCase(value.trim()) || "off".equalsIgnoreCase(value.trim())) {
trueOrOn = false;
} else {
LogLog.error("Value \"" + value + "\" not true, on, false, or off -- assuming false");
}
}
return trueOrOn;
}
protected void _initialize() {
String initializedProtocol = initialize();
if (initializedProtocol != null && this.protocol == null) {
this.protocol = initializedProtocol;
}
if (this.protocol != null) {
try {
this.syslog = Syslog.getInstance(this.protocol);
if (this.host != null) {
this.syslog.getConfig().setHost(this.host);
}
if (this.facility != null) {
this.syslog.getConfig().setFacility(SyslogUtility.getFacility(this.facility));
}
if (this.port != null) {
try {
int i = Integer.parseInt(this.port);
this.syslog.getConfig().setPort(i);
} catch (NumberFormatException nfe) {
LogLog.error(nfe.toString());
}
}
if (this.charSet != null) {
this.syslog.getConfig().setCharSet(this.charSet);
}
if (this.ident != null) {
this.syslog.getConfig().setIdent(this.ident);
}
if (this.localName != null) {
this.syslog.getConfig().setLocalName(this.localName);
}
if (this.truncateMessage != null && !"".equals(this.truncateMessage.trim())) {
this.syslog.getConfig().setTruncateMessage(isTrueOrOn(this.truncateMessage));
}
if (this.maxMessageLength != null && this.maxMessageLength.length() > 0) {
try {
int i = Integer.parseInt(this.maxMessageLength.trim());
this.syslog.getConfig().setMaxMessageLength(i);
} catch (NumberFormatException nfe) {
LogLog.error(nfe.toString());
}
}
if (this.useStructuredData != null) {
this.syslog.getConfig().setUseStructuredData(isTrueOrOn(this.useStructuredData));
}
if (this.syslog.getConfig() instanceof AbstractSyslogConfigIF) {
AbstractSyslogConfigIF abstractSyslogConfig = (AbstractSyslogConfigIF) this.syslog.getConfig();
if (this.threaded != null && !"".equals(this.threaded.trim())) {
abstractSyslogConfig.setThreaded(isTrueOrOn(this.threaded));
}
protected SyslogIF syslog = null;
if (this.threadLoopInterval != null && this.threadLoopInterval.length() > 0) {
try {
long l = Long.parseLong(this.threadLoopInterval.trim());
abstractSyslogConfig.setThreadLoopInterval(l);
} catch (NumberFormatException nfe) {
LogLog.error(nfe.toString());
}
}
if (this.splitMessageBeginText != null) {
abstractSyslogConfig.setSplitMessageBeginText(SyslogUtility.getBytes(abstractSyslogConfig,this.splitMessageBeginText));
}
protected String ident = null;
protected String localName = null;
protected String protocol = null;
protected String facility = null;
protected String host = null;
protected String port = null;
protected String charSet = null;
protected String threaded = null;
protected String threadLoopInterval = null;
protected String splitMessageBeginText = null;
protected String splitMessageEndText = null;
protected String maxMessageLength = null;
protected String maxShutdownWait = null;
protected String writeRetries = null;
protected String truncateMessage = null;
protected String useStructuredData = null;
if (this.splitMessageEndText != null) {
abstractSyslogConfig.setSplitMessageEndText(SyslogUtility.getBytes(abstractSyslogConfig,this.splitMessageEndText));
}
if (this.maxShutdownWait != null && this.maxShutdownWait.length() > 0) {
try {
int i = Integer.parseInt(this.maxShutdownWait.trim());
abstractSyslogConfig.setMaxShutdownWait(i);
} catch (NumberFormatException nfe) {
LogLog.error(nfe.toString());
}
}
if (this.writeRetries != null && this.writeRetries.length() > 0) {
try {
int i = Integer.parseInt(this.writeRetries.trim());
abstractSyslogConfig.setWriteRetries(i);
} catch (NumberFormatException nfe) {
LogLog.error(nfe.toString());
}
}
}
this.initialized = true;
} catch (SyslogRuntimeException sre) {
LogLog.error(sre.toString());
}
}
}
public String getProtocol() {
return this.protocol;
}
protected boolean initialized = false;
public void setProtocol(String protocol) {
this.protocol = protocol;
}
public abstract String initialize() throws SyslogRuntimeException;
protected void append(LoggingEvent event) {
if (!this.initialized) {
_initialize();
}
if (this.initialized) {
int level = event.getLevel().getSyslogEquivalent();
if (this.layout != null) {
String message = this.layout.format(event);
this.syslog.log(level,message);
} else {
String message = event.getRenderedMessage();
this.syslog.log(level,message);
}
}
}
protected static boolean isTrueOrOn(String value) {
boolean trueOrOn = false;
public void close() {
if (this.syslog != null) {
this.syslog.flush();
}
}
if (value != null) {
if ("true".equalsIgnoreCase(value.trim()) || "on".equalsIgnoreCase(value.trim())) {
trueOrOn = true;
public String getFacility() {
return this.facility;
}
} else if ("false".equalsIgnoreCase(value.trim()) || "off".equalsIgnoreCase(value.trim())) {
trueOrOn = false;
public void setFacility(String facility) {
this.facility = facility;
}
} else {
LogLog.error("Value \"" + value + "\" not true, on, false, or off -- assuming false");
}
}
public String getHost() {
return this.host;
}
return trueOrOn;
}
public void setHost(String host) {
this.host = host;
}
protected void _initialize() {
String initializedProtocol = initialize();
public String getLocalName() {
return localName;
}
if (initializedProtocol != null && this.protocol == null) {
this.protocol = initializedProtocol;
}
public void setLocalName(String localName) {
this.localName = localName;
}
if (this.protocol != null) {
try {
this.syslog = Syslog.getInstance(this.protocol);
if (this.host != null) {
this.syslog.getConfig().setHost(this.host);
}
if (this.facility != null) {
this.syslog.getConfig().setFacility(SyslogUtility.getFacility(this.facility));
}
if (this.port != null) {
try {
int i = Integer.parseInt(this.port);
this.syslog.getConfig().setPort(i);
public String getPort() {
return this.port;
}
} catch (NumberFormatException nfe) {
LogLog.error(nfe.toString());
}
}
if (this.charSet != null) {
this.syslog.getConfig().setCharSet(this.charSet);
}
if (this.ident != null) {
this.syslog.getConfig().setIdent(this.ident);
}
if (this.localName != null) {
this.syslog.getConfig().setLocalName(this.localName);
}
if (this.truncateMessage != null && !"".equals(this.truncateMessage.trim())) {
this.syslog.getConfig().setTruncateMessage(isTrueOrOn(this.truncateMessage));
}
if (this.maxMessageLength != null && this.maxMessageLength.length() > 0) {
try {
int i = Integer.parseInt(this.maxMessageLength.trim());
this.syslog.getConfig().setMaxMessageLength(i);
public void setPort(String port) {
this.port = port;
}
public String getCharSet() {
return this.charSet;
}
} catch (NumberFormatException nfe) {
LogLog.error(nfe.toString());
}
}
if (this.useStructuredData != null) {
this.syslog.getConfig().setUseStructuredData(isTrueOrOn(this.useStructuredData));
}
if (this.syslog.getConfig() instanceof AbstractSyslogConfigIF) {
AbstractSyslogConfigIF abstractSyslogConfig = (AbstractSyslogConfigIF) this.syslog.getConfig();
public void setCharSet(String charSet) {
this.charSet = charSet;
}
if (this.threaded != null && !"".equals(this.threaded.trim())) {
abstractSyslogConfig.setThreaded(isTrueOrOn(this.threaded));
}
public String getIdent() {
return this.ident;
}
if (this.threadLoopInterval != null && this.threadLoopInterval.length() > 0) {
try {
long l = Long.parseLong(this.threadLoopInterval.trim());
abstractSyslogConfig.setThreadLoopInterval(l);
public void setIdent(String ident) {
this.ident = ident;
}
} catch (NumberFormatException nfe) {
LogLog.error(nfe.toString());
}
}
public String getThreaded() {
return this.threaded;
}
if (this.splitMessageBeginText != null) {
abstractSyslogConfig.setSplitMessageBeginText(SyslogUtility.getBytes(abstractSyslogConfig, this.splitMessageBeginText));
}
public void setThreaded(String threaded) {
this.threaded = threaded;
}
if (this.splitMessageEndText != null) {
abstractSyslogConfig.setSplitMessageEndText(SyslogUtility.getBytes(abstractSyslogConfig, this.splitMessageEndText));
}
public boolean requiresLayout() {
return false;
}
if (this.maxShutdownWait != null && this.maxShutdownWait.length() > 0) {
try {
int i = Integer.parseInt(this.maxShutdownWait.trim());
abstractSyslogConfig.setMaxShutdownWait(i);
public String getThreadLoopInterval() {
return this.threadLoopInterval;
}
} catch (NumberFormatException nfe) {
LogLog.error(nfe.toString());
}
}
public void setThreadLoopInterval(String threadLoopInterval) {
this.threadLoopInterval = threadLoopInterval;
}
if (this.writeRetries != null && this.writeRetries.length() > 0) {
try {
int i = Integer.parseInt(this.writeRetries.trim());
abstractSyslogConfig.setWriteRetries(i);
public String getSplitMessageBeginText() {
return this.splitMessageBeginText;
}
} catch (NumberFormatException nfe) {
LogLog.error(nfe.toString());
}
}
}
public void setSplitMessageBeginText(String splitMessageBeginText) {
this.splitMessageBeginText = splitMessageBeginText;
}
this.initialized = true;
public String getSplitMessageEndText() {
return this.splitMessageEndText;
}
} catch (SyslogRuntimeException sre) {
LogLog.error(sre.toString());
}
}
}
public void setSplitMessageEndText(String splitMessageEndText) {
this.splitMessageEndText = splitMessageEndText;
}
public String getProtocol() {
return this.protocol;
}
public String getMaxMessageLength() {
return this.maxMessageLength;
}
public void setProtocol(String protocol) {
this.protocol = protocol;
}
public void setMaxMessageLength(String maxMessageLength) {
this.maxMessageLength = maxMessageLength;
}
protected void append(LoggingEvent event) {
if (!this.initialized) {
_initialize();
}
public String getMaxShutdownWait() {
return this.maxShutdownWait;
}
if (this.initialized) {
int level = event.getLevel().getSyslogEquivalent();
public void setMaxShutdownWait(String maxShutdownWait) {
this.maxShutdownWait = maxShutdownWait;
}
if (this.layout != null) {
String message = this.layout.format(event);
public String getWriteRetries() {
return this.writeRetries;
}
this.syslog.log(level, message);
public void setWriteRetries(String writeRetries) {
this.writeRetries = writeRetries;
}
} else {
String message = event.getRenderedMessage();
public String getTruncateMessage() {
return this.truncateMessage;
}
this.syslog.log(level, message);
}
}
}
public void setTruncateMessage(String truncateMessage) {
this.truncateMessage = truncateMessage;
}
public void close() {
if (this.syslog != null) {
this.syslog.flush();
}
}
public String getUseStructuredData() {
return useStructuredData;
}
public String getFacility() {
return this.facility;
}
public void setUseStructuredData(String useStructuredData) {
this.useStructuredData = useStructuredData;
}
public void setFacility(String facility) {
this.facility = facility;
}
public String getHost() {
return this.host;
}
public void setHost(String host) {
this.host = host;
}
public String getLocalName() {
return localName;
}
public void setLocalName(String localName) {
this.localName = localName;
}
public String getPort() {
return this.port;
}
public void setPort(String port) {
this.port = port;
}
public String getCharSet() {
return this.charSet;
}
public void setCharSet(String charSet) {
this.charSet = charSet;
}
public String getIdent() {
return this.ident;
}
public void setIdent(String ident) {
this.ident = ident;
}
public String getThreaded() {
return this.threaded;
}
public void setThreaded(String threaded) {
this.threaded = threaded;
}
public boolean requiresLayout() {
return false;
}
public String getThreadLoopInterval() {
return this.threadLoopInterval;
}
public void setThreadLoopInterval(String threadLoopInterval) {
this.threadLoopInterval = threadLoopInterval;
}
public String getSplitMessageBeginText() {
return this.splitMessageBeginText;
}
public void setSplitMessageBeginText(String splitMessageBeginText) {
this.splitMessageBeginText = splitMessageBeginText;
}
public String getSplitMessageEndText() {
return this.splitMessageEndText;
}
public void setSplitMessageEndText(String splitMessageEndText) {
this.splitMessageEndText = splitMessageEndText;
}
public String getMaxMessageLength() {
return this.maxMessageLength;
}
public void setMaxMessageLength(String maxMessageLength) {
this.maxMessageLength = maxMessageLength;
}
public String getMaxShutdownWait() {
return this.maxShutdownWait;
}
public void setMaxShutdownWait(String maxShutdownWait) {
this.maxShutdownWait = maxShutdownWait;
}
public String getWriteRetries() {
return this.writeRetries;
}
public void setWriteRetries(String writeRetries) {
this.writeRetries = writeRetries;
}
public String getTruncateMessage() {
return this.truncateMessage;
}
public void setTruncateMessage(String truncateMessage) {
this.truncateMessage = truncateMessage;
}
public String getUseStructuredData() {
return useStructuredData;
}
public void setUseStructuredData(String useStructuredData) {
this.useStructuredData = useStructuredData;
}
}

View File

@ -8,94 +8,94 @@ import java.util.Date;
import org.graylog2.syslog4j.SyslogMessageIF;
/**
* AbstractSyslogMessage provides support for turning POJO (Plain Ol'
* Java Objects) into Syslog messages.
*
* <p>More information on the PCI DSS specification is available here:</p>
*
* <p>https://www.pcisecuritystandards.org/security_standards/pci_dss.shtml</p>
*
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: AbstractSyslogMessage.java,v 1.2 2009/04/17 02:37:04 cvs Exp $
*/
* AbstractSyslogMessage provides support for turning POJO (Plain Ol'
* Java Objects) into Syslog messages.
* <p/>
* <p>More information on the PCI DSS specification is available here:</p>
* <p/>
* <p>https://www.pcisecuritystandards.org/security_standards/pci_dss.shtml</p>
* <p/>
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: AbstractSyslogMessage.java,v 1.2 2009/04/17 02:37:04 cvs Exp $
*/
public abstract class AbstractSyslogMessage implements SyslogMessageIF {
private static final long serialVersionUID = 414124277626756491L;
private static final long serialVersionUID = 414124277626756491L;
public static final String UNDEFINED = "undefined";
public static final String DEFAULT_DATE_FORMAT = "yyyy/MM/dd";
public static final String DEFAULT_TIME_FORMAT = "HH:mm:ss";
public static final String UNDEFINED = "undefined";
public static final char DEFAULT_DELIMITER = ' ';
public static final String DEFAULT_REPLACE_DELIMITER = "_";
protected char getDelimiter() {
return DEFAULT_DELIMITER;
}
public static final String DEFAULT_DATE_FORMAT = "yyyy/MM/dd";
public static final String DEFAULT_TIME_FORMAT = "HH:mm:ss";
protected String getReplaceDelimiter() {
return DEFAULT_REPLACE_DELIMITER;
}
public static final char DEFAULT_DELIMITER = ' ';
public static final String DEFAULT_REPLACE_DELIMITER = "_";
protected String getDateFormat() {
return DEFAULT_DATE_FORMAT;
}
protected char getDelimiter() {
return DEFAULT_DELIMITER;
}
protected String getTimeFormat() {
return DEFAULT_TIME_FORMAT;
}
protected String generateDate() {
String date = new SimpleDateFormat(getDateFormat()).format(new Date());
return date;
}
protected String getReplaceDelimiter() {
return DEFAULT_REPLACE_DELIMITER;
}
protected String generateTime() {
String time = new SimpleDateFormat(getTimeFormat()).format(new Date());
return time;
}
protected String getDateFormat() {
return DEFAULT_DATE_FORMAT;
}
protected String[] generateDateAndTime(Date date) {
String[] dateAndTime = new String[2];
dateAndTime[0] = new SimpleDateFormat(getDateFormat()).format(date);
dateAndTime[1] = new SimpleDateFormat(getTimeFormat()).format(date);
return dateAndTime;
}
protected String getTimeFormat() {
return DEFAULT_TIME_FORMAT;
}
protected String generateLocalHostName() {
String localHostName = UNDEFINED;
protected String generateDate() {
String date = new SimpleDateFormat(getDateFormat()).format(new Date());
try {
localHostName = InetAddress.getLocalHost().getHostName();
} catch (UnknownHostException uhe) {
//
}
return localHostName;
}
return date;
}
protected boolean nullOrEmpty(String value) {
return (value == null || "".equals(value.trim()));
}
protected String generateTime() {
String time = new SimpleDateFormat(getTimeFormat()).format(new Date());
protected String replaceDelimiter(String fieldName, String fieldValue, char delimiter, String replaceDelimiter) {
if (replaceDelimiter == null || replaceDelimiter.length() < 1 || fieldValue == null || fieldValue.length() < 1) {
return fieldValue;
}
String newFieldValue = fieldValue.replaceAll("\\" + delimiter, replaceDelimiter);
return newFieldValue;
}
return time;
}
public abstract String createMessage();
protected String[] generateDateAndTime(Date date) {
String[] dateAndTime = new String[2];
dateAndTime[0] = new SimpleDateFormat(getDateFormat()).format(date);
dateAndTime[1] = new SimpleDateFormat(getTimeFormat()).format(date);
return dateAndTime;
}
protected String generateLocalHostName() {
String localHostName = UNDEFINED;
try {
localHostName = InetAddress.getLocalHost().getHostName();
} catch (UnknownHostException uhe) {
//
}
return localHostName;
}
protected boolean nullOrEmpty(String value) {
return (value == null || "".equals(value.trim()));
}
protected String replaceDelimiter(String fieldName, String fieldValue, char delimiter, String replaceDelimiter) {
if (replaceDelimiter == null || replaceDelimiter.length() < 1 || fieldValue == null || fieldValue.length() < 1) {
return fieldValue;
}
String newFieldValue = fieldValue.replaceAll("\\" + delimiter, replaceDelimiter);
return newFieldValue;
}
public abstract String createMessage();
}

View File

@ -4,60 +4,60 @@ import org.graylog2.syslog4j.SyslogMessageModifierConfigIF;
import org.graylog2.syslog4j.SyslogMessageModifierIF;
public abstract class AbstractSyslogMessageModifier implements SyslogMessageModifierIF {
private static final long serialVersionUID = 7632959170109372003L;
protected SyslogMessageModifierConfigIF messageModifierConfig = null;
public AbstractSyslogMessageModifier(SyslogMessageModifierConfigIF messageModifierConfig) {
this.messageModifierConfig = messageModifierConfig;
}
private static final long serialVersionUID = 7632959170109372003L;
public String[] parseInlineModifier(String message) {
return parseInlineModifier(message,this.messageModifierConfig.getPrefix(),this.messageModifierConfig.getSuffix());
}
public static String[] parseInlineModifier(String message, String prefix, String suffix) {
String[] messageAndModifier = null;
if (message == null || "".equals(message.trim())) {
return null;
}
if (prefix == null || "".equals(prefix)) {
prefix = " ";
}
if (suffix == null || "".equals(suffix)) {
int pi = message.lastIndexOf(prefix);
if (pi > -1) {
messageAndModifier = new String[] { message.substring(0,pi), message.substring(pi+prefix.length()) };
}
} else {
int si = message.lastIndexOf(suffix);
if (si > -1) {
int pi = message.lastIndexOf(prefix,si);
if (pi > -1) {
messageAndModifier = new String[] { message.substring(0,pi), message.substring(pi+prefix.length(),si) };
}
}
}
return messageAndModifier;
}
protected abstract boolean verify(String message, String modifier);
public boolean verify(String message) {
String[] messageAndModifier = parseInlineModifier(message);
if (messageAndModifier == null || messageAndModifier.length != 2) {
return false;
}
return verify(messageAndModifier[0],messageAndModifier[1]);
}
protected SyslogMessageModifierConfigIF messageModifierConfig = null;
public AbstractSyslogMessageModifier(SyslogMessageModifierConfigIF messageModifierConfig) {
this.messageModifierConfig = messageModifierConfig;
}
public String[] parseInlineModifier(String message) {
return parseInlineModifier(message, this.messageModifierConfig.getPrefix(), this.messageModifierConfig.getSuffix());
}
public static String[] parseInlineModifier(String message, String prefix, String suffix) {
String[] messageAndModifier = null;
if (message == null || "".equals(message.trim())) {
return null;
}
if (prefix == null || "".equals(prefix)) {
prefix = " ";
}
if (suffix == null || "".equals(suffix)) {
int pi = message.lastIndexOf(prefix);
if (pi > -1) {
messageAndModifier = new String[]{message.substring(0, pi), message.substring(pi + prefix.length())};
}
} else {
int si = message.lastIndexOf(suffix);
if (si > -1) {
int pi = message.lastIndexOf(prefix, si);
if (pi > -1) {
messageAndModifier = new String[]{message.substring(0, pi), message.substring(pi + prefix.length(), si)};
}
}
}
return messageAndModifier;
}
protected abstract boolean verify(String message, String modifier);
public boolean verify(String message) {
String[] messageAndModifier = parseInlineModifier(message);
if (messageAndModifier == null || messageAndModifier.length != 2) {
return false;
}
return verify(messageAndModifier[0], messageAndModifier[1]);
}
}

View File

@ -5,54 +5,54 @@ import org.graylog2.syslog4j.SyslogConstants;
import org.graylog2.syslog4j.SyslogMessageModifierConfigIF;
/**
* AbstractSyslogMessageModifierConfig provides a base abstract implementation of the
* SyslogMessageModifierConfigIF.
*
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: AbstractSyslogMessageModifierConfig.java,v 1.4 2010/10/28 05:10:57 cvs Exp $
*/
* AbstractSyslogMessageModifierConfig provides a base abstract implementation of the
* SyslogMessageModifierConfigIF.
* <p/>
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: AbstractSyslogMessageModifierConfig.java,v 1.4 2010/10/28 05:10:57 cvs Exp $
*/
public abstract class AbstractSyslogMessageModifierConfig implements SyslogMessageModifierConfigIF, SyslogCharSetIF {
private static final long serialVersionUID = 5036574188079124884L;
protected String prefix = SYSLOG_MESSAGE_MODIFIER_PREFIX_DEFAULT;
protected String suffix = SYSLOG_MESSAGE_MODIFIER_SUFFIX_DEFAULT;
protected String charSet = SyslogConstants.CHAR_SET_DEFAULT;
public String getPrefix() {
return this.prefix;
}
private static final long serialVersionUID = 5036574188079124884L;
public String getSuffix() {
return this.suffix;
}
protected String prefix = SYSLOG_MESSAGE_MODIFIER_PREFIX_DEFAULT;
protected String suffix = SYSLOG_MESSAGE_MODIFIER_SUFFIX_DEFAULT;
protected String charSet = SyslogConstants.CHAR_SET_DEFAULT;
public void setPrefix(String prefix) {
if (prefix == null) {
this.prefix = "";
} else {
this.prefix = prefix;
}
}
public String getPrefix() {
return this.prefix;
}
public void setSuffix(String suffix) {
if (suffix == null) {
this.suffix = "";
} else {
this.suffix = suffix;
}
}
public String getSuffix() {
return this.suffix;
}
public String getCharSet() {
return charSet;
}
public void setPrefix(String prefix) {
if (prefix == null) {
this.prefix = "";
public void setCharSet(String charSet) {
this.charSet = charSet;
}
} else {
this.prefix = prefix;
}
}
public void setSuffix(String suffix) {
if (suffix == null) {
this.suffix = "";
} else {
this.suffix = suffix;
}
}
public String getCharSet() {
return charSet;
}
public void setCharSet(String charSet) {
this.charSet = charSet;
}
}

View File

@ -6,96 +6,97 @@ import org.graylog2.syslog4j.impl.message.modifier.AbstractSyslogMessageModifier
import org.graylog2.syslog4j.util.SyslogUtility;
/**
* ChecksumSyslogMessageModifier is an implementation of SyslogMessageModifierIF
* that provides support for Java Checksum algorithms (java.util.zip.Checksum).
*
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: ChecksumSyslogMessageModifier.java,v 1.5 2010/10/28 05:10:57 cvs Exp $
*/
* ChecksumSyslogMessageModifier is an implementation of SyslogMessageModifierIF
* that provides support for Java Checksum algorithms (java.util.zip.Checksum).
* <p/>
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: ChecksumSyslogMessageModifier.java,v 1.5 2010/10/28 05:10:57 cvs Exp $
*/
public class ChecksumSyslogMessageModifier extends AbstractSyslogMessageModifier {
private static final long serialVersionUID = -3268914290497005065L;
protected ChecksumSyslogMessageModifierConfig config = null;
public static final ChecksumSyslogMessageModifier createCRC32() {
ChecksumSyslogMessageModifier crc32 = new ChecksumSyslogMessageModifier(ChecksumSyslogMessageModifierConfig.createCRC32());
return crc32;
}
public static final ChecksumSyslogMessageModifier createADLER32() {
ChecksumSyslogMessageModifier adler32 = new ChecksumSyslogMessageModifier(ChecksumSyslogMessageModifierConfig.createADLER32());
return adler32;
}
public ChecksumSyslogMessageModifier(ChecksumSyslogMessageModifierConfig config) {
super(config);
this.config = config;
if (this.config == null) {
throw new SyslogRuntimeException("Checksum config object cannot be null");
}
if (this.config.getChecksum() == null) {
throw new SyslogRuntimeException("Checksum object cannot be null");
}
}
public ChecksumSyslogMessageModifierConfig getConfig() {
return this.config;
}
protected void continuousCheckForVerify() {
if (this.config.isContinuous()) {
throw new SyslogRuntimeException(this.getClass().getName() + ".verify(..) does not work with isContinuous() returning true");
}
}
public boolean verify(String message, String hexChecksum) {
continuousCheckForVerify();
private static final long serialVersionUID = -3268914290497005065L;
long checksum = Long.parseLong(hexChecksum,16);
return verify(message,checksum);
}
public boolean verify(String message, long checksum) {
continuousCheckForVerify();
synchronized(this.config.getChecksum()) {
this.config.getChecksum().reset();
byte[] messageBytes = SyslogUtility.getBytes(this.config,message);
this.config.getChecksum().update(messageBytes,0,message.length());
return this.config.getChecksum().getValue() == checksum;
}
}
protected ChecksumSyslogMessageModifierConfig config = null;
public String modify(SyslogIF syslog, int facility, int level, String message) {
synchronized(this.config.getChecksum()) {
StringBuffer messageBuffer = new StringBuffer(message);
byte[] messageBytes = SyslogUtility.getBytes(syslog.getConfig(),message);
if (!this.config.isContinuous()) {
this.config.getChecksum().reset();
}
this.config.getChecksum().update(messageBytes,0,message.length());
messageBuffer.append(this.config.getPrefix());
messageBuffer.append(Long.toHexString(this.config.getChecksum().getValue()).toUpperCase());
messageBuffer.append(this.config.getSuffix());
return messageBuffer.toString();
}
}
public static final ChecksumSyslogMessageModifier createCRC32() {
ChecksumSyslogMessageModifier crc32 = new ChecksumSyslogMessageModifier(ChecksumSyslogMessageModifierConfig.createCRC32());
return crc32;
}
public static final ChecksumSyslogMessageModifier createADLER32() {
ChecksumSyslogMessageModifier adler32 = new ChecksumSyslogMessageModifier(ChecksumSyslogMessageModifierConfig.createADLER32());
return adler32;
}
public ChecksumSyslogMessageModifier(ChecksumSyslogMessageModifierConfig config) {
super(config);
this.config = config;
if (this.config == null) {
throw new SyslogRuntimeException("Checksum config object cannot be null");
}
if (this.config.getChecksum() == null) {
throw new SyslogRuntimeException("Checksum object cannot be null");
}
}
public ChecksumSyslogMessageModifierConfig getConfig() {
return this.config;
}
protected void continuousCheckForVerify() {
if (this.config.isContinuous()) {
throw new SyslogRuntimeException(this.getClass().getName() + ".verify(..) does not work with isContinuous() returning true");
}
}
public boolean verify(String message, String hexChecksum) {
continuousCheckForVerify();
long checksum = Long.parseLong(hexChecksum, 16);
return verify(message, checksum);
}
public boolean verify(String message, long checksum) {
continuousCheckForVerify();
synchronized (this.config.getChecksum()) {
this.config.getChecksum().reset();
byte[] messageBytes = SyslogUtility.getBytes(this.config, message);
this.config.getChecksum().update(messageBytes, 0, message.length());
return this.config.getChecksum().getValue() == checksum;
}
}
public String modify(SyslogIF syslog, int facility, int level, String message) {
synchronized (this.config.getChecksum()) {
StringBuffer messageBuffer = new StringBuffer(message);
byte[] messageBytes = SyslogUtility.getBytes(syslog.getConfig(), message);
if (!this.config.isContinuous()) {
this.config.getChecksum().reset();
}
this.config.getChecksum().update(messageBytes, 0, message.length());
messageBuffer.append(this.config.getPrefix());
messageBuffer.append(Long.toHexString(this.config.getChecksum().getValue()).toUpperCase());
messageBuffer.append(this.config.getSuffix());
return messageBuffer.toString();
}
}
}

View File

@ -7,51 +7,51 @@ import java.util.zip.Checksum;
import org.graylog2.syslog4j.impl.message.modifier.AbstractSyslogMessageModifierConfig;
/**
* ChecksumSyslogMessageModifierConfig is an implementation of AbstractSyslogMessageModifierConfig
* that provides configuration for ChecksumSyslogMessageModifier.
*
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: ChecksumSyslogMessageModifierConfig.java,v 1.2 2010/02/04 03:41:38 cvs Exp $
*/
* ChecksumSyslogMessageModifierConfig is an implementation of AbstractSyslogMessageModifierConfig
* that provides configuration for ChecksumSyslogMessageModifier.
* <p/>
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: ChecksumSyslogMessageModifierConfig.java,v 1.2 2010/02/04 03:41:38 cvs Exp $
*/
public class ChecksumSyslogMessageModifierConfig extends AbstractSyslogMessageModifierConfig {
private static final long serialVersionUID = -8298600135683882489L;
private static final long serialVersionUID = -8298600135683882489L;
protected Checksum checksum = null;
protected boolean continuous = false;
public static final ChecksumSyslogMessageModifierConfig createCRC32() {
ChecksumSyslogMessageModifierConfig crc32 = new ChecksumSyslogMessageModifierConfig(new CRC32());
return crc32;
}
public static final ChecksumSyslogMessageModifierConfig createADLER32() {
ChecksumSyslogMessageModifierConfig adler32 = new ChecksumSyslogMessageModifierConfig(new Adler32());
return adler32;
}
public ChecksumSyslogMessageModifierConfig(Checksum checksum) {
this.checksum = checksum;
}
protected Checksum checksum = null;
protected boolean continuous = false;
public Checksum getChecksum() {
return this.checksum;
}
public static final ChecksumSyslogMessageModifierConfig createCRC32() {
ChecksumSyslogMessageModifierConfig crc32 = new ChecksumSyslogMessageModifierConfig(new CRC32());
public void setChecksum(Checksum checksum) {
this.checksum = checksum;
}
return crc32;
}
public boolean isContinuous() {
return continuous;
}
public static final ChecksumSyslogMessageModifierConfig createADLER32() {
ChecksumSyslogMessageModifierConfig adler32 = new ChecksumSyslogMessageModifierConfig(new Adler32());
public void setContinuous(boolean continuous) {
this.continuous = continuous;
}
return adler32;
}
public ChecksumSyslogMessageModifierConfig(Checksum checksum) {
this.checksum = checksum;
}
public Checksum getChecksum() {
return this.checksum;
}
public void setChecksum(Checksum checksum) {
this.checksum = checksum;
}
public boolean isContinuous() {
return continuous;
}
public void setContinuous(boolean continuous) {
this.continuous = continuous;
}
}

View File

@ -4,77 +4,77 @@ import org.graylog2.syslog4j.SyslogIF;
import org.graylog2.syslog4j.SyslogMessageModifierIF;
/**
* HTMLEntityEscapeSyslogMessageModifier is an implementation of SyslogMessageModifierIF
* that safely escapes HTML entity characters.
*
* <p>This modifier is useful for applications that display log content in browsers without
* properly escaping HTML characters.</p>
*
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: HTMLEntityEscapeSyslogMessageModifier.java,v 1.4 2010/10/28 05:10:57 cvs Exp $
*/
* HTMLEntityEscapeSyslogMessageModifier is an implementation of SyslogMessageModifierIF
* that safely escapes HTML entity characters.
* <p/>
* <p>This modifier is useful for applications that display log content in browsers without
* properly escaping HTML characters.</p>
* <p/>
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: HTMLEntityEscapeSyslogMessageModifier.java,v 1.4 2010/10/28 05:10:57 cvs Exp $
*/
public class HTMLEntityEscapeSyslogMessageModifier implements SyslogMessageModifierIF {
private static final long serialVersionUID = -8481773209240762293L;
private static final long serialVersionUID = -8481773209240762293L;
public static final SyslogMessageModifierIF createDefault() {
return new HTMLEntityEscapeSyslogMessageModifier();
}
public static final SyslogMessageModifierIF createDefault() {
return new HTMLEntityEscapeSyslogMessageModifier();
}
public String modify(SyslogIF syslog, int facility, int level, String message) {
if (message != null && !"".equals(message.trim())) {
String escapedMessage = escapeHtml(message);
return escapedMessage;
}
return message;
}
public boolean verify(String message) {
// NO-OP
return true;
}
/**
* escapeHtml(String) is based partly on the article posted here: http://www.owasp.org/index.php/How_to_perform_HTML_entity_encoding_in_Java
* with the addition of common characters and modifications for Java 1.4 support.
*
* @param message
* @return Returns a message where any HTML entity characters are escaped.
*/
public static String escapeHtml(String message) {
StringBuffer b = new StringBuffer(message.length());
for (int i = 0; i < message.length(); i++) {
char ch = message.charAt(i);
public String modify(SyslogIF syslog, int facility, int level, String message) {
if (message != null && !"".equals(message.trim())) {
String escapedMessage = escapeHtml(message);
if (ch == '<') {
b.append("&lt;");
} else if (ch == '>') {
b.append("&gt;");
} else if (ch == '"') {
b.append("&quot;");
} else if (ch == '\'') {
b.append("&#39;");
} else if (ch == '&') {
b.append("&amp;");
} else if (ch >= ' ' && ch <= '~') {
b.append(ch);
} else if (Character.isWhitespace(ch)) {
b.append("&#").append((int) ch).append(";");
} else if (Character.isISOControl(ch)) {
// Ignore character
} else if (Character.isDefined(ch)) {
b.append("&#").append((int) ch).append(";");
}
}
return b.toString();
}
return escapedMessage;
}
return message;
}
public boolean verify(String message) {
// NO-OP
return true;
}
/**
* escapeHtml(String) is based partly on the article posted here: http://www.owasp.org/index.php/How_to_perform_HTML_entity_encoding_in_Java
* with the addition of common characters and modifications for Java 1.4 support.
*
* @param message
* @return Returns a message where any HTML entity characters are escaped.
*/
public static String escapeHtml(String message) {
StringBuffer b = new StringBuffer(message.length());
for (int i = 0; i < message.length(); i++) {
char ch = message.charAt(i);
if (ch == '<') {
b.append("&lt;");
} else if (ch == '>') {
b.append("&gt;");
} else if (ch == '"') {
b.append("&quot;");
} else if (ch == '\'') {
b.append("&#39;");
} else if (ch == '&') {
b.append("&amp;");
} else if (ch >= ' ' && ch <= '~') {
b.append(ch);
} else if (Character.isWhitespace(ch)) {
b.append("&#").append((int) ch).append(";");
} else if (Character.isISOControl(ch)) {
// Ignore character
} else if (Character.isDefined(ch)) {
b.append("&#").append((int) ch).append(";");
}
}
return b.toString();
}
}

View File

@ -11,122 +11,122 @@ import org.graylog2.syslog4j.util.Base64;
import org.graylog2.syslog4j.util.SyslogUtility;
/**
* HashSyslogMessageModifier is an implementation of SyslogMessageModifierIF
* that provides support for Java Cryptographic hashes (MD5, SHA1, SHA256, etc.).
*
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: HashSyslogMessageModifier.java,v 1.5 2010/10/28 05:10:57 cvs Exp $
*/
* HashSyslogMessageModifier is an implementation of SyslogMessageModifierIF
* that provides support for Java Cryptographic hashes (MD5, SHA1, SHA256, etc.).
* <p/>
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: HashSyslogMessageModifier.java,v 1.5 2010/10/28 05:10:57 cvs Exp $
*/
public class HashSyslogMessageModifier extends AbstractSyslogMessageModifier {
private static final long serialVersionUID = 7335757344826206953L;
protected HashSyslogMessageModifierConfig config = null;
public static final HashSyslogMessageModifier createMD5() {
HashSyslogMessageModifier md5 = new HashSyslogMessageModifier(HashSyslogMessageModifierConfig.createMD5());
return md5;
}
public static final HashSyslogMessageModifier createSHA1() {
HashSyslogMessageModifier sha1 = new HashSyslogMessageModifier(HashSyslogMessageModifierConfig.createSHA1());
return sha1;
}
public static final HashSyslogMessageModifier createSHA160() {
return createSHA1();
}
public static final HashSyslogMessageModifier createSHA256() {
HashSyslogMessageModifier sha256 = new HashSyslogMessageModifier(HashSyslogMessageModifierConfig.createSHA256());
return sha256;
}
public static final HashSyslogMessageModifier createSHA384() {
HashSyslogMessageModifier sha384 = new HashSyslogMessageModifier(HashSyslogMessageModifierConfig.createSHA384());
return sha384;
}
public static final HashSyslogMessageModifier createSHA512() {
HashSyslogMessageModifier sha512 = new HashSyslogMessageModifier(HashSyslogMessageModifierConfig.createSHA512());
return sha512;
}
public HashSyslogMessageModifier(HashSyslogMessageModifierConfig config) throws SyslogRuntimeException {
super(config);
this.config = config;
if (this.config == null) {
throw new SyslogRuntimeException("Hash config object cannot be null");
}
private static final long serialVersionUID = 7335757344826206953L;
if (this.config.getHashAlgorithm() == null) {
throw new SyslogRuntimeException("Hash algorithm cannot be null");
}
try {
MessageDigest.getInstance(config.getHashAlgorithm());
} catch (NoSuchAlgorithmException nsae){
throw new SyslogRuntimeException(nsae);
}
}
protected MessageDigest obtainMessageDigest() {
MessageDigest digest = null;
try {
digest = MessageDigest.getInstance(this.config.getHashAlgorithm());
} catch (NoSuchAlgorithmException nsae) {
throw new SyslogRuntimeException(nsae);
}
return digest;
}
protected HashSyslogMessageModifierConfig config = null;
public HashSyslogMessageModifierConfig getConfig() {
return this.config;
}
public String modify(SyslogIF syslog, int facility, int level, String message) {
byte[] messageBytes = SyslogUtility.getBytes(syslog.getConfig(),message);
MessageDigest digest = obtainMessageDigest();
byte[] digestBytes = digest.digest(messageBytes);
public static final HashSyslogMessageModifier createMD5() {
HashSyslogMessageModifier md5 = new HashSyslogMessageModifier(HashSyslogMessageModifierConfig.createMD5());
String digestString = Base64.encodeBytes(digestBytes,Base64.DONT_BREAK_LINES);
return md5;
}
StringBuffer buffer = new StringBuffer(message);
buffer.append(this.config.getPrefix());
buffer.append(digestString);
buffer.append(this.config.getSuffix());
return buffer.toString();
}
public static final HashSyslogMessageModifier createSHA1() {
HashSyslogMessageModifier sha1 = new HashSyslogMessageModifier(HashSyslogMessageModifierConfig.createSHA1());
public boolean verify(String message, String base64Hash) {
byte[] hash = Base64.decode(base64Hash);
return verify(message,hash);
}
public boolean verify(String message, byte[] hash) {
byte[] messageBytes = SyslogUtility.getBytes(this.config,message);
MessageDigest digest = obtainMessageDigest();
byte[] digestBytes = digest.digest(messageBytes);
return Arrays.equals(digestBytes,hash);
}
return sha1;
}
public static final HashSyslogMessageModifier createSHA160() {
return createSHA1();
}
public static final HashSyslogMessageModifier createSHA256() {
HashSyslogMessageModifier sha256 = new HashSyslogMessageModifier(HashSyslogMessageModifierConfig.createSHA256());
return sha256;
}
public static final HashSyslogMessageModifier createSHA384() {
HashSyslogMessageModifier sha384 = new HashSyslogMessageModifier(HashSyslogMessageModifierConfig.createSHA384());
return sha384;
}
public static final HashSyslogMessageModifier createSHA512() {
HashSyslogMessageModifier sha512 = new HashSyslogMessageModifier(HashSyslogMessageModifierConfig.createSHA512());
return sha512;
}
public HashSyslogMessageModifier(HashSyslogMessageModifierConfig config) throws SyslogRuntimeException {
super(config);
this.config = config;
if (this.config == null) {
throw new SyslogRuntimeException("Hash config object cannot be null");
}
if (this.config.getHashAlgorithm() == null) {
throw new SyslogRuntimeException("Hash algorithm cannot be null");
}
try {
MessageDigest.getInstance(config.getHashAlgorithm());
} catch (NoSuchAlgorithmException nsae) {
throw new SyslogRuntimeException(nsae);
}
}
protected MessageDigest obtainMessageDigest() {
MessageDigest digest = null;
try {
digest = MessageDigest.getInstance(this.config.getHashAlgorithm());
} catch (NoSuchAlgorithmException nsae) {
throw new SyslogRuntimeException(nsae);
}
return digest;
}
public HashSyslogMessageModifierConfig getConfig() {
return this.config;
}
public String modify(SyslogIF syslog, int facility, int level, String message) {
byte[] messageBytes = SyslogUtility.getBytes(syslog.getConfig(), message);
MessageDigest digest = obtainMessageDigest();
byte[] digestBytes = digest.digest(messageBytes);
String digestString = Base64.encodeBytes(digestBytes, Base64.DONT_BREAK_LINES);
StringBuffer buffer = new StringBuffer(message);
buffer.append(this.config.getPrefix());
buffer.append(digestString);
buffer.append(this.config.getSuffix());
return buffer.toString();
}
public boolean verify(String message, String base64Hash) {
byte[] hash = Base64.decode(base64Hash);
return verify(message, hash);
}
public boolean verify(String message, byte[] hash) {
byte[] messageBytes = SyslogUtility.getBytes(this.config, message);
MessageDigest digest = obtainMessageDigest();
byte[] digestBytes = digest.digest(messageBytes);
return Arrays.equals(digestBytes, hash);
}
}

View File

@ -3,64 +3,64 @@ package org.graylog2.syslog4j.impl.message.modifier.hash;
import org.graylog2.syslog4j.impl.message.modifier.AbstractSyslogMessageModifierConfig;
/**
* HashSyslogMessageModifierConfig is an implementation of AbstractSyslogMessageModifierConfig
* that provides configuration for HashSyslogMessageModifier.
*
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: HashSyslogMessageModifierConfig.java,v 1.1 2008/11/10 04:38:37 cvs Exp $
*/
* HashSyslogMessageModifierConfig is an implementation of AbstractSyslogMessageModifierConfig
* that provides configuration for HashSyslogMessageModifier.
* <p/>
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: HashSyslogMessageModifierConfig.java,v 1.1 2008/11/10 04:38:37 cvs Exp $
*/
public class HashSyslogMessageModifierConfig extends AbstractSyslogMessageModifierConfig {
private static final long serialVersionUID = -3148300281439874231L;
protected String hashAlgorithm = null;
public static final HashSyslogMessageModifierConfig createMD5() {
HashSyslogMessageModifierConfig md5 = new HashSyslogMessageModifierConfig("MD5");
return md5;
}
public static final HashSyslogMessageModifierConfig createSHA1() {
HashSyslogMessageModifierConfig sha1 = new HashSyslogMessageModifierConfig("SHA1");
return sha1;
}
public static final HashSyslogMessageModifierConfig createSHA160() {
return createSHA1();
}
public static final HashSyslogMessageModifierConfig createSHA256() {
HashSyslogMessageModifierConfig sha256 = new HashSyslogMessageModifierConfig("SHA-256");
return sha256;
}
public static final HashSyslogMessageModifierConfig createSHA384() {
HashSyslogMessageModifierConfig sha384 = new HashSyslogMessageModifierConfig("SHA-384");
return sha384;
}
public static final HashSyslogMessageModifierConfig createSHA512() {
HashSyslogMessageModifierConfig sha512 = new HashSyslogMessageModifierConfig("SHA-512");
return sha512;
}
public HashSyslogMessageModifierConfig(String hashAlgorithm) {
this.hashAlgorithm = hashAlgorithm;
}
private static final long serialVersionUID = -3148300281439874231L;
public String getHashAlgorithm() {
return this.hashAlgorithm;
}
public void setHashAlgorithm(String hashAlgorithm) {
this.hashAlgorithm = hashAlgorithm;
}
protected String hashAlgorithm = null;
public static final HashSyslogMessageModifierConfig createMD5() {
HashSyslogMessageModifierConfig md5 = new HashSyslogMessageModifierConfig("MD5");
return md5;
}
public static final HashSyslogMessageModifierConfig createSHA1() {
HashSyslogMessageModifierConfig sha1 = new HashSyslogMessageModifierConfig("SHA1");
return sha1;
}
public static final HashSyslogMessageModifierConfig createSHA160() {
return createSHA1();
}
public static final HashSyslogMessageModifierConfig createSHA256() {
HashSyslogMessageModifierConfig sha256 = new HashSyslogMessageModifierConfig("SHA-256");
return sha256;
}
public static final HashSyslogMessageModifierConfig createSHA384() {
HashSyslogMessageModifierConfig sha384 = new HashSyslogMessageModifierConfig("SHA-384");
return sha384;
}
public static final HashSyslogMessageModifierConfig createSHA512() {
HashSyslogMessageModifierConfig sha512 = new HashSyslogMessageModifierConfig("SHA-512");
return sha512;
}
public HashSyslogMessageModifierConfig(String hashAlgorithm) {
this.hashAlgorithm = hashAlgorithm;
}
public String getHashAlgorithm() {
return this.hashAlgorithm;
}
public void setHashAlgorithm(String hashAlgorithm) {
this.hashAlgorithm = hashAlgorithm;
}
}

View File

@ -14,107 +14,107 @@ import org.graylog2.syslog4j.util.Base64;
import org.graylog2.syslog4j.util.SyslogUtility;
/**
* MacSyslogMessageModifier is an implementation of SyslogMessageModifierIF
* that provides support for Java Cryptographic signed hashes (HmacSHA1, etc.)
*
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: MacSyslogMessageModifier.java,v 1.5 2010/10/28 05:10:57 cvs Exp $
*/
* MacSyslogMessageModifier is an implementation of SyslogMessageModifierIF
* that provides support for Java Cryptographic signed hashes (HmacSHA1, etc.)
* <p/>
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: MacSyslogMessageModifier.java,v 1.5 2010/10/28 05:10:57 cvs Exp $
*/
public class MacSyslogMessageModifier extends AbstractSyslogMessageModifier {
private static final long serialVersionUID = 5054979194802197540L;
private static final long serialVersionUID = 5054979194802197540L;
protected MacSyslogMessageModifierConfig config = null;
protected Mac mac = null;
public MacSyslogMessageModifier(MacSyslogMessageModifierConfig config) throws SyslogRuntimeException {
super(config);
this.config = config;
protected MacSyslogMessageModifierConfig config = null;
try {
this.mac = Mac.getInstance(config.getMacAlgorithm());
this.mac.init(config.getKey());
} catch (NoSuchAlgorithmException nsae) {
throw new SyslogRuntimeException(nsae);
} catch (InvalidKeyException ike) {
throw new SyslogRuntimeException(ike);
}
}
protected Mac mac = null;
public static MacSyslogMessageModifier createHmacSHA1(Key key) {
return new MacSyslogMessageModifier(MacSyslogMessageModifierConfig.createHmacSHA1(key));
}
public MacSyslogMessageModifier(MacSyslogMessageModifierConfig config) throws SyslogRuntimeException {
super(config);
public static MacSyslogMessageModifier createHmacSHA1(String base64Key) {
return new MacSyslogMessageModifier(MacSyslogMessageModifierConfig.createHmacSHA1(base64Key));
}
this.config = config;
public static MacSyslogMessageModifier createHmacSHA256(Key key) {
return new MacSyslogMessageModifier(MacSyslogMessageModifierConfig.createHmacSHA256(key));
}
try {
this.mac = Mac.getInstance(config.getMacAlgorithm());
this.mac.init(config.getKey());
public static MacSyslogMessageModifier createHmacSHA256(String base64Key) {
return new MacSyslogMessageModifier(MacSyslogMessageModifierConfig.createHmacSHA256(base64Key));
}
} catch (NoSuchAlgorithmException nsae) {
throw new SyslogRuntimeException(nsae);
public static MacSyslogMessageModifier createHmacSHA512(Key key) {
return new MacSyslogMessageModifier(MacSyslogMessageModifierConfig.createHmacSHA512(key));
}
} catch (InvalidKeyException ike) {
throw new SyslogRuntimeException(ike);
}
}
public static MacSyslogMessageModifier createHmacSHA512(String base64Key) {
return new MacSyslogMessageModifier(MacSyslogMessageModifierConfig.createHmacSHA512(base64Key));
}
public static MacSyslogMessageModifier createHmacSHA1(Key key) {
return new MacSyslogMessageModifier(MacSyslogMessageModifierConfig.createHmacSHA1(key));
}
public static MacSyslogMessageModifier createHmacMD5(Key key) {
return new MacSyslogMessageModifier(MacSyslogMessageModifierConfig.createHmacMD5(key));
}
public static MacSyslogMessageModifier createHmacSHA1(String base64Key) {
return new MacSyslogMessageModifier(MacSyslogMessageModifierConfig.createHmacSHA1(base64Key));
}
public static MacSyslogMessageModifier createHmacMD5(String base64Key) {
return new MacSyslogMessageModifier(MacSyslogMessageModifierConfig.createHmacMD5(base64Key));
}
public static MacSyslogMessageModifier createHmacSHA256(Key key) {
return new MacSyslogMessageModifier(MacSyslogMessageModifierConfig.createHmacSHA256(key));
}
public MacSyslogMessageModifierConfig getConfig() {
return this.config;
}
public static MacSyslogMessageModifier createHmacSHA256(String base64Key) {
return new MacSyslogMessageModifier(MacSyslogMessageModifierConfig.createHmacSHA256(base64Key));
}
public String modify(SyslogIF syslog, int facility, int level, String message) {
synchronized(this.mac) {
byte[] messageBytes = SyslogUtility.getBytes(syslog.getConfig(),message);
StringBuffer buffer = new StringBuffer(message);
byte[] macBytes = this.mac.doFinal(messageBytes);
String macString = Base64.encodeBytes(macBytes,Base64.DONT_BREAK_LINES);
buffer.append(this.config.getPrefix());
buffer.append(macString);
buffer.append(this.config.getSuffix());
return buffer.toString();
}
}
public boolean verify(String message, String base64Signature) {
byte[] signature = Base64.decode(base64Signature);
return verify(message,signature);
}
public boolean verify(String message, byte[] signature) {
synchronized(this.mac) {
byte[] messageBytes = SyslogUtility.getBytes(this.config,message);
byte[] macBytes = this.mac.doFinal(messageBytes);
return Arrays.equals(macBytes,signature);
}
}
public static MacSyslogMessageModifier createHmacSHA512(Key key) {
return new MacSyslogMessageModifier(MacSyslogMessageModifierConfig.createHmacSHA512(key));
}
public static MacSyslogMessageModifier createHmacSHA512(String base64Key) {
return new MacSyslogMessageModifier(MacSyslogMessageModifierConfig.createHmacSHA512(base64Key));
}
public static MacSyslogMessageModifier createHmacMD5(Key key) {
return new MacSyslogMessageModifier(MacSyslogMessageModifierConfig.createHmacMD5(key));
}
public static MacSyslogMessageModifier createHmacMD5(String base64Key) {
return new MacSyslogMessageModifier(MacSyslogMessageModifierConfig.createHmacMD5(base64Key));
}
public MacSyslogMessageModifierConfig getConfig() {
return this.config;
}
public String modify(SyslogIF syslog, int facility, int level, String message) {
synchronized (this.mac) {
byte[] messageBytes = SyslogUtility.getBytes(syslog.getConfig(), message);
StringBuffer buffer = new StringBuffer(message);
byte[] macBytes = this.mac.doFinal(messageBytes);
String macString = Base64.encodeBytes(macBytes, Base64.DONT_BREAK_LINES);
buffer.append(this.config.getPrefix());
buffer.append(macString);
buffer.append(this.config.getSuffix());
return buffer.toString();
}
}
public boolean verify(String message, String base64Signature) {
byte[] signature = Base64.decode(base64Signature);
return verify(message, signature);
}
public boolean verify(String message, byte[] signature) {
synchronized (this.mac) {
byte[] messageBytes = SyslogUtility.getBytes(this.config, message);
byte[] macBytes = this.mac.doFinal(messageBytes);
return Arrays.equals(macBytes, signature);
}
}
}

View File

@ -9,100 +9,100 @@ import org.graylog2.syslog4j.impl.message.modifier.AbstractSyslogMessageModifier
import org.graylog2.syslog4j.util.Base64;
/**
* MacSyslogMessageModifierConfig is an implementation of AbstractSyslogMessageModifierConfig
* that provides configuration for HashSyslogMessageModifier.
*
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: MacSyslogMessageModifierConfig.java,v 1.3 2009/04/17 02:37:04 cvs Exp $
*/
* MacSyslogMessageModifierConfig is an implementation of AbstractSyslogMessageModifierConfig
* that provides configuration for HashSyslogMessageModifier.
* <p/>
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: MacSyslogMessageModifierConfig.java,v 1.3 2009/04/17 02:37:04 cvs Exp $
*/
public class MacSyslogMessageModifierConfig extends AbstractSyslogMessageModifierConfig {
private static final long serialVersionUID = 4524180892377960695L;
protected String macAlgorithm = null;
protected String keyAlgorithm = null;
protected Key key = null;
public MacSyslogMessageModifierConfig(String macAlgorithm, String keyAlgorithm, Key key) {
this.macAlgorithm = macAlgorithm;
this.keyAlgorithm = keyAlgorithm;
this.key = key;
}
private static final long serialVersionUID = 4524180892377960695L;
public MacSyslogMessageModifierConfig(String macAlgorithm, String keyAlgorithm, byte[] keyBytes) {
this.macAlgorithm = macAlgorithm;
this.keyAlgorithm = keyAlgorithm;
try {
this.key = new SecretKeySpec(keyBytes,keyAlgorithm);
} catch (IllegalArgumentException iae) {
throw new SyslogRuntimeException(iae);
}
}
protected String macAlgorithm = null;
protected String keyAlgorithm = null;
protected Key key = null;
public MacSyslogMessageModifierConfig(String macAlgorithm, String keyAlgorithm, String base64Key) {
this.macAlgorithm = macAlgorithm;
this.keyAlgorithm = keyAlgorithm;
byte[] keyBytes = Base64.decode(base64Key);
try {
this.key = new SecretKeySpec(keyBytes,keyAlgorithm);
} catch (IllegalArgumentException iae) {
throw new SyslogRuntimeException(iae);
}
}
public static MacSyslogMessageModifierConfig createHmacSHA1(Key key) {
return new MacSyslogMessageModifierConfig("HmacSHA1","SHA1",key);
}
public MacSyslogMessageModifierConfig(String macAlgorithm, String keyAlgorithm, Key key) {
this.macAlgorithm = macAlgorithm;
this.keyAlgorithm = keyAlgorithm;
this.key = key;
}
public static MacSyslogMessageModifierConfig createHmacSHA1(String base64Key) {
return new MacSyslogMessageModifierConfig("HmacSHA1","SHA1",base64Key);
}
public MacSyslogMessageModifierConfig(String macAlgorithm, String keyAlgorithm, byte[] keyBytes) {
this.macAlgorithm = macAlgorithm;
this.keyAlgorithm = keyAlgorithm;
public static MacSyslogMessageModifierConfig createHmacSHA256(Key key) {
return new MacSyslogMessageModifierConfig("HmacSHA256","SHA-256",key);
}
try {
this.key = new SecretKeySpec(keyBytes, keyAlgorithm);
public static MacSyslogMessageModifierConfig createHmacSHA256(String base64Key) {
return new MacSyslogMessageModifierConfig("HmacSHA256","SHA-256",base64Key);
}
} catch (IllegalArgumentException iae) {
throw new SyslogRuntimeException(iae);
}
}
public static MacSyslogMessageModifierConfig createHmacSHA512(Key key) {
return new MacSyslogMessageModifierConfig("HmacSHA512","SHA-512",key);
}
public MacSyslogMessageModifierConfig(String macAlgorithm, String keyAlgorithm, String base64Key) {
this.macAlgorithm = macAlgorithm;
this.keyAlgorithm = keyAlgorithm;
public static MacSyslogMessageModifierConfig createHmacSHA512(String base64Key) {
return new MacSyslogMessageModifierConfig("HmacSHA512","SHA-512",base64Key);
}
byte[] keyBytes = Base64.decode(base64Key);
public static MacSyslogMessageModifierConfig createHmacMD5(Key key) {
return new MacSyslogMessageModifierConfig("HmacMD5","MD5",key);
}
try {
this.key = new SecretKeySpec(keyBytes, keyAlgorithm);
public static MacSyslogMessageModifierConfig createHmacMD5(String base64Key) {
return new MacSyslogMessageModifierConfig("HmacMD5","MD5",base64Key);
}
} catch (IllegalArgumentException iae) {
throw new SyslogRuntimeException(iae);
}
}
public String getMacAlgorithm() {
return this.macAlgorithm;
}
public String getKeyAlgorithm() {
return this.keyAlgorithm;
}
public static MacSyslogMessageModifierConfig createHmacSHA1(Key key) {
return new MacSyslogMessageModifierConfig("HmacSHA1", "SHA1", key);
}
public Key getKey() {
return this.key;
}
public static MacSyslogMessageModifierConfig createHmacSHA1(String base64Key) {
return new MacSyslogMessageModifierConfig("HmacSHA1", "SHA1", base64Key);
}
public void setKey(Key key) {
this.key = key;
}
public static MacSyslogMessageModifierConfig createHmacSHA256(Key key) {
return new MacSyslogMessageModifierConfig("HmacSHA256", "SHA-256", key);
}
public static MacSyslogMessageModifierConfig createHmacSHA256(String base64Key) {
return new MacSyslogMessageModifierConfig("HmacSHA256", "SHA-256", base64Key);
}
public static MacSyslogMessageModifierConfig createHmacSHA512(Key key) {
return new MacSyslogMessageModifierConfig("HmacSHA512", "SHA-512", key);
}
public static MacSyslogMessageModifierConfig createHmacSHA512(String base64Key) {
return new MacSyslogMessageModifierConfig("HmacSHA512", "SHA-512", base64Key);
}
public static MacSyslogMessageModifierConfig createHmacMD5(Key key) {
return new MacSyslogMessageModifierConfig("HmacMD5", "MD5", key);
}
public static MacSyslogMessageModifierConfig createHmacMD5(String base64Key) {
return new MacSyslogMessageModifierConfig("HmacMD5", "MD5", base64Key);
}
public String getMacAlgorithm() {
return this.macAlgorithm;
}
public String getKeyAlgorithm() {
return this.keyAlgorithm;
}
public Key getKey() {
return this.key;
}
public void setKey(Key key) {
this.key = key;
}
}

View File

@ -4,98 +4,98 @@ import org.graylog2.syslog4j.SyslogIF;
import org.graylog2.syslog4j.SyslogMessageModifierIF;
/**
* SequentialSyslogMessageModifier is an implementation of SyslogMessageModifierIF
* that adds an incremented number at the end.
*
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: SequentialSyslogMessageModifier.java,v 1.8 2010/11/28 04:43:31 cvs Exp $
*/
* SequentialSyslogMessageModifier is an implementation of SyslogMessageModifierIF
* that adds an incremented number at the end.
* <p/>
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: SequentialSyslogMessageModifier.java,v 1.8 2010/11/28 04:43:31 cvs Exp $
*/
public class SequentialSyslogMessageModifier implements SyslogMessageModifierIF {
private static final long serialVersionUID = 6107735010240030785L;
protected SequentialSyslogMessageModifierConfig config = null;
protected long currentSequence[] = new long[LEVEL_DEBUG + 1];
private static final long serialVersionUID = 6107735010240030785L;
public static final SequentialSyslogMessageModifier createDefault() {
SequentialSyslogMessageModifier modifier = new SequentialSyslogMessageModifier(SequentialSyslogMessageModifierConfig.createDefault());
return modifier;
}
protected SequentialSyslogMessageModifierConfig config = null;
public SequentialSyslogMessageModifier(SequentialSyslogMessageModifierConfig config) {
this.config = config;
for(int i=0; i<(LEVEL_DEBUG + 1); i++) {
this.currentSequence[i] = config.getFirstNumber();
}
}
protected String pad(long number) {
StringBuffer buffer = new StringBuffer(Long.toString(number));
while (buffer.length() < this.config.getLastNumberDigits()) {
buffer.insert(0,this.config.getPadChar());
}
return buffer.toString();
}
public void setNextSequence(int level, long nextSequence) {
if (nextSequence >= this.config.getFirstNumber() && nextSequence < this.config.getLastNumber()) {
synchronized(this) {
this.currentSequence[level] = nextSequence;
}
}
}
protected String nextSequence(int level) {
long sequence = -1;
synchronized(this) {
sequence = this.currentSequence[level];
if (this.currentSequence[level] >= this.config.getLastNumber()) {
this.currentSequence[level] = this.config.getFirstNumber();
} else {
this.currentSequence[level]++;
}
}
String _sequence = null;
if (this.config.isUsePadding()) {
_sequence = pad(sequence);
} else {
_sequence = Long.toString(sequence);
}
return _sequence;
}
protected long currentSequence[] = new long[LEVEL_DEBUG + 1];
public SequentialSyslogMessageModifierConfig getConfig() {
return this.config;
}
public static final SequentialSyslogMessageModifier createDefault() {
SequentialSyslogMessageModifier modifier = new SequentialSyslogMessageModifier(SequentialSyslogMessageModifierConfig.createDefault());
public String modify(SyslogIF syslog, int facility, int level, String message) {
StringBuffer buffer = new StringBuffer(message);
buffer.append(this.config.getPrefix());
buffer.append(nextSequence(level));
buffer.append(this.config.getSuffix());
return buffer.toString();
}
public boolean verify(String message) {
// NO-OP
return true;
}
return modifier;
}
public SequentialSyslogMessageModifier(SequentialSyslogMessageModifierConfig config) {
this.config = config;
for (int i = 0; i < (LEVEL_DEBUG + 1); i++) {
this.currentSequence[i] = config.getFirstNumber();
}
}
protected String pad(long number) {
StringBuffer buffer = new StringBuffer(Long.toString(number));
while (buffer.length() < this.config.getLastNumberDigits()) {
buffer.insert(0, this.config.getPadChar());
}
return buffer.toString();
}
public void setNextSequence(int level, long nextSequence) {
if (nextSequence >= this.config.getFirstNumber() && nextSequence < this.config.getLastNumber()) {
synchronized (this) {
this.currentSequence[level] = nextSequence;
}
}
}
protected String nextSequence(int level) {
long sequence = -1;
synchronized (this) {
sequence = this.currentSequence[level];
if (this.currentSequence[level] >= this.config.getLastNumber()) {
this.currentSequence[level] = this.config.getFirstNumber();
} else {
this.currentSequence[level]++;
}
}
String _sequence = null;
if (this.config.isUsePadding()) {
_sequence = pad(sequence);
} else {
_sequence = Long.toString(sequence);
}
return _sequence;
}
public SequentialSyslogMessageModifierConfig getConfig() {
return this.config;
}
public String modify(SyslogIF syslog, int facility, int level, String message) {
StringBuffer buffer = new StringBuffer(message);
buffer.append(this.config.getPrefix());
buffer.append(nextSequence(level));
buffer.append(this.config.getSuffix());
return buffer.toString();
}
public boolean verify(String message) {
// NO-OP
return true;
}
}

View File

@ -3,72 +3,72 @@ package org.graylog2.syslog4j.impl.message.modifier.sequential;
import org.graylog2.syslog4j.impl.message.modifier.AbstractSyslogMessageModifierConfig;
/**
* SequentialSyslogMessageModifierConfig is an implementation of AbstractSyslogMessageModifierConfig
* that provides configuration for SequentialSyslogMessageModifier.
*
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: SequentialSyslogMessageModifierConfig.java,v 1.4 2009/03/29 17:38:58 cvs Exp $
*/
* SequentialSyslogMessageModifierConfig is an implementation of AbstractSyslogMessageModifierConfig
* that provides configuration for SequentialSyslogMessageModifier.
* <p/>
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: SequentialSyslogMessageModifierConfig.java,v 1.4 2009/03/29 17:38:58 cvs Exp $
*/
public class SequentialSyslogMessageModifierConfig extends AbstractSyslogMessageModifierConfig {
private static final long serialVersionUID = 1570930406228960303L;
protected long firstNumber = SYSLOG_SEQUENTIAL_MESSAGE_MODIFIER_FIRST_NUMBER_DEFAULT;
protected long lastNumber = SYSLOG_SEQUENTIAL_MESSAGE_MODIFIER_LAST_NUMBER_DEFAULT;
protected char padChar = SYSLOG_SEQUENTIAL_MESSAGE_MODIFIER_PAD_CHAR_DEFAULT;
protected boolean usePadding = SYSLOG_SEQUENTIAL_MESSAGE_MODIFIER_USE_PADDING_DEFAULT;
public static final SequentialSyslogMessageModifierConfig createDefault() {
SequentialSyslogMessageModifierConfig modifierConfig = new SequentialSyslogMessageModifierConfig();
return modifierConfig;
}
private static final long serialVersionUID = 1570930406228960303L;
public SequentialSyslogMessageModifierConfig() {
setPrefix(SYSLOG_SEQUENTIAL_MESSAGE_MODIFIER_PREFIX_DEFAULT);
setSuffix(SYSLOG_SEQUENTIAL_MESSAGE_MODIFIER_SUFFIX_DEFAULT);
}
public long getLastNumberDigits() {
return Long.toString(this.lastNumber).length();
}
public long getFirstNumber() {
return this.firstNumber;
}
public void setFirstNumber(long firstNumber) {
if (firstNumber < this.lastNumber) {
this.firstNumber = firstNumber;
}
}
public long getLastNumber() {
return this.lastNumber;
}
public void setLastNumber(long lastNumber) {
if (lastNumber > this.firstNumber) {
this.lastNumber = lastNumber;
}
}
public boolean isUsePadding() {
return this.usePadding;
}
protected long firstNumber = SYSLOG_SEQUENTIAL_MESSAGE_MODIFIER_FIRST_NUMBER_DEFAULT;
protected long lastNumber = SYSLOG_SEQUENTIAL_MESSAGE_MODIFIER_LAST_NUMBER_DEFAULT;
protected char padChar = SYSLOG_SEQUENTIAL_MESSAGE_MODIFIER_PAD_CHAR_DEFAULT;
protected boolean usePadding = SYSLOG_SEQUENTIAL_MESSAGE_MODIFIER_USE_PADDING_DEFAULT;
public void setUsePadding(boolean usePadding) {
this.usePadding = usePadding;
}
public static final SequentialSyslogMessageModifierConfig createDefault() {
SequentialSyslogMessageModifierConfig modifierConfig = new SequentialSyslogMessageModifierConfig();
public char getPadChar() {
return this.padChar;
}
public void setPadChar(char padChar) {
this.padChar = padChar;
}
return modifierConfig;
}
public SequentialSyslogMessageModifierConfig() {
setPrefix(SYSLOG_SEQUENTIAL_MESSAGE_MODIFIER_PREFIX_DEFAULT);
setSuffix(SYSLOG_SEQUENTIAL_MESSAGE_MODIFIER_SUFFIX_DEFAULT);
}
public long getLastNumberDigits() {
return Long.toString(this.lastNumber).length();
}
public long getFirstNumber() {
return this.firstNumber;
}
public void setFirstNumber(long firstNumber) {
if (firstNumber < this.lastNumber) {
this.firstNumber = firstNumber;
}
}
public long getLastNumber() {
return this.lastNumber;
}
public void setLastNumber(long lastNumber) {
if (lastNumber > this.firstNumber) {
this.lastNumber = lastNumber;
}
}
public boolean isUsePadding() {
return this.usePadding;
}
public void setUsePadding(boolean usePadding) {
this.usePadding = usePadding;
}
public char getPadChar() {
return this.padChar;
}
public void setPadChar(char padChar) {
this.padChar = padChar;
}
}

View File

@ -4,56 +4,56 @@ import org.graylog2.syslog4j.SyslogIF;
import org.graylog2.syslog4j.SyslogMessageModifierIF;
/**
* PrefixSyslogMessageModifier is an implementation of SyslogMessageModifierIF
* that provides support for adding static text to the beginning of a Syslog message.
*
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: PrefixSyslogMessageModifier.java,v 1.5 2010/10/28 05:10:57 cvs Exp $
*/
* PrefixSyslogMessageModifier is an implementation of SyslogMessageModifierIF
* that provides support for adding static text to the beginning of a Syslog message.
* <p/>
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: PrefixSyslogMessageModifier.java,v 1.5 2010/10/28 05:10:57 cvs Exp $
*/
public class PrefixSyslogMessageModifier implements SyslogMessageModifierIF {
private static final long serialVersionUID = 6718826215583513972L;
protected String prefix = null;
protected String delimiter = " ";
private static final long serialVersionUID = 6718826215583513972L;
public PrefixSyslogMessageModifier() {
//
}
public PrefixSyslogMessageModifier(String prefix) {
this.prefix = prefix;
}
protected String prefix = null;
protected String delimiter = " ";
public PrefixSyslogMessageModifier(String prefix, String delimiter) {
this.prefix = prefix;
if (delimiter != null) {
this.delimiter = delimiter;
}
}
public PrefixSyslogMessageModifier() {
//
}
public String getPrefix() {
return this.prefix;
}
public PrefixSyslogMessageModifier(String prefix) {
this.prefix = prefix;
}
public void setPrefix(String prefix) {
this.prefix = prefix;
}
public PrefixSyslogMessageModifier(String prefix, String delimiter) {
this.prefix = prefix;
if (delimiter != null) {
this.delimiter = delimiter;
}
}
public String modify(SyslogIF syslog, int facility, int level, String message) {
if (this.prefix == null || "".equals(this.prefix.trim())) {
return message;
}
public String getPrefix() {
return this.prefix;
}
return this.prefix + this.delimiter + message;
}
public void setPrefix(String prefix) {
this.prefix = prefix;
}
public boolean verify(String message) {
// NO-OP
return true;
}
public String modify(SyslogIF syslog, int facility, int level, String message) {
if (this.prefix == null || "".equals(this.prefix.trim())) {
return message;
}
return this.prefix + this.delimiter + message;
}
public boolean verify(String message) {
// NO-OP
return true;
}
}

View File

@ -5,54 +5,54 @@ import org.graylog2.syslog4j.SyslogMessageModifierIF;
import org.graylog2.syslog4j.SyslogRuntimeException;
/**
* StringCaseSyslogMessageModifier is an implementation of SyslogMessageModifierIF
* that provides support for shifting a Syslog message to all upper case or all
* lower case.
*
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: StringCaseSyslogMessageModifier.java,v 1.3 2010/10/28 05:10:57 cvs Exp $
*/
* StringCaseSyslogMessageModifier is an implementation of SyslogMessageModifierIF
* that provides support for shifting a Syslog message to all upper case or all
* lower case.
* <p/>
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: StringCaseSyslogMessageModifier.java,v 1.3 2010/10/28 05:10:57 cvs Exp $
*/
public class StringCaseSyslogMessageModifier implements SyslogMessageModifierIF {
private static final long serialVersionUID = 8383234811585957460L;
public static final byte LOWER_CASE = 0;
public static final byte UPPER_CASE = 1;
public static final StringCaseSyslogMessageModifier LOWER = new StringCaseSyslogMessageModifier(LOWER_CASE);
public static final StringCaseSyslogMessageModifier UPPER = new StringCaseSyslogMessageModifier(UPPER_CASE);
protected byte stringCase = LOWER_CASE;
public StringCaseSyslogMessageModifier(byte stringCase) {
this.stringCase = stringCase;
if (stringCase < LOWER_CASE || stringCase > UPPER_CASE) {
throw new SyslogRuntimeException("stringCase must be LOWER_CASE (0) or UPPER_CASE (1)");
}
}
private static final long serialVersionUID = 8383234811585957460L;
public String modify(SyslogIF syslog, int facility, int level, String message) {
String _message = message;
if (message != null) {
if (this.stringCase == LOWER_CASE) {
_message = _message.toLowerCase();
} else if (this.stringCase == UPPER_CASE) {
_message = _message.toUpperCase();
}
}
return _message;
}
public static final byte LOWER_CASE = 0;
public static final byte UPPER_CASE = 1;
public boolean verify(String message) {
// NO-OP
return true;
}
public static final StringCaseSyslogMessageModifier LOWER = new StringCaseSyslogMessageModifier(LOWER_CASE);
public static final StringCaseSyslogMessageModifier UPPER = new StringCaseSyslogMessageModifier(UPPER_CASE);
protected byte stringCase = LOWER_CASE;
public StringCaseSyslogMessageModifier(byte stringCase) {
this.stringCase = stringCase;
if (stringCase < LOWER_CASE || stringCase > UPPER_CASE) {
throw new SyslogRuntimeException("stringCase must be LOWER_CASE (0) or UPPER_CASE (1)");
}
}
public String modify(SyslogIF syslog, int facility, int level, String message) {
String _message = message;
if (message != null) {
if (this.stringCase == LOWER_CASE) {
_message = _message.toLowerCase();
} else if (this.stringCase == UPPER_CASE) {
_message = _message.toUpperCase();
}
}
return _message;
}
public boolean verify(String message) {
// NO-OP
return true;
}
}

View File

@ -4,56 +4,56 @@ import org.graylog2.syslog4j.SyslogIF;
import org.graylog2.syslog4j.SyslogMessageModifierIF;
/**
* SuffixSyslogMessageModifier is an implementation of SyslogMessageModifierIF
* that provides support for adding static text to the end of a Syslog message.
*
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: SuffixSyslogMessageModifier.java,v 1.5 2010/10/28 05:10:57 cvs Exp $
*/
* SuffixSyslogMessageModifier is an implementation of SyslogMessageModifierIF
* that provides support for adding static text to the end of a Syslog message.
* <p/>
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: SuffixSyslogMessageModifier.java,v 1.5 2010/10/28 05:10:57 cvs Exp $
*/
public class SuffixSyslogMessageModifier implements SyslogMessageModifierIF {
private static final long serialVersionUID = 7160593302741507576L;
protected String suffix = null;
protected String delimiter = " ";
private static final long serialVersionUID = 7160593302741507576L;
public SuffixSyslogMessageModifier() {
//
}
protected String suffix = null;
protected String delimiter = " ";
public SuffixSyslogMessageModifier(String suffix) {
this.suffix = suffix;
}
public SuffixSyslogMessageModifier() {
//
}
public SuffixSyslogMessageModifier(String suffix, String delimiter) {
this.suffix = suffix;
if (delimiter != null) {
this.delimiter = delimiter;
}
}
public SuffixSyslogMessageModifier(String suffix) {
this.suffix = suffix;
}
public String getSuffix() {
return this.suffix;
}
public SuffixSyslogMessageModifier(String suffix, String delimiter) {
this.suffix = suffix;
if (delimiter != null) {
this.delimiter = delimiter;
}
}
public void setSuffix(String suffix) {
this.suffix = suffix;
}
public String getSuffix() {
return this.suffix;
}
public String modify(SyslogIF syslog, int facility, int level, String message) {
if (this.suffix == null || "".equals(this.suffix.trim())) {
return message;
}
public void setSuffix(String suffix) {
this.suffix = suffix;
}
return message + this.delimiter + this.suffix;
}
public String modify(SyslogIF syslog, int facility, int level, String message) {
if (this.suffix == null || "".equals(this.suffix.trim())) {
return message;
}
public boolean verify(String message) {
// NO-OP
return true;
}
return message + this.delimiter + this.suffix;
}
public boolean verify(String message) {
// NO-OP
return true;
}
}

View File

@ -6,251 +6,275 @@ import java.util.Map;
import org.graylog2.syslog4j.impl.message.AbstractSyslogMessage;
/**
* PCISyslogMessage provides support for audit trails defined by section
* 10.3 of the PCI Data Security Standard (PCI DSS) versions 1.1 and 1.2.
*
* <p>More information on the PCI DSS specification is available here:</p>
*
* <p>https://www.pcisecuritystandards.org/security_standards/pci_dss.shtml</p>
*
* <p>The PCI DSS specification is Copyright 2008 PCI Security Standards
* Council LLC.</p>
*
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: PCISyslogMessage.java,v 1.3 2008/11/14 04:32:00 cvs Exp $
*/
* PCISyslogMessage provides support for audit trails defined by section
* 10.3 of the PCI Data Security Standard (PCI DSS) versions 1.1 and 1.2.
* <p/>
* <p>More information on the PCI DSS specification is available here:</p>
* <p/>
* <p>https://www.pcisecuritystandards.org/security_standards/pci_dss.shtml</p>
* <p/>
* <p>The PCI DSS specification is Copyright 2008 PCI Security Standards
* Council LLC.</p>
* <p/>
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: PCISyslogMessage.java,v 1.3 2008/11/14 04:32:00 cvs Exp $
*/
public class PCISyslogMessage extends AbstractSyslogMessage implements PCISyslogMessageIF {
private static final long serialVersionUID = 3571696218386879119L;
public static final String USER_ID = "userId";
public static final String EVENT_TYPE = "eventType";
public static final String DATE = "date";
public static final String TIME = "time";
public static final String STATUS = "status";
public static final String ORIGINATION = "origination";
public static final String AFFECTED_RESOURCE = "affectedResource";
protected String userId = UNDEFINED; // 10.3.1 "User Identification"
protected String eventType = UNDEFINED; // 10.3.2 "Type of event"
protected String date = null; // 10.3.3 "Date and time" (date)
protected String time = null; // 10.3.3 "Date and time" (time)
protected String status = UNDEFINED; // 10.3.4 "Success or failure indication"
protected String origination = null; // 10.3.5 "Origination of Event"
protected String affectedResource = UNDEFINED; // 10.3.6 "Identity or name of affected data, system component, or resource"
private static final long serialVersionUID = 3571696218386879119L;
public PCISyslogMessage() {
//
}
public static final String USER_ID = "userId";
public static final String EVENT_TYPE = "eventType";
public static final String DATE = "date";
public static final String TIME = "time";
public static final String STATUS = "status";
public static final String ORIGINATION = "origination";
public static final String AFFECTED_RESOURCE = "affectedResource";
public PCISyslogMessage(PCISyslogMessageIF message) {
init(message);
}
public PCISyslogMessage(Map fields) {
init(fields);
}
protected void init(PCISyslogMessageIF message) {
this.userId = message.getUserId();
this.eventType = message.getEventType();
this.date = message.getDate();
this.time = message.getTime();
this.status = message.getStatus();
this.origination = message.getOrigination();
this.affectedResource = message.getAffectedResource();
}
protected String userId = UNDEFINED; // 10.3.1 "User Identification"
protected String eventType = UNDEFINED; // 10.3.2 "Type of event"
protected String date = null; // 10.3.3 "Date and time" (date)
protected String time = null; // 10.3.3 "Date and time" (time)
protected String status = UNDEFINED; // 10.3.4 "Success or failure indication"
protected String origination = null; // 10.3.5 "Origination of Event"
protected String affectedResource = UNDEFINED; // 10.3.6 "Identity or name of affected data, system component, or resource"
protected void init(Map fields) {
if (fields.containsKey(USER_ID)) { this.userId = (String) fields.get(USER_ID); };
if (fields.containsKey(EVENT_TYPE)) { this.eventType = (String) fields.get(EVENT_TYPE); };
if (fields.containsKey(DATE) && fields.get(DATE) instanceof String) { this.date = (String) fields.get(DATE); };
if (fields.containsKey(DATE) && fields.get(DATE) instanceof Date) { setDate((Date) fields.get(DATE)); };
if (fields.containsKey(TIME)) { this.time = (String) fields.get(TIME); };
if (fields.containsKey(STATUS)) { this.status = (String) fields.get(STATUS); };
if (fields.containsKey(ORIGINATION)) { this.origination = (String) fields.get(ORIGINATION); };
if (fields.containsKey(AFFECTED_RESOURCE)) { this.affectedResource = (String) fields.get(AFFECTED_RESOURCE); };
}
public PCISyslogMessage() {
//
}
public PCISyslogMessage(String userId, String eventType, String status, String affectedResource) {
this.userId = userId;
this.eventType = eventType;
this.status = status;
this.affectedResource = affectedResource;
}
public PCISyslogMessage(PCISyslogMessageIF message) {
init(message);
}
public PCISyslogMessage(String userId, String eventType, String status, String origination, String affectedResource) {
this.userId = userId;
this.eventType = eventType;
this.status = status;
this.origination = origination;
this.affectedResource = affectedResource;
}
public PCISyslogMessage(Map fields) {
init(fields);
}
public PCISyslogMessage(String userId, String eventType, String date, String time, String status, String affectedResource) {
this.userId = userId;
this.eventType = eventType;
this.date = date;
this.time = time;
this.status = status;
this.affectedResource = affectedResource;
}
protected void init(PCISyslogMessageIF message) {
this.userId = message.getUserId();
this.eventType = message.getEventType();
this.date = message.getDate();
this.time = message.getTime();
this.status = message.getStatus();
this.origination = message.getOrigination();
this.affectedResource = message.getAffectedResource();
}
public PCISyslogMessage(String userId, String eventType, String date, String time, String status, String origination, String affectedResource) {
this.userId = userId;
this.eventType = eventType;
this.date = date;
this.time = time;
this.status = status;
this.origination = origination;
this.affectedResource = affectedResource;
}
protected void init(Map fields) {
if (fields.containsKey(USER_ID)) {
this.userId = (String) fields.get(USER_ID);
}
;
if (fields.containsKey(EVENT_TYPE)) {
this.eventType = (String) fields.get(EVENT_TYPE);
}
;
if (fields.containsKey(DATE) && fields.get(DATE) instanceof String) {
this.date = (String) fields.get(DATE);
}
;
if (fields.containsKey(DATE) && fields.get(DATE) instanceof Date) {
setDate((Date) fields.get(DATE));
}
;
if (fields.containsKey(TIME)) {
this.time = (String) fields.get(TIME);
}
;
if (fields.containsKey(STATUS)) {
this.status = (String) fields.get(STATUS);
}
;
if (fields.containsKey(ORIGINATION)) {
this.origination = (String) fields.get(ORIGINATION);
}
;
if (fields.containsKey(AFFECTED_RESOURCE)) {
this.affectedResource = (String) fields.get(AFFECTED_RESOURCE);
}
;
}
public PCISyslogMessage(String userId, String eventType, Date date, String status, String affectedResource) {
this.userId = userId;
this.eventType = eventType;
String[] dateAndTime = generateDateAndTime(date);
this.date = dateAndTime[0];
this.time = dateAndTime[1];
this.status = status;
this.affectedResource = affectedResource;
}
public PCISyslogMessage(String userId, String eventType, Date date, String status, String origination, String affectedResource) {
this.userId = userId;
this.eventType = eventType;
String[] dateAndTime = generateDateAndTime(date);
this.date = dateAndTime[0];
this.time = dateAndTime[1];
this.status = status;
this.origination = origination;
this.affectedResource = affectedResource;
}
public PCISyslogMessage(String userId, String eventType, String status, String affectedResource) {
this.userId = userId;
this.eventType = eventType;
this.status = status;
this.affectedResource = affectedResource;
}
public String getUserId() {
if (nullOrEmpty(this.userId)) {
return UNDEFINED;
}
return this.userId;
}
public PCISyslogMessage(String userId, String eventType, String status, String origination, String affectedResource) {
this.userId = userId;
this.eventType = eventType;
this.status = status;
this.origination = origination;
this.affectedResource = affectedResource;
}
public void setUserId(String userId) {
this.userId = userId;
}
public PCISyslogMessage(String userId, String eventType, String date, String time, String status, String affectedResource) {
this.userId = userId;
this.eventType = eventType;
this.date = date;
this.time = time;
this.status = status;
this.affectedResource = affectedResource;
}
public String getEventType() {
if (nullOrEmpty(this.eventType)) {
return UNDEFINED;
}
return this.eventType;
}
public PCISyslogMessage(String userId, String eventType, String date, String time, String status, String origination, String affectedResource) {
this.userId = userId;
this.eventType = eventType;
this.date = date;
this.time = time;
this.status = status;
this.origination = origination;
this.affectedResource = affectedResource;
}
public void setEventType(String eventType) {
this.eventType = eventType;
}
public PCISyslogMessage(String userId, String eventType, Date date, String status, String affectedResource) {
this.userId = userId;
this.eventType = eventType;
public String getDate() {
if (nullOrEmpty(this.date)) {
String dateNow = generateDate();
return dateNow;
}
return this.date;
}
String[] dateAndTime = generateDateAndTime(date);
this.date = dateAndTime[0];
this.time = dateAndTime[1];
public void setDate(String date) {
this.date = date;
}
this.status = status;
this.affectedResource = affectedResource;
}
public void setDate(Date date) {
String[] d = generateDateAndTime(date);
this.date = d[0];
this.time = d[1];
}
public PCISyslogMessage(String userId, String eventType, Date date, String status, String origination, String affectedResource) {
this.userId = userId;
this.eventType = eventType;
public String getTime() {
if (nullOrEmpty(this.time)) {
String timeNow = generateTime();
return timeNow;
}
return this.time;
}
String[] dateAndTime = generateDateAndTime(date);
this.date = dateAndTime[0];
this.time = dateAndTime[1];
public void setTime(String time) {
this.time = time;
}
this.status = status;
this.origination = origination;
this.affectedResource = affectedResource;
}
public String getStatus() {
if (nullOrEmpty(this.status)) {
return UNDEFINED;
}
return this.status;
}
public String getUserId() {
if (nullOrEmpty(this.userId)) {
return UNDEFINED;
}
public void setStatus(String status) {
this.status = status;
}
return this.userId;
}
public String getOrigination() {
if (nullOrEmpty(this.origination)) {
String originationHere = generateLocalHostName();
return originationHere;
}
return this.origination;
}
public void setUserId(String userId) {
this.userId = userId;
}
public void setOrigination(String origination) {
this.origination = origination;
}
public String getEventType() {
if (nullOrEmpty(this.eventType)) {
return UNDEFINED;
}
public String getAffectedResource() {
if (nullOrEmpty(this.affectedResource)) {
return UNDEFINED;
}
return this.affectedResource;
}
return this.eventType;
}
public void setAffectedResource(String affectedResource) {
this.affectedResource = affectedResource;
}
public String createMessage() {
StringBuffer buffer = new StringBuffer();
char delimiter = getDelimiter();
String replaceDelimiter = getReplaceDelimiter();
buffer.append(replaceDelimiter(USER_ID,getUserId(),delimiter,replaceDelimiter));
buffer.append(delimiter);
buffer.append(replaceDelimiter(EVENT_TYPE,getEventType(),delimiter,replaceDelimiter));
buffer.append(delimiter);
buffer.append(replaceDelimiter(DATE,getDate(),delimiter,replaceDelimiter));
buffer.append(delimiter);
buffer.append(replaceDelimiter(TIME,getTime(),delimiter,replaceDelimiter));
buffer.append(delimiter);
buffer.append(replaceDelimiter(STATUS,getStatus(),delimiter,replaceDelimiter));
buffer.append(delimiter);
buffer.append(replaceDelimiter(ORIGINATION,getOrigination(),delimiter,replaceDelimiter));
buffer.append(delimiter);
buffer.append(replaceDelimiter(AFFECTED_RESOURCE,getAffectedResource(),delimiter,replaceDelimiter));
return buffer.toString();
}
public void setEventType(String eventType) {
this.eventType = eventType;
}
public String getDate() {
if (nullOrEmpty(this.date)) {
String dateNow = generateDate();
return dateNow;
}
return this.date;
}
public void setDate(String date) {
this.date = date;
}
public void setDate(Date date) {
String[] d = generateDateAndTime(date);
this.date = d[0];
this.time = d[1];
}
public String getTime() {
if (nullOrEmpty(this.time)) {
String timeNow = generateTime();
return timeNow;
}
return this.time;
}
public void setTime(String time) {
this.time = time;
}
public String getStatus() {
if (nullOrEmpty(this.status)) {
return UNDEFINED;
}
return this.status;
}
public void setStatus(String status) {
this.status = status;
}
public String getOrigination() {
if (nullOrEmpty(this.origination)) {
String originationHere = generateLocalHostName();
return originationHere;
}
return this.origination;
}
public void setOrigination(String origination) {
this.origination = origination;
}
public String getAffectedResource() {
if (nullOrEmpty(this.affectedResource)) {
return UNDEFINED;
}
return this.affectedResource;
}
public void setAffectedResource(String affectedResource) {
this.affectedResource = affectedResource;
}
public String createMessage() {
StringBuffer buffer = new StringBuffer();
char delimiter = getDelimiter();
String replaceDelimiter = getReplaceDelimiter();
buffer.append(replaceDelimiter(USER_ID, getUserId(), delimiter, replaceDelimiter));
buffer.append(delimiter);
buffer.append(replaceDelimiter(EVENT_TYPE, getEventType(), delimiter, replaceDelimiter));
buffer.append(delimiter);
buffer.append(replaceDelimiter(DATE, getDate(), delimiter, replaceDelimiter));
buffer.append(delimiter);
buffer.append(replaceDelimiter(TIME, getTime(), delimiter, replaceDelimiter));
buffer.append(delimiter);
buffer.append(replaceDelimiter(STATUS, getStatus(), delimiter, replaceDelimiter));
buffer.append(delimiter);
buffer.append(replaceDelimiter(ORIGINATION, getOrigination(), delimiter, replaceDelimiter));
buffer.append(delimiter);
buffer.append(replaceDelimiter(AFFECTED_RESOURCE, getAffectedResource(), delimiter, replaceDelimiter));
return buffer.toString();
}
}

View File

@ -1,30 +1,36 @@
package org.graylog2.syslog4j.impl.message.pci;
/**
* PCISyslogMessageIF provides a definition of the fields for audit trails
* defined by section 10.3 of the PCI Data Security Standard (PCI DSS)
* versions 1.1 and 1.2.
*
* <p>More information on the PCI DSS specification is available here:</p>
*
* <p>https://www.pcisecuritystandards.org/security_standards/pci_dss.shtml</p>
*
* <p>The PCI DSS specification is Copyright 2008 PCI Security Standards
* Council LLC.</p>
*
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: PCISyslogMessageIF.java,v 1.1 2008/11/10 04:38:37 cvs Exp $
*/
* PCISyslogMessageIF provides a definition of the fields for audit trails
* defined by section 10.3 of the PCI Data Security Standard (PCI DSS)
* versions 1.1 and 1.2.
* <p/>
* <p>More information on the PCI DSS specification is available here:</p>
* <p/>
* <p>https://www.pcisecuritystandards.org/security_standards/pci_dss.shtml</p>
* <p/>
* <p>The PCI DSS specification is Copyright 2008 PCI Security Standards
* Council LLC.</p>
* <p/>
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: PCISyslogMessageIF.java,v 1.1 2008/11/10 04:38:37 cvs Exp $
*/
public interface PCISyslogMessageIF {
public String getUserId();
public String getEventType();
public String getDate();
public String getTime();
public String getStatus();
public String getOrigination();
public String getAffectedResource();
public String getUserId();
public String getEventType();
public String getDate();
public String getTime();
public String getStatus();
public String getOrigination();
public String getAffectedResource();
}

View File

@ -9,110 +9,110 @@ import org.graylog2.syslog4j.SyslogMessageProcessorIF;
import org.graylog2.syslog4j.util.SyslogUtility;
/**
* AbstractSyslogMessageProcessor provides the ability to split a syslog message
* into multiple messages when the message is greater than the syslog
* maximum message length (1024 bytes including the header).
*
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: AbstractSyslogMessageProcessor.java,v 1.2 2010/11/28 04:15:18 cvs Exp $
*/
* AbstractSyslogMessageProcessor provides the ability to split a syslog message
* into multiple messages when the message is greater than the syslog
* maximum message length (1024 bytes including the header).
* <p/>
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: AbstractSyslogMessageProcessor.java,v 1.2 2010/11/28 04:15:18 cvs Exp $
*/
public abstract class AbstractSyslogMessageProcessor implements SyslogMessageProcessorIF, SyslogConstants {
private static final long serialVersionUID = -5413127301924500938L;
protected String localName = null;
public AbstractSyslogMessageProcessor() {
this.localName = SyslogUtility.getLocalName();
}
private static final long serialVersionUID = -5413127301924500938L;
protected String localName = null;
public byte[] createPacketData(byte[] header, byte[] message, int start, int length) {
return createPacketData(header,message,start,length,null,null);
}
public AbstractSyslogMessageProcessor() {
this.localName = SyslogUtility.getLocalName();
}
public byte[] createPacketData(byte[] header, byte[] message, int start, int length, byte[] splitBeginText, byte[] splitEndText) {
if (header == null || message == null || start < 0 || length < 0) {
return null;
}
int dataLength = header.length + length;
if (splitBeginText != null) {
dataLength += splitBeginText.length;
}
if (splitEndText != null) {
dataLength += splitEndText.length;
}
byte[] data = new byte[dataLength];
public byte[] createPacketData(byte[] header, byte[] message, int start, int length) {
return createPacketData(header, message, start, length, null, null);
}
System.arraycopy(header,0,data,0,header.length);
int pos = header.length;
if (splitBeginText != null) {
System.arraycopy(splitBeginText,0,data,pos,splitBeginText.length);
pos += splitBeginText.length;
}
System.arraycopy(message,start,data,pos,length);
pos += length;
public byte[] createPacketData(byte[] header, byte[] message, int start, int length, byte[] splitBeginText, byte[] splitEndText) {
if (header == null || message == null || start < 0 || length < 0) {
return null;
}
if (splitEndText != null) {
System.arraycopy(splitEndText,0,data,pos,splitEndText.length);
}
return data;
}
int dataLength = header.length + length;
protected void appendPriority(StringBuffer buffer, int facility, int level) {
int priority = facility | level;
if (splitBeginText != null) {
dataLength += splitBeginText.length;
}
if (splitEndText != null) {
dataLength += splitEndText.length;
}
buffer.append("<");
buffer.append(priority);
buffer.append(">");
}
protected void appendLocalTimestamp(StringBuffer buffer) {
SimpleDateFormat dateFormat = new SimpleDateFormat(SYSLOG_DATEFORMAT,Locale.ENGLISH);
String datePrefix = dateFormat.format(new Date());
int pos = buffer.length() + 4;
buffer.append(datePrefix);
// RFC 3164 requires leading space for days 1-9
if (buffer.charAt(pos) == '0') {
buffer.setCharAt(pos,' ');
}
}
protected void appendLocalName(StringBuffer buffer, String localName) {
if (localName != null) {
buffer.append(localName);
} else {
buffer.append(this.localName);
}
buffer.append(' ');
}
byte[] data = new byte[dataLength];
public String createSyslogHeader(int facility, int level, String localName, boolean sendLocalTimestamp, boolean sendLocalName) {
StringBuffer buffer = new StringBuffer();
appendPriority(buffer,facility,level);
if (sendLocalTimestamp) {
appendLocalTimestamp(buffer);
}
if (sendLocalName) {
appendLocalName(buffer,localName);
}
return buffer.toString();
}
System.arraycopy(header, 0, data, 0, header.length);
int pos = header.length;
if (splitBeginText != null) {
System.arraycopy(splitBeginText, 0, data, pos, splitBeginText.length);
pos += splitBeginText.length;
}
System.arraycopy(message, start, data, pos, length);
pos += length;
if (splitEndText != null) {
System.arraycopy(splitEndText, 0, data, pos, splitEndText.length);
}
return data;
}
protected void appendPriority(StringBuffer buffer, int facility, int level) {
int priority = facility | level;
buffer.append("<");
buffer.append(priority);
buffer.append(">");
}
protected void appendLocalTimestamp(StringBuffer buffer) {
SimpleDateFormat dateFormat = new SimpleDateFormat(SYSLOG_DATEFORMAT, Locale.ENGLISH);
String datePrefix = dateFormat.format(new Date());
int pos = buffer.length() + 4;
buffer.append(datePrefix);
// RFC 3164 requires leading space for days 1-9
if (buffer.charAt(pos) == '0') {
buffer.setCharAt(pos, ' ');
}
}
protected void appendLocalName(StringBuffer buffer, String localName) {
if (localName != null) {
buffer.append(localName);
} else {
buffer.append(this.localName);
}
buffer.append(' ');
}
public String createSyslogHeader(int facility, int level, String localName, boolean sendLocalTimestamp, boolean sendLocalName) {
StringBuffer buffer = new StringBuffer();
appendPriority(buffer, facility, level);
if (sendLocalTimestamp) {
appendLocalTimestamp(buffer);
}
if (sendLocalName) {
appendLocalName(buffer, localName);
}
return buffer.toString();
}
}

View File

@ -2,34 +2,34 @@ package org.graylog2.syslog4j.impl.message.processor;
/**
* SyslogMessageProcessor wraps AbstractSyslogMessageProcessor.
*
* <p>Those wishing to replace (or improve upon) this implementation
* can write a custom SyslogMessageProcessorIF and set it per
* instance via the SyslogIF.setMessageProcessor(..) method or set it globally
* via the SyslogMessageProcessor.setDefault(..) method.</p>
*
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: SyslogMessageProcessor.java,v 1.7 2010/02/04 03:41:37 cvs Exp $
*/
* SyslogMessageProcessor wraps AbstractSyslogMessageProcessor.
* <p/>
* <p>Those wishing to replace (or improve upon) this implementation
* can write a custom SyslogMessageProcessorIF and set it per
* instance via the SyslogIF.setMessageProcessor(..) method or set it globally
* via the SyslogMessageProcessor.setDefault(..) method.</p>
* <p/>
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: SyslogMessageProcessor.java,v 1.7 2010/02/04 03:41:37 cvs Exp $
*/
public class SyslogMessageProcessor extends AbstractSyslogMessageProcessor {
private static final long serialVersionUID = -4232803978024990353L;
private static final SyslogMessageProcessor INSTANCE = new SyslogMessageProcessor();
protected static SyslogMessageProcessor defaultInstance = INSTANCE;
public static void setDefault(SyslogMessageProcessor messageProcessor) {
if (messageProcessor != null) {
defaultInstance = messageProcessor;
}
}
public static SyslogMessageProcessor getDefault() {
return defaultInstance;
}
private static final long serialVersionUID = -4232803978024990353L;
private static final SyslogMessageProcessor INSTANCE = new SyslogMessageProcessor();
protected static SyslogMessageProcessor defaultInstance = INSTANCE;
public static void setDefault(SyslogMessageProcessor messageProcessor) {
if (messageProcessor != null) {
defaultInstance = messageProcessor;
}
}
public static SyslogMessageProcessor getDefault() {
return defaultInstance;
}
}

View File

@ -11,96 +11,96 @@ import org.graylog2.syslog4j.impl.message.structured.StructuredSyslogMessage;
* than the syslog maximum message length (1024 bytes including the header). It
* adds support for structured syslog messages as specified by
* draft-ietf-syslog-protocol-23. More information here:
*
* <p/>
* <p>http://tools.ietf.org/html/draft-ietf-syslog-protocol-23</p>
*
* <p/>
* <p>Those wishing to replace (or improve upon) this implementation
* can write a custom SyslogMessageProcessorIF and set it per
* instance via the SyslogIF.setStructuredMessageProcessor(..) method or set it globally
* via the StructuredSyslogMessageProcessor.setDefault(..) method.</p>
*
* <p/>
* <p>
* Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy of the
* LGPL license is available in the META-INF folder in all distributions of
* Syslog4j and in the base directory of the "doc" ZIP.
* </p>
*
*
* @author Manish Motwani
* @version $Id: StructuredSyslogMessageProcessor.java,v 1.4 2011/01/11 05:11:13 cvs Exp $
*/
public class StructuredSyslogMessageProcessor extends AbstractSyslogMessageProcessor {
private static final long serialVersionUID = -1563777226913475257L;
public static String VERSION = "1";
private static final long serialVersionUID = -1563777226913475257L;
private static final StructuredSyslogMessageProcessor INSTANCE = new StructuredSyslogMessageProcessor();
protected static StructuredSyslogMessageProcessor defaultInstance = INSTANCE;
private String applicationName = STRUCTURED_DATA_APP_NAME_DEFAULT_VALUE;
private String processId = STRUCTURED_DATA_PROCESS_ID_DEFAULT_VALUE;
private DateTimeFormatter dateTimeFormatter = ISODateTimeFormat.dateTime();
public static String VERSION = "1";
public static void setDefault(StructuredSyslogMessageProcessor messageProcessor) {
if (messageProcessor != null) {
defaultInstance = messageProcessor;
}
}
public static StructuredSyslogMessageProcessor getDefault() {
return defaultInstance;
}
public StructuredSyslogMessageProcessor() {
super();
}
private static final StructuredSyslogMessageProcessor INSTANCE = new StructuredSyslogMessageProcessor();
protected static StructuredSyslogMessageProcessor defaultInstance = INSTANCE;
public StructuredSyslogMessageProcessor(final String applicationName) {
super();
this.applicationName = applicationName;
}
private String applicationName = STRUCTURED_DATA_APP_NAME_DEFAULT_VALUE;
private String processId = STRUCTURED_DATA_PROCESS_ID_DEFAULT_VALUE;
public DateTimeFormatter getDateTimeFormatter() {
return dateTimeFormatter;
}
private DateTimeFormatter dateTimeFormatter = ISODateTimeFormat.dateTime();
public void setDateTimeFormatter(DateTimeFormatter dateTimeFormatter) {
this.dateTimeFormatter = dateTimeFormatter;
}
public static void setDefault(StructuredSyslogMessageProcessor messageProcessor) {
if (messageProcessor != null) {
defaultInstance = messageProcessor;
}
}
public String getApplicationName() {
return this.applicationName;
}
public static StructuredSyslogMessageProcessor getDefault() {
return defaultInstance;
}
public void setApplicationName(String applicationName) {
this.applicationName = applicationName;
}
public StructuredSyslogMessageProcessor() {
super();
}
public String getProcessId() {
return this.processId;
}
public StructuredSyslogMessageProcessor(final String applicationName) {
super();
this.applicationName = applicationName;
}
public void setProcessId(String processId) {
this.processId = processId;
}
public DateTimeFormatter getDateTimeFormatter() {
return dateTimeFormatter;
}
public String createSyslogHeader(final int facility, final int level, String localName, final boolean sendLocalTimestamp, final boolean sendLocalName) {
final StringBuffer buffer = new StringBuffer();
public void setDateTimeFormatter(DateTimeFormatter dateTimeFormatter) {
this.dateTimeFormatter = dateTimeFormatter;
}
appendPriority(buffer,facility,level);
buffer.append(VERSION);
buffer.append(' ');
public String getApplicationName() {
return this.applicationName;
}
getDateTimeFormatter().printTo(buffer,System.currentTimeMillis());
buffer.append(' ');
public void setApplicationName(String applicationName) {
this.applicationName = applicationName;
}
appendLocalName(buffer,localName);
public String getProcessId() {
return this.processId;
}
buffer.append(StructuredSyslogMessage.nilProtect(this.applicationName))
.append(' ');
public void setProcessId(String processId) {
this.processId = processId;
}
buffer.append(StructuredSyslogMessage.nilProtect(this.processId)).append(' ');
return buffer.toString();
}
public String createSyslogHeader(final int facility, final int level, String localName, final boolean sendLocalTimestamp, final boolean sendLocalName) {
final StringBuffer buffer = new StringBuffer();
appendPriority(buffer, facility, level);
buffer.append(VERSION);
buffer.append(' ');
getDateTimeFormatter().printTo(buffer, System.currentTimeMillis());
buffer.append(' ');
appendLocalName(buffer, localName);
buffer.append(StructuredSyslogMessage.nilProtect(this.applicationName))
.append(' ');
buffer.append(StructuredSyslogMessage.nilProtect(this.processId)).append(' ');
return buffer.toString();
}
}

View File

@ -13,379 +13,379 @@ import org.graylog2.syslog4j.impl.message.AbstractSyslogMessage;
* support for turning POJO (Plain Ol' Java Objects) into Syslog messages. It
* adds support for structured syslog messages as specified by
* draft-ietf-syslog-protocol-23. More information here:
*
* <p/>
* <p>
* http://tools.ietf.org/html/draft-ietf-syslog-protocol-23#section-6
* </p>
*
* <p/>
* <p>
* Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy of the
* LGPL license is available in the META-INF folder in all distributions of
* Syslog4j and in the base directory of the "doc" ZIP.
* </p>
*
*
* @author Manish Motwani
* @version $Id: StructuredSyslogMessage.java,v 1.5 2010/09/11 16:49:24 cvs Exp $
*/
public class StructuredSyslogMessage extends AbstractSyslogMessage implements StructuredSyslogMessageIF {
private static final long serialVersionUID = 3669887659567965965L;
private static final long serialVersionUID = 3669887659567965965L;
private String messageId;
private Map structuredData;
private String message;
private String messageId;
private Map structuredData;
private String message;
private StructuredSyslogMessage() {
this.messageId = null;
this.message = null;
this.structuredData = null;
}
private StructuredSyslogMessage() {
this.messageId = null;
this.message = null;
this.structuredData = null;
}
/**
* Constructs the {@link StructuredSyslogMessage} using MSGID,
* STRUCTURED-DATA and MSG fields, as described in:
*
* <p>
* http://tools.ietf.org/html/draft-ietf-syslog-protocol-23#section-6
* </p>
*
* The Map must be a String -> (Map of String -> String), which encompasses
* the STRUCTURED-DATA field described in above document.
*
* @param messageId
* @param structuredData
* @param message
*/
public StructuredSyslogMessage(final String messageId,
final Map structuredData, final String message) {
super();
this.messageId = messageId;
this.structuredData = structuredData;
this.message = message;
/**
* Constructs the {@link StructuredSyslogMessage} using MSGID,
* STRUCTURED-DATA and MSG fields, as described in:
* <p/>
* <p>
* http://tools.ietf.org/html/draft-ietf-syslog-protocol-23#section-6
* </p>
* <p/>
* The Map must be a String -> (Map of String -> String), which encompasses
* the STRUCTURED-DATA field described in above document.
*
* @param messageId
* @param structuredData
* @param message
*/
public StructuredSyslogMessage(final String messageId,
final Map structuredData, final String message) {
super();
this.messageId = messageId;
this.structuredData = structuredData;
this.message = message;
ensureCorrectMapType();
}
ensureCorrectMapType();
}
private void ensureCorrectMapType() {
if (!(getStructuredData() == null)) {
Set sdEntrySet = getStructuredData().entrySet();
for (Iterator it = sdEntrySet.iterator(); it.hasNext();) {
Map.Entry sdEntry = (Map.Entry) it.next();
if (!(sdEntry.getKey() instanceof String)) {
throw new IllegalArgumentException(
"Structured data map must be a map of String -> (Map of String,String)");
}
if (!(sdEntry.getValue() instanceof Map)) {
throw new IllegalArgumentException(
"Structured data map must be a map of String -> (Map of String,String)");
}
private void ensureCorrectMapType() {
if (!(getStructuredData() == null)) {
Set sdEntrySet = getStructuredData().entrySet();
for (Iterator it = sdEntrySet.iterator(); it.hasNext(); ) {
Map.Entry sdEntry = (Map.Entry) it.next();
if (!(sdEntry.getKey() instanceof String)) {
throw new IllegalArgumentException(
"Structured data map must be a map of String -> (Map of String,String)");
}
if (!(sdEntry.getValue() instanceof Map)) {
throw new IllegalArgumentException(
"Structured data map must be a map of String -> (Map of String,String)");
}
Set entrySet = ((Map) sdEntry.getValue()).entrySet();
for (Iterator it2 = entrySet.iterator(); it2.hasNext();) {
Map.Entry entry = (Map.Entry) it2.next();
Set entrySet = ((Map) sdEntry.getValue()).entrySet();
for (Iterator it2 = entrySet.iterator(); it2.hasNext(); ) {
Map.Entry entry = (Map.Entry) it2.next();
if (!(entry.getKey() instanceof String)) {
throw new IllegalArgumentException(
"Structured data map must be a map of String -> (Map of String,String)");
}
if (!(entry.getValue() instanceof String)) {
throw new IllegalArgumentException(
"Structured data map must be a map of String -> (Map of String,String)");
}
}
}
if (!(entry.getKey() instanceof String)) {
throw new IllegalArgumentException(
"Structured data map must be a map of String -> (Map of String,String)");
}
if (!(entry.getValue() instanceof String)) {
throw new IllegalArgumentException(
"Structured data map must be a map of String -> (Map of String,String)");
}
}
}
}
}
}
}
/**
* Parses and loads a {@link StructuredSyslogMessage} from string.
*
* @param syslogMessageStr
* @return Returns an instance of StructuredSyslogMessage.
*/
public static StructuredSyslogMessage fromString(
final String syslogMessageStr) {
final StructuredSyslogMessage syslogMessage = new StructuredSyslogMessage();
syslogMessage.deserialize(syslogMessageStr);
return syslogMessage;
}
/**
* Parses and loads a {@link StructuredSyslogMessage} from string.
*
* @param syslogMessageStr
* @return Returns an instance of StructuredSyslogMessage.
*/
public static StructuredSyslogMessage fromString(
final String syslogMessageStr) {
final StructuredSyslogMessage syslogMessage = new StructuredSyslogMessage();
syslogMessage.deserialize(syslogMessageStr);
return syslogMessage;
}
private void deserialize(final String stringMessage) {
// Check correct format
if (stringMessage.indexOf('[') <= 0)
throw new IllegalArgumentException("Invalid Syslog string format: "
+ stringMessage);
private void deserialize(final String stringMessage) {
// Check correct format
if (stringMessage.indexOf('[') <= 0)
throw new IllegalArgumentException("Invalid Syslog string format: "
+ stringMessage);
// Divide the string in 2 sections
final String syslogHeader = stringMessage.substring(0, stringMessage
.indexOf('['));
String structuredDataString = stringMessage.substring(stringMessage
.indexOf('['), stringMessage.lastIndexOf(']') + 1);
if ((stringMessage.lastIndexOf(']') + 2) <= stringMessage.length())
this.message = stringMessage.substring(stringMessage.lastIndexOf(']') + 2);
else {
this.message = "";
}
// Split into tokens
final String[] tokens = syslogHeader.split(" ");
// Divide the string in 2 sections
final String syslogHeader = stringMessage.substring(0, stringMessage
.indexOf('['));
String structuredDataString = stringMessage.substring(stringMessage
.indexOf('['), stringMessage.lastIndexOf(']') + 1);
// Check number of tokens must be 1 -- rest of the header should already
// be stripped
if (tokens.length != 1) {
throw new IllegalArgumentException("Invalid Syslog string format: "
+ stringMessage);
}
if ((stringMessage.lastIndexOf(']') + 2) <= stringMessage.length())
this.message = stringMessage.substring(stringMessage.lastIndexOf(']') + 2);
this.messageId = SyslogConstants.STRUCTURED_DATA_NILVALUE.equals(tokens[0]) ? null
: tokens[0];
else {
this.message = "";
}
this.structuredData = new HashMap();
if (!SyslogConstants.STRUCTURED_DATA_EMPTY_VALUE.equals(structuredDataString)) {
while (!"".equals(structuredDataString)) {
if (!structuredDataString.startsWith("[")
|| structuredDataString.indexOf(']') == -1) {
throw new IllegalArgumentException(
"Invalid structured data format in Syslog message: "
+ stringMessage);
}
// Split into tokens
final String[] tokens = syslogHeader.split(" ");
final String structuredDataIteration = structuredDataString
.substring(1, structuredDataString.indexOf(']'));
// Check number of tokens must be 1 -- rest of the header should already
// be stripped
if (tokens.length != 1) {
throw new IllegalArgumentException("Invalid Syslog string format: "
+ stringMessage);
}
final Map iterMap = new HashMap();
this.messageId = SyslogConstants.STRUCTURED_DATA_NILVALUE.equals(tokens[0]) ? null
: tokens[0];
final String[] params = structuredDataIteration.split(" ");
this.structuredData = new HashMap();
if (!SyslogConstants.STRUCTURED_DATA_EMPTY_VALUE.equals(structuredDataString)) {
while (!"".equals(structuredDataString)) {
if (!structuredDataString.startsWith("[")
|| structuredDataString.indexOf(']') == -1) {
throw new IllegalArgumentException(
"Invalid structured data format in Syslog message: "
+ stringMessage);
}
for (int i = 1; i < params.length; i++) {
final String[] paramIter = params[i].split("=");
if (paramIter.length != 2) {
throw new IllegalArgumentException(
"Invalid structured data format in Syslog message: "
+ stringMessage);
}
final String structuredDataIteration = structuredDataString
.substring(1, structuredDataString.indexOf(']'));
if (!paramIter[1].startsWith("\"")
|| !paramIter[1].endsWith("\"")) {
throw new IllegalArgumentException(
"Invalid structured data format in Syslog message: "
+ stringMessage);
}
final Map iterMap = new HashMap();
iterMap.put(paramIter[0], paramIter[1].substring(1,
paramIter[1].length() - 1));
}
final String[] params = structuredDataIteration.split(" ");
this.structuredData.put(params[0], iterMap);
for (int i = 1; i < params.length; i++) {
final String[] paramIter = params[i].split("=");
if (paramIter.length != 2) {
throw new IllegalArgumentException(
"Invalid structured data format in Syslog message: "
+ stringMessage);
}
if (structuredDataString.indexOf(']') != structuredDataString
.lastIndexOf(']')) {
structuredDataString = structuredDataString
.substring(structuredDataString.indexOf(']') + 1);
} else {
structuredDataString = "";
}
}
}
}
if (!paramIter[1].startsWith("\"")
|| !paramIter[1].endsWith("\"")) {
throw new IllegalArgumentException(
"Invalid structured data format in Syslog message: "
+ stringMessage);
}
/**
* Returns the MSGID field of the structured message format, as described
* in:
*
* <p>
* http://tools.ietf.org/html/draft-ietf-syslog-protocol-23#section-6
* </p>
*
* @return Returns the MSG ID field.
*/
public String getMessageId() {
return this.messageId;
}
iterMap.put(paramIter[0], paramIter[1].substring(1,
paramIter[1].length() - 1));
}
/**
* Returns the structured data map. The Map is a String -> (Map of String ->
* String), which encompasses the STRUCTURED-DATA field, as described in:
*
* <p>
* http://tools.ietf.org/html/draft-ietf-syslog-protocol-23#section-6
* </p>
*
* @return Returns a Map object containing structured data.
*/
public Map getStructuredData() {
return this.structuredData;
}
this.structuredData.put(params[0], iterMap);
/**
* Returns the MSG field of the structured message format, as described in:
*
* <p>
* http://tools.ietf.org/html/draft-ietf-syslog-protocol-23#section-6
* </p>
*
* @return Returns the MSG field.
*/
public String getMessage() {
return this.message;
}
if (structuredDataString.indexOf(']') != structuredDataString
.lastIndexOf(']')) {
structuredDataString = structuredDataString
.substring(structuredDataString.indexOf(']') + 1);
} else {
structuredDataString = "";
}
}
}
}
/*
* (non-Javadoc)
*
* @seeorg.productivity.java.syslog4j.impl.message.AbstractSyslogMessage#
* createMessage()
*/
public String createMessage() {
return serialize();
}
/**
* Returns the MSGID field of the structured message format, as described
* in:
* <p/>
* <p>
* http://tools.ietf.org/html/draft-ietf-syslog-protocol-23#section-6
* </p>
*
* @return Returns the MSG ID field.
*/
public String getMessageId() {
return this.messageId;
}
private String serialize() {
if (!StructuredSyslogMessage.checkIsPrintable(getMessageId()))
throw new IllegalArgumentException("Invalid message id: "
+ getMessageId());
/**
* Returns the structured data map. The Map is a String -> (Map of String ->
* String), which encompasses the STRUCTURED-DATA field, as described in:
* <p/>
* <p>
* http://tools.ietf.org/html/draft-ietf-syslog-protocol-23#section-6
* </p>
*
* @return Returns a Map object containing structured data.
*/
public Map getStructuredData() {
return this.structuredData;
}
final StringBuffer sb = new StringBuffer();
/**
* Returns the MSG field of the structured message format, as described in:
* <p/>
* <p>
* http://tools.ietf.org/html/draft-ietf-syslog-protocol-23#section-6
* </p>
*
* @return Returns the MSG field.
*/
public String getMessage() {
return this.message;
}
sb.append(StructuredSyslogMessage.nilProtect(getMessageId()));
sb.append(' ');
/*
* (non-Javadoc)
*
* @seeorg.productivity.java.syslog4j.impl.message.AbstractSyslogMessage#
* createMessage()
*/
public String createMessage() {
return serialize();
}
if (getStructuredData() == null || getStructuredData().size() == 0) {
// This is not desired, but rsyslogd does not store version 1 syslog
// message correctly if
// there is no
// structured data present
sb.append(SyslogConstants.STRUCTURED_DATA_EMPTY_VALUE);
} else {
Set sdEntrySet = getStructuredData().entrySet();
for (Iterator it = sdEntrySet.iterator(); it.hasNext();) {
final Map.Entry sdElement = (Map.Entry) it.next();
final String sdId = (String) sdElement.getKey();
private String serialize() {
if (!StructuredSyslogMessage.checkIsPrintable(getMessageId()))
throw new IllegalArgumentException("Invalid message id: "
+ getMessageId());
if (sdId == null || sdId.length() == 0
|| !StructuredSyslogMessage.checkIsPrintable(sdId)) {
throw new IllegalArgumentException(
"Illegal structured data id: " + sdId);
}
final StringBuffer sb = new StringBuffer();
sb.append('[').append(sdId);
sb.append(StructuredSyslogMessage.nilProtect(getMessageId()));
sb.append(' ');
final Map sdParams = (Map) sdElement.getValue();
if (getStructuredData() == null || getStructuredData().size() == 0) {
// This is not desired, but rsyslogd does not store version 1 syslog
// message correctly if
// there is no
// structured data present
sb.append(SyslogConstants.STRUCTURED_DATA_EMPTY_VALUE);
} else {
Set sdEntrySet = getStructuredData().entrySet();
for (Iterator it = sdEntrySet.iterator(); it.hasNext(); ) {
final Map.Entry sdElement = (Map.Entry) it.next();
final String sdId = (String) sdElement.getKey();
if (sdParams != null) {
Set entrySet = sdParams.entrySet();
for (Iterator it2 = entrySet.iterator(); it2.hasNext();) {
Map.Entry entry = (Map.Entry) it2.next();
final String paramName = (String) entry.getKey();
final String paramValue = (String) entry.getValue();
if (sdId == null || sdId.length() == 0
|| !StructuredSyslogMessage.checkIsPrintable(sdId)) {
throw new IllegalArgumentException(
"Illegal structured data id: " + sdId);
}
if (paramName == null
|| paramName.length() == 0
|| !StructuredSyslogMessage
.checkIsPrintable(paramName))
throw new IllegalArgumentException(
"Illegal structured data parameter name: "
+ paramName);
sb.append('[').append(sdId);
if (paramValue == null)
throw new IllegalArgumentException(
"Null structured data parameter value for parameter name: "
+ paramName);
final Map sdParams = (Map) sdElement.getValue();
sb.append(' ');
sb.append(paramName);
sb.append('=').append('"');
StructuredSyslogMessage.sdEscape(sb, paramValue);
sb.append('"');
}
}
if (sdParams != null) {
Set entrySet = sdParams.entrySet();
for (Iterator it2 = entrySet.iterator(); it2.hasNext(); ) {
Map.Entry entry = (Map.Entry) it2.next();
final String paramName = (String) entry.getKey();
final String paramValue = (String) entry.getValue();
sb.append(']');
}
}
if (paramName == null
|| paramName.length() == 0
|| !StructuredSyslogMessage
.checkIsPrintable(paramName))
throw new IllegalArgumentException(
"Illegal structured data parameter name: "
+ paramName);
if (getMessage() != null && getMessage().length() != 0) {
sb.append(' ');
sb.append(StructuredSyslogMessage.nilProtect(getMessage()));
}
if (paramValue == null)
throw new IllegalArgumentException(
"Null structured data parameter value for parameter name: "
+ paramName);
return sb.toString();
sb.append(' ');
sb.append(paramName);
sb.append('=').append('"');
StructuredSyslogMessage.sdEscape(sb, paramValue);
sb.append('"');
}
}
}
sb.append(']');
}
}
public static void sdEscape(final StringBuffer sb, final String value) {
for (int i = 0; i < value.length(); i++) {
final char c = value.charAt(i);
if (getMessage() != null && getMessage().length() != 0) {
sb.append(' ');
sb.append(StructuredSyslogMessage.nilProtect(getMessage()));
}
if (c == '"' || c == '\\' || c == ']') {
sb.append('\\');
}
return sb.toString();
sb.append(c);
}
}
}
public static boolean checkIsPrintable(final String value) {
if (value == null)
return true;
public static void sdEscape(final StringBuffer sb, final String value) {
for (int i = 0; i < value.length(); i++) {
final char c = value.charAt(i);
for (int i = 0; i < value.length(); i++) {
final char c = value.charAt(i);
if (c == '"' || c == '\\' || c == ']') {
sb.append('\\');
}
if (c < 33 || c > 126)
return false;
}
sb.append(c);
}
}
return true;
}
public static boolean checkIsPrintable(final String value) {
if (value == null)
return true;
public static String nilProtect(final String value) {
if (value == null || value.trim().length() == 0) {
return SyslogConstants.STRUCTURED_DATA_NILVALUE;
}
for (int i = 0; i < value.length(); i++) {
final char c = value.charAt(i);
return value;
}
if (c < 33 || c > 126)
return false;
}
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((message == null) ? 0 : message.hashCode());
result = prime * result
+ ((messageId == null) ? 0 : messageId.hashCode());
result = prime * result
+ ((structuredData == null) ? 0 : structuredData.hashCode());
return result;
}
return true;
}
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
StructuredSyslogMessage other = (StructuredSyslogMessage) obj;
if (message == null) {
if (other.message != null) return false;
} else if (!message.equals(other.message)) return false;
if (messageId == null) {
if (other.messageId != null) return false;
} else if (!messageId.equals(other.messageId)) return false;
if (structuredData == null) {
if (other.structuredData != null) return false;
} else if (!structuredData.equals(other.structuredData)) return false;
return true;
}
public static String nilProtect(final String value) {
if (value == null || value.trim().length() == 0) {
return SyslogConstants.STRUCTURED_DATA_NILVALUE;
}
public String toString() {
return serialize();
}
return value;
}
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((message == null) ? 0 : message.hashCode());
result = prime * result
+ ((messageId == null) ? 0 : messageId.hashCode());
result = prime * result
+ ((structuredData == null) ? 0 : structuredData.hashCode());
return result;
}
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
StructuredSyslogMessage other = (StructuredSyslogMessage) obj;
if (message == null) {
if (other.message != null) return false;
} else if (!message.equals(other.message)) return false;
if (messageId == null) {
if (other.messageId != null) return false;
} else if (!messageId.equals(other.messageId)) return false;
if (structuredData == null) {
if (other.structuredData != null) return false;
} else if (!structuredData.equals(other.structuredData)) return false;
return true;
}
public String toString() {
return serialize();
}
}

View File

@ -3,16 +3,16 @@ package org.graylog2.syslog4j.impl.message.structured;
import org.graylog2.syslog4j.SyslogMessageIF;
/**
* StructuredSyslogMessageIF is a "marker" interface to identify structured
* SyslogMessageIF implementations.
*
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: StructuredSyslogMessageIF.java,v 1.1 2009/07/22 15:54:23 cvs Exp $
*/
* StructuredSyslogMessageIF is a "marker" interface to identify structured
* SyslogMessageIF implementations.
* <p/>
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: StructuredSyslogMessageIF.java,v 1.1 2009/07/22 15:54:23 cvs Exp $
*/
public interface StructuredSyslogMessageIF extends SyslogMessageIF {
//
//
}

View File

@ -9,166 +9,166 @@ import org.graylog2.syslog4j.SyslogMessageProcessorIF;
import org.graylog2.syslog4j.SyslogRuntimeException;
/**
* MultipleSyslog is an aggregator Syslog implementation for allowing a single
* Syslog call to send to multiple Syslog implementations.
*
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: MultipleSyslog.java,v 1.10 2010/02/11 05:00:55 cvs Exp $
*/
* MultipleSyslog is an aggregator Syslog implementation for allowing a single
* Syslog call to send to multiple Syslog implementations.
* <p/>
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: MultipleSyslog.java,v 1.10 2010/02/11 05:00:55 cvs Exp $
*/
public class MultipleSyslog implements SyslogIF {
private static final long serialVersionUID = 587308197526365108L;
private static final long serialVersionUID = 587308197526365108L;
protected String syslogProtocol = null;
protected MultipleSyslogConfig multipleSyslogConfig = null;
protected String syslogProtocol = null;
protected MultipleSyslogConfig multipleSyslogConfig = null;
public void initialize(String protocol, SyslogConfigIF config) throws SyslogRuntimeException {
this.syslogProtocol = protocol;
try {
this.multipleSyslogConfig = (MultipleSyslogConfig) config;
} catch (ClassCastException cce) {
throw new SyslogRuntimeException("config must be of type MultipleSyslogConfig");
}
}
public void initialize(String protocol, SyslogConfigIF config) throws SyslogRuntimeException {
this.syslogProtocol = protocol;
public SyslogConfigIF getConfig() {
return this.multipleSyslogConfig;
}
try {
this.multipleSyslogConfig = (MultipleSyslogConfig) config;
public void debug(String message) {
log(SyslogConstants.LEVEL_DEBUG,message);
}
} catch (ClassCastException cce) {
throw new SyslogRuntimeException("config must be of type MultipleSyslogConfig");
}
}
public void debug(SyslogMessageIF message) {
log(SyslogConstants.LEVEL_DEBUG,message);
}
public SyslogConfigIF getConfig() {
return this.multipleSyslogConfig;
}
public void critical(String message) {
log(SyslogConstants.LEVEL_CRITICAL,message);
}
public void debug(String message) {
log(SyslogConstants.LEVEL_DEBUG, message);
}
public void critical(SyslogMessageIF message) {
log(SyslogConstants.LEVEL_CRITICAL,message);
}
public void debug(SyslogMessageIF message) {
log(SyslogConstants.LEVEL_DEBUG, message);
}
public void error(String message) {
log(SyslogConstants.LEVEL_ERROR,message);
}
public void critical(String message) {
log(SyslogConstants.LEVEL_CRITICAL, message);
}
public void error(SyslogMessageIF message) {
log(SyslogConstants.LEVEL_ERROR,message);
}
public void critical(SyslogMessageIF message) {
log(SyslogConstants.LEVEL_CRITICAL, message);
}
public void alert(String message) {
log(SyslogConstants.LEVEL_ALERT,message);
}
public void error(String message) {
log(SyslogConstants.LEVEL_ERROR, message);
}
public void alert(SyslogMessageIF message) {
log(SyslogConstants.LEVEL_ALERT,message);
}
public void error(SyslogMessageIF message) {
log(SyslogConstants.LEVEL_ERROR, message);
}
public void notice(String message) {
log(SyslogConstants.LEVEL_NOTICE,message);
}
public void alert(String message) {
log(SyslogConstants.LEVEL_ALERT, message);
}
public void notice(SyslogMessageIF message) {
log(SyslogConstants.LEVEL_NOTICE,message);
}
public void alert(SyslogMessageIF message) {
log(SyslogConstants.LEVEL_ALERT, message);
}
public void emergency(String message) {
log(SyslogConstants.LEVEL_EMERGENCY,message);
}
public void notice(String message) {
log(SyslogConstants.LEVEL_NOTICE, message);
}
public void emergency(SyslogMessageIF message) {
log(SyslogConstants.LEVEL_EMERGENCY,message);
}
public void notice(SyslogMessageIF message) {
log(SyslogConstants.LEVEL_NOTICE, message);
}
public void info(String message) {
log(SyslogConstants.LEVEL_INFO,message);
}
public void emergency(String message) {
log(SyslogConstants.LEVEL_EMERGENCY, message);
}
public void info(SyslogMessageIF message) {
log(SyslogConstants.LEVEL_INFO,message);
}
public void emergency(SyslogMessageIF message) {
log(SyslogConstants.LEVEL_EMERGENCY, message);
}
public void warn(String message) {
log(SyslogConstants.LEVEL_WARN,message);
}
public void info(String message) {
log(SyslogConstants.LEVEL_INFO, message);
}
public void warn(SyslogMessageIF message) {
log(SyslogConstants.LEVEL_WARN,message);
}
public void info(SyslogMessageIF message) {
log(SyslogConstants.LEVEL_INFO, message);
}
public void log(int level, String message) {
for(int i=0; i<this.multipleSyslogConfig.getProtocols().size(); i++) {
String protocol = (String) this.multipleSyslogConfig.getProtocols().get(i);
SyslogIF syslog = Syslog.getInstance(protocol);
syslog.log(level,message);
}
}
public void warn(String message) {
log(SyslogConstants.LEVEL_WARN, message);
}
public void log(int level, SyslogMessageIF message) {
for(int i=0; i<this.multipleSyslogConfig.getProtocols().size(); i++) {
String protocol = (String) this.multipleSyslogConfig.getProtocols().get(i);
SyslogIF syslog = Syslog.getInstance(protocol);
syslog.log(level,message);
}
}
public void warn(SyslogMessageIF message) {
log(SyslogConstants.LEVEL_WARN, message);
}
public void flush() throws SyslogRuntimeException {
for(int i=0; i<this.multipleSyslogConfig.getProtocols().size(); i++) {
String protocol = (String) this.multipleSyslogConfig.getProtocols().get(i);
SyslogIF syslog = Syslog.getInstance(protocol);
syslog.flush();
}
}
public void log(int level, String message) {
for (int i = 0; i < this.multipleSyslogConfig.getProtocols().size(); i++) {
String protocol = (String) this.multipleSyslogConfig.getProtocols().get(i);
public void shutdown() throws SyslogRuntimeException {
for(int i=0; i<this.multipleSyslogConfig.getProtocols().size(); i++) {
String protocol = (String) this.multipleSyslogConfig.getProtocols().get(i);
SyslogIF syslog = Syslog.getInstance(protocol);
syslog.shutdown();
}
}
public void backLog(int level, String message, Throwable reasonThrowable) {
// MultipleSyslog is an aggregator; backLog state will be handled by individual Syslog protocols
}
SyslogIF syslog = Syslog.getInstance(protocol);
public void backLog(int level, String message, String reason) {
// MultipleSyslog is an aggregator; backLog state will be handled by individual Syslog protocols
}
syslog.log(level, message);
}
}
public void setMessageProcessor(SyslogMessageProcessorIF messageProcessor) {
throw new SyslogRuntimeException("MultipleSyslog is an aggregator; please set the individual protocols");
}
public void log(int level, SyslogMessageIF message) {
for (int i = 0; i < this.multipleSyslogConfig.getProtocols().size(); i++) {
String protocol = (String) this.multipleSyslogConfig.getProtocols().get(i);
public SyslogMessageProcessorIF getMessageProcessor() {
throw new SyslogRuntimeException("MultipleSyslog is an aggregator; please set the individual protocols");
}
SyslogIF syslog = Syslog.getInstance(protocol);
public void setStructuredMessageProcessor(SyslogMessageProcessorIF messageProcessor) {
throw new SyslogRuntimeException("MultipleSyslog is an aggregator; please set the individual protocols");
}
syslog.log(level, message);
}
}
public SyslogMessageProcessorIF getStructuredMessageProcessor() {
throw new SyslogRuntimeException("MultipleSyslog is an aggregator; please set the individual protocols");
}
public void flush() throws SyslogRuntimeException {
for (int i = 0; i < this.multipleSyslogConfig.getProtocols().size(); i++) {
String protocol = (String) this.multipleSyslogConfig.getProtocols().get(i);
public String getProtocol() {
return this.syslogProtocol;
}
SyslogIF syslog = Syslog.getInstance(protocol);
syslog.flush();
}
}
public void shutdown() throws SyslogRuntimeException {
for (int i = 0; i < this.multipleSyslogConfig.getProtocols().size(); i++) {
String protocol = (String) this.multipleSyslogConfig.getProtocols().get(i);
SyslogIF syslog = Syslog.getInstance(protocol);
syslog.shutdown();
}
}
public void backLog(int level, String message, Throwable reasonThrowable) {
// MultipleSyslog is an aggregator; backLog state will be handled by individual Syslog protocols
}
public void backLog(int level, String message, String reason) {
// MultipleSyslog is an aggregator; backLog state will be handled by individual Syslog protocols
}
public void setMessageProcessor(SyslogMessageProcessorIF messageProcessor) {
throw new SyslogRuntimeException("MultipleSyslog is an aggregator; please set the individual protocols");
}
public SyslogMessageProcessorIF getMessageProcessor() {
throw new SyslogRuntimeException("MultipleSyslog is an aggregator; please set the individual protocols");
}
public void setStructuredMessageProcessor(SyslogMessageProcessorIF messageProcessor) {
throw new SyslogRuntimeException("MultipleSyslog is an aggregator; please set the individual protocols");
}
public SyslogMessageProcessorIF getStructuredMessageProcessor() {
throw new SyslogRuntimeException("MultipleSyslog is an aggregator; please set the individual protocols");
}
public String getProtocol() {
return this.syslogProtocol;
}
}

View File

@ -10,232 +10,232 @@ import org.graylog2.syslog4j.SyslogMessageModifierIF;
import org.graylog2.syslog4j.SyslogRuntimeException;
/**
* MultipleSyslogConfig is a configuration Object for allowing a single
* Syslog call to send to multiple Syslog implementations.
*
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: MultipleSyslogConfig.java,v 1.8 2010/11/28 04:15:18 cvs Exp $
*/
* MultipleSyslogConfig is a configuration Object for allowing a single
* Syslog call to send to multiple Syslog implementations.
* <p/>
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: MultipleSyslogConfig.java,v 1.8 2010/11/28 04:15:18 cvs Exp $
*/
public class MultipleSyslogConfig implements SyslogConfigIF {
private static final long serialVersionUID = 753704522364959612L;
protected List syslogProtocols = null;
public MultipleSyslogConfig() {
this.syslogProtocols = new ArrayList();
}
private static final long serialVersionUID = 753704522364959612L;
public MultipleSyslogConfig(List protocols) {
if (protocols != null) {
this.syslogProtocols = protocols;
} else {
this.syslogProtocols = new ArrayList();
}
}
protected List syslogProtocols = null;
public MultipleSyslogConfig(String[] protocols) {
if (protocols != null) {
this.syslogProtocols = new ArrayList(protocols.length);
for(int i=0; i<protocols.length; i++) {
this.syslogProtocols.add(protocols[i]);
}
} else {
this.syslogProtocols = new ArrayList();
}
}
public List getProtocols() {
return this.syslogProtocols;
}
public MultipleSyslogConfig() {
this.syslogProtocols = new ArrayList();
}
public void addProtocol(String protocol) {
this.syslogProtocols.add(protocol);
}
public MultipleSyslogConfig(List protocols) {
if (protocols != null) {
this.syslogProtocols = protocols;
public void insertProtocol(int index, String protocol) {
this.syslogProtocols.add(index,protocol);
}
} else {
this.syslogProtocols = new ArrayList();
}
}
public void removeProtocol(String protocol) {
this.syslogProtocols.remove(protocol);
}
public MultipleSyslogConfig(String[] protocols) {
if (protocols != null) {
this.syslogProtocols = new ArrayList(protocols.length);
public void removeAllProtocols() {
this.syslogProtocols.clear();
}
for (int i = 0; i < protocols.length; i++) {
this.syslogProtocols.add(protocols[i]);
}
public void addBackLogHandler(SyslogBackLogHandlerIF backLogHandler) {
throw new SyslogRuntimeException("MultipleSyslog is an aggregator; please set the individual protocols");
}
} else {
this.syslogProtocols = new ArrayList();
}
}
public void addMessageModifier(SyslogMessageModifierIF messageModifier) {
throw new SyslogRuntimeException("MultipleSyslog is an aggregator; please set the individual protocols");
}
public List getProtocols() {
return this.syslogProtocols;
}
public Class getSyslogClass() {
return MultipleSyslog.class;
}
public void addProtocol(String protocol) {
this.syslogProtocols.add(protocol);
}
public String getCharSet() {
return SyslogConstants.CHAR_SET_DEFAULT;
}
public void insertProtocol(int index, String protocol) {
this.syslogProtocols.add(index, protocol);
}
public int getFacility() {
return SyslogConstants.SYSLOG_FACILITY_DEFAULT;
}
public void removeProtocol(String protocol) {
this.syslogProtocols.remove(protocol);
}
public String getHost() {
return SyslogConstants.SYSLOG_HOST_DEFAULT;
}
public void removeAllProtocols() {
this.syslogProtocols.clear();
}
public String getIdent() {
return null;
}
public String getLocalName() {
return null;
}
public void addBackLogHandler(SyslogBackLogHandlerIF backLogHandler) {
throw new SyslogRuntimeException("MultipleSyslog is an aggregator; please set the individual protocols");
}
public int getPort() {
return SyslogConstants.SYSLOG_PORT_DEFAULT;
}
public int getMaxShutdownWait() {
return SyslogConstants.MAX_SHUTDOWN_WAIT_DEFAULT;
}
public void addMessageModifier(SyslogMessageModifierIF messageModifier) {
throw new SyslogRuntimeException("MultipleSyslog is an aggregator; please set the individual protocols");
}
public void setMaxShutdownWait(int maxShutdownWait) {
throw new SyslogRuntimeException("MultipleSyslog is an aggregator; please set the individual protocols");
}
public Class getSyslogClass() {
return MultipleSyslog.class;
}
public void insertBackLogHandler(int index, SyslogBackLogHandlerIF backLogHandler) {
throw new SyslogRuntimeException("MultipleSyslog is an aggregator; please set the individual protocols");
}
public String getCharSet() {
return SyslogConstants.CHAR_SET_DEFAULT;
}
public void insertMessageModifier(int index, SyslogMessageModifierIF messageModifier) {
throw new SyslogRuntimeException("MultipleSyslog is an aggregator; please set the individual protocols");
}
public int getFacility() {
return SyslogConstants.SYSLOG_FACILITY_DEFAULT;
}
public boolean isCacheHostAddress() {
return SyslogConstants.CACHE_HOST_ADDRESS_DEFAULT;
}
public String getHost() {
return SyslogConstants.SYSLOG_HOST_DEFAULT;
}
public boolean isIncludeIdentInMessageModifier() {
return SyslogConstants.INCLUDE_IDENT_IN_MESSAGE_MODIFIER_DEFAULT;
}
public String getIdent() {
return null;
}
public boolean isSendLocalName() {
return SyslogConstants.SEND_LOCAL_NAME_DEFAULT;
}
public String getLocalName() {
return null;
}
public boolean isSendLocalTimestamp() {
return SyslogConstants.SEND_LOCAL_TIMESTAMP_DEFAULT;
}
public int getPort() {
return SyslogConstants.SYSLOG_PORT_DEFAULT;
}
public boolean isThrowExceptionOnInitialize() {
return SyslogConstants.THROW_EXCEPTION_ON_INITIALIZE_DEFAULT;
}
public int getMaxShutdownWait() {
return SyslogConstants.MAX_SHUTDOWN_WAIT_DEFAULT;
}
public boolean isThrowExceptionOnWrite() {
return SyslogConstants.THROW_EXCEPTION_ON_WRITE_DEFAULT;
}
public void setMaxShutdownWait(int maxShutdownWait) {
throw new SyslogRuntimeException("MultipleSyslog is an aggregator; please set the individual protocols");
}
public void removeAllBackLogHandlers() {
throw new SyslogRuntimeException("MultipleSyslog is an aggregator; please set the individual protocols");
}
public void insertBackLogHandler(int index, SyslogBackLogHandlerIF backLogHandler) {
throw new SyslogRuntimeException("MultipleSyslog is an aggregator; please set the individual protocols");
}
public void removeAllMessageModifiers() {
throw new SyslogRuntimeException("MultipleSyslog is an aggregator; please set the individual protocols");
}
public void insertMessageModifier(int index, SyslogMessageModifierIF messageModifier) {
throw new SyslogRuntimeException("MultipleSyslog is an aggregator; please set the individual protocols");
}
public void removeBackLogHandler(SyslogBackLogHandlerIF backLogHandler) {
throw new SyslogRuntimeException("MultipleSyslog is an aggregator; please set the individual protocols");
}
public boolean isCacheHostAddress() {
return SyslogConstants.CACHE_HOST_ADDRESS_DEFAULT;
}
public void removeMessageModifier(SyslogMessageModifierIF messageModifier) {
throw new SyslogRuntimeException("MultipleSyslog is an aggregator; please set the individual protocols");
}
public boolean isIncludeIdentInMessageModifier() {
return SyslogConstants.INCLUDE_IDENT_IN_MESSAGE_MODIFIER_DEFAULT;
}
public void setCacheHostAddress(boolean cacheHostAddress) {
throw new SyslogRuntimeException("MultipleSyslog is an aggregator; please set the individual protocols");
}
public boolean isSendLocalName() {
return SyslogConstants.SEND_LOCAL_NAME_DEFAULT;
}
public void setCharSet(String charSet) {
throw new SyslogRuntimeException("MultipleSyslog is an aggregator; please set the individual protocols");
}
public boolean isSendLocalTimestamp() {
return SyslogConstants.SEND_LOCAL_TIMESTAMP_DEFAULT;
}
public void setFacility(int facility) {
throw new SyslogRuntimeException("MultipleSyslog is an aggregator; please set the individual protocols");
}
public boolean isThrowExceptionOnInitialize() {
return SyslogConstants.THROW_EXCEPTION_ON_INITIALIZE_DEFAULT;
}
public void setFacility(String facilityName) {
throw new SyslogRuntimeException("MultipleSyslog is an aggregator; please set the individual protocols");
}
public boolean isThrowExceptionOnWrite() {
return SyslogConstants.THROW_EXCEPTION_ON_WRITE_DEFAULT;
}
public void setHost(String host) throws SyslogRuntimeException {
throw new SyslogRuntimeException("MultipleSyslog is an aggregator; please set the individual protocols");
}
public void removeAllBackLogHandlers() {
throw new SyslogRuntimeException("MultipleSyslog is an aggregator; please set the individual protocols");
}
public void setIdent(String ident) {
throw new SyslogRuntimeException("MultipleSyslog is an aggregator; please set the individual protocols");
}
public void removeAllMessageModifiers() {
throw new SyslogRuntimeException("MultipleSyslog is an aggregator; please set the individual protocols");
}
public void setLocalName(String localName) {
throw new SyslogRuntimeException("MultipleSyslog is an aggregator; please set the individual protocols");
}
public void removeBackLogHandler(SyslogBackLogHandlerIF backLogHandler) {
throw new SyslogRuntimeException("MultipleSyslog is an aggregator; please set the individual protocols");
}
public void setIncludeIdentInMessageModifier(boolean throwExceptionOnInitialize) {
throw new SyslogRuntimeException("MultipleSyslog is an aggregator; please set the individual protocols");
}
public void removeMessageModifier(SyslogMessageModifierIF messageModifier) {
throw new SyslogRuntimeException("MultipleSyslog is an aggregator; please set the individual protocols");
}
public void setPort(int port) throws SyslogRuntimeException {
throw new SyslogRuntimeException("MultipleSyslog is an aggregator; please set the individual protocols");
}
public void setCacheHostAddress(boolean cacheHostAddress) {
throw new SyslogRuntimeException("MultipleSyslog is an aggregator; please set the individual protocols");
}
public void setSendLocalName(boolean sendLocalName) {
throw new SyslogRuntimeException("MultipleSyslog is an aggregator; please set the individual protocols");
}
public void setCharSet(String charSet) {
throw new SyslogRuntimeException("MultipleSyslog is an aggregator; please set the individual protocols");
}
public void setSendLocalTimestamp(boolean sendLocalTimestamp) {
throw new SyslogRuntimeException("MultipleSyslog is an aggregator; please set the individual protocols");
}
public void setFacility(int facility) {
throw new SyslogRuntimeException("MultipleSyslog is an aggregator; please set the individual protocols");
}
public void setThrowExceptionOnInitialize(boolean throwExceptionOnInitialize) {
throw new SyslogRuntimeException("MultipleSyslog is an aggregator; please set the individual protocols");
}
public void setFacility(String facilityName) {
throw new SyslogRuntimeException("MultipleSyslog is an aggregator; please set the individual protocols");
}
public void setThrowExceptionOnWrite(boolean throwExceptionOnWrite) {
throw new SyslogRuntimeException("MultipleSyslog is an aggregator; please set the individual protocols");
}
public void setHost(String host) throws SyslogRuntimeException {
throw new SyslogRuntimeException("MultipleSyslog is an aggregator; please set the individual protocols");
}
public int getMaxMessageLength() {
return SyslogConstants.MAX_MESSAGE_LENGTH_DEFAULT;
}
public void setIdent(String ident) {
throw new SyslogRuntimeException("MultipleSyslog is an aggregator; please set the individual protocols");
}
public void setMaxMessageLength(int maxMessageLength) {
throw new SyslogRuntimeException("MultipleSyslog is an aggregator; please set the individual protocols");
}
public void setLocalName(String localName) {
throw new SyslogRuntimeException("MultipleSyslog is an aggregator; please set the individual protocols");
}
public boolean isTruncateMessage() {
return SyslogConstants.TRUNCATE_MESSAGE_DEFAULT;
}
public void setIncludeIdentInMessageModifier(boolean throwExceptionOnInitialize) {
throw new SyslogRuntimeException("MultipleSyslog is an aggregator; please set the individual protocols");
}
public void setTruncateMessage(boolean truncateMessage) {
throw new SyslogRuntimeException("MultipleSyslog is an aggregator; please set the individual protocols");
}
public void setPort(int port) throws SyslogRuntimeException {
throw new SyslogRuntimeException("MultipleSyslog is an aggregator; please set the individual protocols");
}
public boolean isUseStructuredData() {
return SyslogConstants.USE_STRUCTURED_DATA_DEFAULT;
}
public void setSendLocalName(boolean sendLocalName) {
throw new SyslogRuntimeException("MultipleSyslog is an aggregator; please set the individual protocols");
}
public void setUseStructuredData(boolean useStructuredData) {
throw new SyslogRuntimeException("MultipleSyslog is an aggregator; please set the individual protocols");
}
public void setSendLocalTimestamp(boolean sendLocalTimestamp) {
throw new SyslogRuntimeException("MultipleSyslog is an aggregator; please set the individual protocols");
}
public void setThrowExceptionOnInitialize(boolean throwExceptionOnInitialize) {
throw new SyslogRuntimeException("MultipleSyslog is an aggregator; please set the individual protocols");
}
public void setThrowExceptionOnWrite(boolean throwExceptionOnWrite) {
throw new SyslogRuntimeException("MultipleSyslog is an aggregator; please set the individual protocols");
}
public int getMaxMessageLength() {
return SyslogConstants.MAX_MESSAGE_LENGTH_DEFAULT;
}
public void setMaxMessageLength(int maxMessageLength) {
throw new SyslogRuntimeException("MultipleSyslog is an aggregator; please set the individual protocols");
}
public boolean isTruncateMessage() {
return SyslogConstants.TRUNCATE_MESSAGE_DEFAULT;
}
public void setTruncateMessage(boolean truncateMessage) {
throw new SyslogRuntimeException("MultipleSyslog is an aggregator; please set the individual protocols");
}
public boolean isUseStructuredData() {
return SyslogConstants.USE_STRUCTURED_DATA_DEFAULT;
}
public void setUseStructuredData(boolean useStructuredData) {
throw new SyslogRuntimeException("MultipleSyslog is an aggregator; please set the individual protocols");
}
}

View File

@ -7,55 +7,55 @@ import org.graylog2.syslog4j.impl.AbstractSyslog;
import org.graylog2.syslog4j.util.SyslogUtility;
/**
* AbstractNetSyslog is an abstract extension of AbstractSyslog
* that provides support for network-based syslog clients.
*
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: AbstractNetSyslog.java,v 1.7 2009/01/24 22:00:18 cvs Exp $
*/
* AbstractNetSyslog is an abstract extension of AbstractSyslog
* that provides support for network-based syslog clients.
* <p/>
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: AbstractNetSyslog.java,v 1.7 2009/01/24 22:00:18 cvs Exp $
*/
public abstract class AbstractNetSyslog extends AbstractSyslog {
private static final long serialVersionUID = -3250858945515853967L;
protected static final Object cachedHostAddressSyncObject = new Object();
protected InetAddress cachedHostAddress = null;
protected AbstractNetSyslogConfigIF netSyslogConfig = null;
protected void initialize() throws SyslogRuntimeException {
try {
this.netSyslogConfig = (AbstractNetSyslogConfigIF) this.syslogConfig;
} catch (ClassCastException cce) {
throw new SyslogRuntimeException("config must implement interface AbstractNetSyslogConfigIF");
}
}
/**
* @return Returns an object of InetAddress of the local host, using caching if so directed.
*/
public InetAddress getHostAddress() {
InetAddress hostAddress = null;
if (this.netSyslogConfig.isCacheHostAddress()) {
if (this.cachedHostAddress == null) {
synchronized(cachedHostAddressSyncObject) {
if (this.cachedHostAddress == null) {
this.cachedHostAddress = SyslogUtility.getInetAddress(this.syslogConfig.getHost());
}
}
}
hostAddress = this.cachedHostAddress;
} else {
hostAddress = SyslogUtility.getInetAddress(this.syslogConfig.getHost());
}
return hostAddress;
}
private static final long serialVersionUID = -3250858945515853967L;
protected static final Object cachedHostAddressSyncObject = new Object();
protected InetAddress cachedHostAddress = null;
protected AbstractNetSyslogConfigIF netSyslogConfig = null;
protected void initialize() throws SyslogRuntimeException {
try {
this.netSyslogConfig = (AbstractNetSyslogConfigIF) this.syslogConfig;
} catch (ClassCastException cce) {
throw new SyslogRuntimeException("config must implement interface AbstractNetSyslogConfigIF");
}
}
/**
* @return Returns an object of InetAddress of the local host, using caching if so directed.
*/
public InetAddress getHostAddress() {
InetAddress hostAddress = null;
if (this.netSyslogConfig.isCacheHostAddress()) {
if (this.cachedHostAddress == null) {
synchronized (cachedHostAddressSyncObject) {
if (this.cachedHostAddress == null) {
this.cachedHostAddress = SyslogUtility.getInetAddress(this.syslogConfig.getHost());
}
}
}
hostAddress = this.cachedHostAddress;
} else {
hostAddress = SyslogUtility.getInetAddress(this.syslogConfig.getHost());
}
return hostAddress;
}
}

View File

@ -3,83 +3,83 @@ package org.graylog2.syslog4j.impl.net;
import org.graylog2.syslog4j.impl.AbstractSyslogConfig;
/**
* AbstractNetSyslogConfig is an abstract extension of AbstractSyslogConfig
* that provides configuration support for network-based syslog clients.
*
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: AbstractNetSyslogConfig.java,v 1.12 2010/10/25 03:50:25 cvs Exp $
*/
* AbstractNetSyslogConfig is an abstract extension of AbstractSyslogConfig
* that provides configuration support for network-based syslog clients.
* <p/>
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: AbstractNetSyslogConfig.java,v 1.12 2010/10/25 03:50:25 cvs Exp $
*/
public abstract class AbstractNetSyslogConfig extends AbstractSyslogConfig implements AbstractNetSyslogConfigIF {
private static final long serialVersionUID = 7240133962159244924L;
private static final long serialVersionUID = 7240133962159244924L;
protected String host = SYSLOG_HOST_DEFAULT;
protected int port = SYSLOG_PORT_DEFAULT;
protected boolean cacheHostAddress = CACHE_HOST_ADDRESS_DEFAULT;
protected int maxQueueSize = MAX_QUEUE_SIZE_DEFAULT;
public AbstractNetSyslogConfig() {
//
}
public AbstractNetSyslogConfig(int facility) {
this.facility = facility;
}
protected String host = SYSLOG_HOST_DEFAULT;
protected int port = SYSLOG_PORT_DEFAULT;
public AbstractNetSyslogConfig(int facility, String host) {
this.facility = facility;
this.host = host;
}
protected boolean cacheHostAddress = CACHE_HOST_ADDRESS_DEFAULT;
public AbstractNetSyslogConfig(String host) {
this.host = host;
}
protected int maxQueueSize = MAX_QUEUE_SIZE_DEFAULT;
public AbstractNetSyslogConfig(int facility, String host, int port) {
this.facility = facility;
this.host = host;
this.port = port;
}
public AbstractNetSyslogConfig() {
//
}
public AbstractNetSyslogConfig(String host, int port) {
this.host = host;
this.port = port;
}
public AbstractNetSyslogConfig(int facility) {
this.facility = facility;
}
public boolean isCacheHostAddress() {
return this.cacheHostAddress;
}
public void setCacheHostAddress(boolean cacheHostAddress) {
this.cacheHostAddress = cacheHostAddress;
}
public String getHost() {
return this.host;
}
public void setHost(String host) {
this.host = host;
}
public int getPort() {
return this.port;
}
public void setPort(int port) {
this.port = port;
}
public AbstractNetSyslogConfig(int facility, String host) {
this.facility = facility;
this.host = host;
}
public int getMaxQueueSize() {
return maxQueueSize;
}
public AbstractNetSyslogConfig(String host) {
this.host = host;
}
public void setMaxQueueSize(int maxQueueSize) {
this.maxQueueSize = maxQueueSize;
}
public AbstractNetSyslogConfig(int facility, String host, int port) {
this.facility = facility;
this.host = host;
this.port = port;
}
public AbstractNetSyslogConfig(String host, int port) {
this.host = host;
this.port = port;
}
public boolean isCacheHostAddress() {
return this.cacheHostAddress;
}
public void setCacheHostAddress(boolean cacheHostAddress) {
this.cacheHostAddress = cacheHostAddress;
}
public String getHost() {
return this.host;
}
public void setHost(String host) {
this.host = host;
}
public int getPort() {
return this.port;
}
public void setPort(int port) {
this.port = port;
}
public int getMaxQueueSize() {
return maxQueueSize;
}
public void setMaxQueueSize(int maxQueueSize) {
this.maxQueueSize = maxQueueSize;
}
}

View File

@ -3,17 +3,18 @@ package org.graylog2.syslog4j.impl.net;
import org.graylog2.syslog4j.impl.AbstractSyslogConfigIF;
/**
* AbstractNetSyslogConfigIF is a configuration interface supporting network-based
* Syslog implementations.
*
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: AbstractNetSyslogConfigIF.java,v 1.4 2009/06/06 19:11:02 cvs Exp $
*/
* AbstractNetSyslogConfigIF is a configuration interface supporting network-based
* Syslog implementations.
* <p/>
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: AbstractNetSyslogConfigIF.java,v 1.4 2009/06/06 19:11:02 cvs Exp $
*/
public interface AbstractNetSyslogConfigIF extends AbstractSyslogConfigIF {
public boolean isCacheHostAddress();
public void setCacheHostAddress(boolean cacheHostAddress);
public boolean isCacheHostAddress();
public void setCacheHostAddress(boolean cacheHostAddress);
}

View File

@ -5,87 +5,87 @@ import org.graylog2.syslog4j.impl.AbstractSyslogWriter;
import org.graylog2.syslog4j.impl.net.AbstractNetSyslog;
/**
* TCPNetSyslog is an extension of AbstractSyslog that provides support for
* TCP/IP-based syslog clients.
*
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: TCPNetSyslog.java,v 1.21 2010/11/28 04:43:31 cvs Exp $
*/
* TCPNetSyslog is an extension of AbstractSyslog that provides support for
* TCP/IP-based syslog clients.
* <p/>
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: TCPNetSyslog.java,v 1.21 2010/11/28 04:43:31 cvs Exp $
*/
public class TCPNetSyslog extends AbstractNetSyslog {
private static final long serialVersionUID = -2157528355215068721L;
private static final long serialVersionUID = -2157528355215068721L;
protected TCPNetSyslogWriter writer = null;
protected TCPNetSyslogConfigIF tcpNetSyslogConfig = null;
public void initialize() throws SyslogRuntimeException {
super.initialize();
try {
this.tcpNetSyslogConfig = (TCPNetSyslogConfigIF) this.syslogConfig;
} catch (ClassCastException cce) {
throw new SyslogRuntimeException("config must implement interface TCPNetSyslogConfigIF");
}
}
protected TCPNetSyslogWriter writer = null;
public AbstractSyslogWriter getWriter() {
return getWriter(true);
}
protected TCPNetSyslogConfigIF tcpNetSyslogConfig = null;
public synchronized AbstractSyslogWriter getWriter(boolean create) {
if (this.writer != null || !create) {
return this.writer;
}
this.writer = (TCPNetSyslogWriter) createWriter();
public void initialize() throws SyslogRuntimeException {
super.initialize();
if (this.tcpNetSyslogConfig.isThreaded()) {
createWriterThread(this.writer);
}
try {
this.tcpNetSyslogConfig = (TCPNetSyslogConfigIF) this.syslogConfig;
return this.writer;
}
protected void write(int level, byte[] message) throws SyslogRuntimeException {
AbstractSyslogWriter syslogWriter = getWriter();
try {
if (syslogWriter.hasThread()) {
syslogWriter.queue(level,message);
} else {
synchronized(syslogWriter) {
syslogWriter.write(message);
}
}
} finally {
returnWriter(syslogWriter);
}
}
} catch (ClassCastException cce) {
throw new SyslogRuntimeException("config must implement interface TCPNetSyslogConfigIF");
}
}
public void flush() throws SyslogRuntimeException {
AbstractSyslogWriter syslogWriter = getWriter(false);
if (syslogWriter != null) {
syslogWriter.flush();
}
}
public AbstractSyslogWriter getWriter() {
return getWriter(true);
}
public void shutdown() throws SyslogRuntimeException {
AbstractSyslogWriter syslogWriter = getWriter(false);
if (syslogWriter != null) {
syslogWriter.shutdown();
}
}
public synchronized AbstractSyslogWriter getWriter(boolean create) {
if (this.writer != null || !create) {
return this.writer;
}
public void returnWriter(AbstractSyslogWriter syslogWriter) {
//
}
this.writer = (TCPNetSyslogWriter) createWriter();
if (this.tcpNetSyslogConfig.isThreaded()) {
createWriterThread(this.writer);
}
return this.writer;
}
protected void write(int level, byte[] message) throws SyslogRuntimeException {
AbstractSyslogWriter syslogWriter = getWriter();
try {
if (syslogWriter.hasThread()) {
syslogWriter.queue(level, message);
} else {
synchronized (syslogWriter) {
syslogWriter.write(message);
}
}
} finally {
returnWriter(syslogWriter);
}
}
public void flush() throws SyslogRuntimeException {
AbstractSyslogWriter syslogWriter = getWriter(false);
if (syslogWriter != null) {
syslogWriter.flush();
}
}
public void shutdown() throws SyslogRuntimeException {
AbstractSyslogWriter syslogWriter = getWriter(false);
if (syslogWriter != null) {
syslogWriter.shutdown();
}
}
public void returnWriter(AbstractSyslogWriter syslogWriter) {
//
}
}

View File

@ -5,152 +5,152 @@ import org.graylog2.syslog4j.impl.net.AbstractNetSyslogConfig;
import org.graylog2.syslog4j.util.SyslogUtility;
/**
* TCPNetSyslogConfig is an extension of AbstractNetSyslogConfig that provides
* configuration support for TCP/IP-based syslog clients.
*
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: TCPNetSyslogConfig.java,v 1.18 2010/10/29 03:14:12 cvs Exp $
*/
* TCPNetSyslogConfig is an extension of AbstractNetSyslogConfig that provides
* configuration support for TCP/IP-based syslog clients.
* <p/>
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: TCPNetSyslogConfig.java,v 1.18 2010/10/29 03:14:12 cvs Exp $
*/
public class TCPNetSyslogConfig extends AbstractNetSyslogConfig implements TCPNetSyslogConfigIF {
private static final long serialVersionUID = 9023152050686365460L;
public static byte[] SYSTEM_DELIMITER_SEQUENCE = null;
static {
String delimiterSequence = System.getProperty("line.separator");
SYSTEM_DELIMITER_SEQUENCE = delimiterSequence.getBytes();
if (SYSTEM_DELIMITER_SEQUENCE == null || SYSTEM_DELIMITER_SEQUENCE.length < 1) {
SYSTEM_DELIMITER_SEQUENCE = SyslogConstants.TCP_DELIMITER_SEQUENCE_DEFAULT;
}
}
protected byte[] delimiterSequence = SYSTEM_DELIMITER_SEQUENCE;
protected boolean persistentConnection = TCP_PERSISTENT_CONNECTION_DEFAULT;
protected boolean soLinger = TCP_SO_LINGER_DEFAULT;
protected int soLingerSeconds = TCP_SO_LINGER_SECONDS_DEFAULT;
protected boolean keepAlive = TCP_KEEP_ALIVE_DEFAULT;
protected boolean reuseAddress = TCP_REUSE_ADDRESS_DEFAULT;
protected boolean setBufferSize = TCP_SET_BUFFER_SIZE_DEFAULT;
protected int freshConnectionInterval = TCP_FRESH_CONNECTION_INTERVAL_DEFAULT;
public TCPNetSyslogConfig() {
initialize();
}
protected void initialize() {
//
}
private static final long serialVersionUID = 9023152050686365460L;
public TCPNetSyslogConfig(int facility, String host, int port) {
super(facility, host, port);
initialize();
}
public static byte[] SYSTEM_DELIMITER_SEQUENCE = null;
public TCPNetSyslogConfig(int facility, String host) {
super(facility, host);
initialize();
}
static {
String delimiterSequence = System.getProperty("line.separator");
public TCPNetSyslogConfig(int facility) {
super(facility);
initialize();
}
SYSTEM_DELIMITER_SEQUENCE = delimiterSequence.getBytes();
public TCPNetSyslogConfig(String host, int port) {
super(host, port);
initialize();
}
if (SYSTEM_DELIMITER_SEQUENCE == null || SYSTEM_DELIMITER_SEQUENCE.length < 1) {
SYSTEM_DELIMITER_SEQUENCE = SyslogConstants.TCP_DELIMITER_SEQUENCE_DEFAULT;
}
}
public TCPNetSyslogConfig(String host) {
super(host);
initialize();
}
protected byte[] delimiterSequence = SYSTEM_DELIMITER_SEQUENCE;
public Class getSyslogClass() {
return TCPNetSyslog.class;
}
public byte[] getDelimiterSequence() {
return this.delimiterSequence;
}
protected boolean persistentConnection = TCP_PERSISTENT_CONNECTION_DEFAULT;
public void setDelimiterSequence(byte[] delimiterSequence) {
this.delimiterSequence = delimiterSequence;
}
protected boolean soLinger = TCP_SO_LINGER_DEFAULT;
protected int soLingerSeconds = TCP_SO_LINGER_SECONDS_DEFAULT;
public void setDelimiterSequence(String delimiterSequence) {
this.delimiterSequence = SyslogUtility.getBytes(this,delimiterSequence);
}
protected boolean keepAlive = TCP_KEEP_ALIVE_DEFAULT;
public boolean isPersistentConnection() {
return this.persistentConnection;
}
protected boolean reuseAddress = TCP_REUSE_ADDRESS_DEFAULT;
public void setPersistentConnection(boolean persistentConnection) {
this.persistentConnection = persistentConnection;
}
protected boolean setBufferSize = TCP_SET_BUFFER_SIZE_DEFAULT;
public boolean isSoLinger() {
return this.soLinger;
}
protected int freshConnectionInterval = TCP_FRESH_CONNECTION_INTERVAL_DEFAULT;
public void setSoLinger(boolean soLinger) {
this.soLinger = soLinger;
}
public TCPNetSyslogConfig() {
initialize();
}
public int getSoLingerSeconds() {
return this.soLingerSeconds;
}
protected void initialize() {
//
}
public void setSoLingerSeconds(int soLingerSeconds) {
this.soLingerSeconds = soLingerSeconds;
}
public TCPNetSyslogConfig(int facility, String host, int port) {
super(facility, host, port);
initialize();
}
public boolean isKeepAlive() {
return this.keepAlive;
}
public TCPNetSyslogConfig(int facility, String host) {
super(facility, host);
initialize();
}
public void setKeepAlive(boolean keepAlive) {
this.keepAlive = keepAlive;
}
public TCPNetSyslogConfig(int facility) {
super(facility);
initialize();
}
public boolean isReuseAddress() {
return this.reuseAddress;
}
public TCPNetSyslogConfig(String host, int port) {
super(host, port);
initialize();
}
public void setReuseAddress(boolean reuseAddress) {
this.reuseAddress = reuseAddress;
}
public TCPNetSyslogConfig(String host) {
super(host);
initialize();
}
public boolean isSetBufferSize() {
return this.setBufferSize;
}
public Class getSyslogClass() {
return TCPNetSyslog.class;
}
public void setSetBufferSize(boolean setBufferSize) {
this.setBufferSize = setBufferSize;
}
public byte[] getDelimiterSequence() {
return this.delimiterSequence;
}
public int getFreshConnectionInterval() {
return freshConnectionInterval;
}
public void setDelimiterSequence(byte[] delimiterSequence) {
this.delimiterSequence = delimiterSequence;
}
public void setFreshConnectionInterval(int freshConnectionInterval) {
this.freshConnectionInterval = freshConnectionInterval;
}
public void setDelimiterSequence(String delimiterSequence) {
this.delimiterSequence = SyslogUtility.getBytes(this, delimiterSequence);
}
public Class getSyslogWriterClass() {
return TCPNetSyslogWriter.class;
}
public boolean isPersistentConnection() {
return this.persistentConnection;
}
public void setPersistentConnection(boolean persistentConnection) {
this.persistentConnection = persistentConnection;
}
public boolean isSoLinger() {
return this.soLinger;
}
public void setSoLinger(boolean soLinger) {
this.soLinger = soLinger;
}
public int getSoLingerSeconds() {
return this.soLingerSeconds;
}
public void setSoLingerSeconds(int soLingerSeconds) {
this.soLingerSeconds = soLingerSeconds;
}
public boolean isKeepAlive() {
return this.keepAlive;
}
public void setKeepAlive(boolean keepAlive) {
this.keepAlive = keepAlive;
}
public boolean isReuseAddress() {
return this.reuseAddress;
}
public void setReuseAddress(boolean reuseAddress) {
this.reuseAddress = reuseAddress;
}
public boolean isSetBufferSize() {
return this.setBufferSize;
}
public void setSetBufferSize(boolean setBufferSize) {
this.setBufferSize = setBufferSize;
}
public int getFreshConnectionInterval() {
return freshConnectionInterval;
}
public void setFreshConnectionInterval(int freshConnectionInterval) {
this.freshConnectionInterval = freshConnectionInterval;
}
public Class getSyslogWriterClass() {
return TCPNetSyslogWriter.class;
}
}

View File

@ -3,38 +3,46 @@ package org.graylog2.syslog4j.impl.net.tcp;
import org.graylog2.syslog4j.impl.net.AbstractNetSyslogConfigIF;
/**
* TCPNetSyslogConfigIF is a configuration interface supporting TCP/IP-based
* Syslog implementations.
*
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: TCPNetSyslogConfigIF.java,v 1.6 2010/10/29 03:14:12 cvs Exp $
*/
* TCPNetSyslogConfigIF is a configuration interface supporting TCP/IP-based
* Syslog implementations.
* <p/>
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: TCPNetSyslogConfigIF.java,v 1.6 2010/10/29 03:14:12 cvs Exp $
*/
public interface TCPNetSyslogConfigIF extends AbstractNetSyslogConfigIF {
public byte[] getDelimiterSequence();
public void setDelimiterSequence(byte[] delimiterSequence);
public byte[] getDelimiterSequence();
public boolean isPersistentConnection();
public void setPersistentConnection(boolean persistentConnection);
public boolean isSoLinger();
public void setSoLinger(boolean soLinger);
public int getSoLingerSeconds();
public void setSoLingerSeconds(int soLingerSeconds);
public boolean isKeepAlive();
public void setKeepAlive(boolean keepAlive);
public boolean isReuseAddress();
public void setReuseAddress(boolean reuseAddress);
public boolean isSetBufferSize();
public void setSetBufferSize(boolean setBufferSize);
public void setDelimiterSequence(byte[] delimiterSequence);
public int getFreshConnectionInterval();
public void setFreshConnectionInterval(int interval);
public boolean isPersistentConnection();
public void setPersistentConnection(boolean persistentConnection);
public boolean isSoLinger();
public void setSoLinger(boolean soLinger);
public int getSoLingerSeconds();
public void setSoLingerSeconds(int soLingerSeconds);
public boolean isKeepAlive();
public void setKeepAlive(boolean keepAlive);
public boolean isReuseAddress();
public void setReuseAddress(boolean reuseAddress);
public boolean isSetBufferSize();
public void setSetBufferSize(boolean setBufferSize);
public int getFreshConnectionInterval();
public void setFreshConnectionInterval(int interval);
}

View File

@ -14,213 +14,213 @@ import org.graylog2.syslog4j.impl.AbstractSyslogWriter;
import org.graylog2.syslog4j.util.SyslogUtility;
/**
* TCPNetSyslogWriter is an implementation of Runnable that supports sending
* TCP-based messages within a separate Thread.
*
* <p>When used in "threaded" mode (see TCPNetSyslogConfig for the option),
* a queuing mechanism is used (via LinkedList).</p>
*
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: TCPNetSyslogWriter.java,v 1.20 2010/11/28 01:38:08 cvs Exp $
*/
* TCPNetSyslogWriter is an implementation of Runnable that supports sending
* TCP-based messages within a separate Thread.
* <p/>
* <p>When used in "threaded" mode (see TCPNetSyslogConfig for the option),
* a queuing mechanism is used (via LinkedList).</p>
* <p/>
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: TCPNetSyslogWriter.java,v 1.20 2010/11/28 01:38:08 cvs Exp $
*/
public class TCPNetSyslogWriter extends AbstractSyslogWriter {
private static final long serialVersionUID = -6388813866108482855L;
private static final long serialVersionUID = -6388813866108482855L;
protected TCPNetSyslog tcpNetSyslog = null;
protected Socket socket = null;
protected TCPNetSyslogConfigIF tcpNetSyslogConfig = null;
protected long lastSocketCreationTimeMs = 0;
public TCPNetSyslogWriter() {
//
}
public void initialize(AbstractSyslog abstractSyslog) {
super.initialize(abstractSyslog);
this.tcpNetSyslog = (TCPNetSyslog) abstractSyslog;
this.tcpNetSyslogConfig = (TCPNetSyslogConfigIF) this.tcpNetSyslog.getConfig();
}
protected SocketFactory obtainSocketFactory() {
return SocketFactory.getDefault();
}
protected Socket createSocket(InetAddress hostAddress, int port, boolean keepalive) throws IOException {
SocketFactory socketFactory = obtainSocketFactory();
Socket newSocket = socketFactory.createSocket(hostAddress,port);
protected TCPNetSyslog tcpNetSyslog = null;
if (this.tcpNetSyslogConfig.isSoLinger()) {
newSocket.setSoLinger(true,this.tcpNetSyslogConfig.getSoLingerSeconds());
}
if (this.tcpNetSyslogConfig.isKeepAlive()) {
newSocket.setKeepAlive(keepalive);
}
if (this.tcpNetSyslogConfig.isReuseAddress()) {
newSocket.setReuseAddress(true);
}
return newSocket;
}
protected Socket getSocket() throws SyslogRuntimeException {
if (this.socket != null && this.socket.isConnected()) {
int freshConnectionInterval = this.tcpNetSyslogConfig.getFreshConnectionInterval();
if (freshConnectionInterval > 0) {
long currentTimeMs = System.currentTimeMillis();
if ((currentTimeMs - lastSocketCreationTimeMs) >= freshConnectionInterval) {
closeSocket(this.socket);
}
} else {
return this.socket;
}
}
if (this.socket == null) {
lastSocketCreationTimeMs = 0;
try {
InetAddress hostAddress = this.tcpNetSyslog.getHostAddress();
this.socket = createSocket(hostAddress,this.syslog.getConfig().getPort(),this.tcpNetSyslogConfig.isPersistentConnection());
lastSocketCreationTimeMs = System.currentTimeMillis();
} catch (IOException ioe) {
throw new SyslogRuntimeException(ioe);
}
}
return this.socket;
}
protected void closeSocket(Socket socketToClose) {
if (socketToClose == null) {
return;
}
try {
socketToClose.close();
} catch (IOException ioe) {
if (!"Socket is closed".equalsIgnoreCase(ioe.getMessage())) {
throw new SyslogRuntimeException(ioe);
}
} finally {
if (socketToClose == this.socket) {
this.socket = null;
}
}
}
public void write(byte[] message) throws SyslogRuntimeException {
Socket currentSocket = null;
int attempts = 0;
while(attempts != -1 && attempts < (this.tcpNetSyslogConfig.getWriteRetries() + 1)) {
try {
currentSocket = getSocket();
if (currentSocket == null) {
throw new SyslogRuntimeException("No socket available");
}
OutputStream os = currentSocket.getOutputStream();
if (this.tcpNetSyslogConfig.isSetBufferSize()) {
currentSocket.setSendBufferSize(message.length);
}
os.write(message);
byte[] delimiterSequence = this.tcpNetSyslogConfig.getDelimiterSequence();
if (delimiterSequence != null && delimiterSequence.length > 0) {
os.write(delimiterSequence);
}
this.syslog.setBackLogStatus(false);
protected Socket socket = null;
attempts = -1;
if (!this.tcpNetSyslogConfig.isPersistentConnection()) {
closeSocket(currentSocket);
}
} catch (IOException ioe) {
attempts++;
closeSocket(currentSocket);
if (attempts >= (this.tcpNetSyslogConfig.getWriteRetries() + 1)) {
throw new SyslogRuntimeException(ioe);
}
}
}
}
protected TCPNetSyslogConfigIF tcpNetSyslogConfig = null;
public synchronized void flush() throws SyslogRuntimeException {
if (this.socket == null) {
return;
}
if (this.syslogConfig.isThreaded()) {
this.shutdown();
this.syslog.createWriterThread(this);
} else {
closeSocket(this.socket);
}
}
public synchronized void shutdown() throws SyslogRuntimeException {
this.shutdown = true;
if (this.syslogConfig.isThreaded()) {
long timeStart = System.currentTimeMillis();
boolean done = false;
while(!done) {
if (this.socket == null || this.socket.isClosed()) {
done = true;
} else {
long now = System.currentTimeMillis();
if (now > (timeStart + this.tcpNetSyslogConfig.getMaxShutdownWait())) {
closeSocket(this.socket);
this.thread.interrupt();
done = true;
}
if (!done) {
SyslogUtility.sleep(SyslogConstants.SHUTDOWN_INTERVAL);
}
}
}
} else {
if (this.socket == null || this.socket.isClosed()) {
return;
}
closeSocket(this.socket);
}
}
protected void runCompleted() {
closeSocket(this.socket);
}
protected long lastSocketCreationTimeMs = 0;
public TCPNetSyslogWriter() {
//
}
public void initialize(AbstractSyslog abstractSyslog) {
super.initialize(abstractSyslog);
this.tcpNetSyslog = (TCPNetSyslog) abstractSyslog;
this.tcpNetSyslogConfig = (TCPNetSyslogConfigIF) this.tcpNetSyslog.getConfig();
}
protected SocketFactory obtainSocketFactory() {
return SocketFactory.getDefault();
}
protected Socket createSocket(InetAddress hostAddress, int port, boolean keepalive) throws IOException {
SocketFactory socketFactory = obtainSocketFactory();
Socket newSocket = socketFactory.createSocket(hostAddress, port);
if (this.tcpNetSyslogConfig.isSoLinger()) {
newSocket.setSoLinger(true, this.tcpNetSyslogConfig.getSoLingerSeconds());
}
if (this.tcpNetSyslogConfig.isKeepAlive()) {
newSocket.setKeepAlive(keepalive);
}
if (this.tcpNetSyslogConfig.isReuseAddress()) {
newSocket.setReuseAddress(true);
}
return newSocket;
}
protected Socket getSocket() throws SyslogRuntimeException {
if (this.socket != null && this.socket.isConnected()) {
int freshConnectionInterval = this.tcpNetSyslogConfig.getFreshConnectionInterval();
if (freshConnectionInterval > 0) {
long currentTimeMs = System.currentTimeMillis();
if ((currentTimeMs - lastSocketCreationTimeMs) >= freshConnectionInterval) {
closeSocket(this.socket);
}
} else {
return this.socket;
}
}
if (this.socket == null) {
lastSocketCreationTimeMs = 0;
try {
InetAddress hostAddress = this.tcpNetSyslog.getHostAddress();
this.socket = createSocket(hostAddress, this.syslog.getConfig().getPort(), this.tcpNetSyslogConfig.isPersistentConnection());
lastSocketCreationTimeMs = System.currentTimeMillis();
} catch (IOException ioe) {
throw new SyslogRuntimeException(ioe);
}
}
return this.socket;
}
protected void closeSocket(Socket socketToClose) {
if (socketToClose == null) {
return;
}
try {
socketToClose.close();
} catch (IOException ioe) {
if (!"Socket is closed".equalsIgnoreCase(ioe.getMessage())) {
throw new SyslogRuntimeException(ioe);
}
} finally {
if (socketToClose == this.socket) {
this.socket = null;
}
}
}
public void write(byte[] message) throws SyslogRuntimeException {
Socket currentSocket = null;
int attempts = 0;
while (attempts != -1 && attempts < (this.tcpNetSyslogConfig.getWriteRetries() + 1)) {
try {
currentSocket = getSocket();
if (currentSocket == null) {
throw new SyslogRuntimeException("No socket available");
}
OutputStream os = currentSocket.getOutputStream();
if (this.tcpNetSyslogConfig.isSetBufferSize()) {
currentSocket.setSendBufferSize(message.length);
}
os.write(message);
byte[] delimiterSequence = this.tcpNetSyslogConfig.getDelimiterSequence();
if (delimiterSequence != null && delimiterSequence.length > 0) {
os.write(delimiterSequence);
}
this.syslog.setBackLogStatus(false);
attempts = -1;
if (!this.tcpNetSyslogConfig.isPersistentConnection()) {
closeSocket(currentSocket);
}
} catch (IOException ioe) {
attempts++;
closeSocket(currentSocket);
if (attempts >= (this.tcpNetSyslogConfig.getWriteRetries() + 1)) {
throw new SyslogRuntimeException(ioe);
}
}
}
}
public synchronized void flush() throws SyslogRuntimeException {
if (this.socket == null) {
return;
}
if (this.syslogConfig.isThreaded()) {
this.shutdown();
this.syslog.createWriterThread(this);
} else {
closeSocket(this.socket);
}
}
public synchronized void shutdown() throws SyslogRuntimeException {
this.shutdown = true;
if (this.syslogConfig.isThreaded()) {
long timeStart = System.currentTimeMillis();
boolean done = false;
while (!done) {
if (this.socket == null || this.socket.isClosed()) {
done = true;
} else {
long now = System.currentTimeMillis();
if (now > (timeStart + this.tcpNetSyslogConfig.getMaxShutdownWait())) {
closeSocket(this.socket);
this.thread.interrupt();
done = true;
}
if (!done) {
SyslogUtility.sleep(SyslogConstants.SHUTDOWN_INTERVAL);
}
}
}
} else {
if (this.socket == null || this.socket.isClosed()) {
return;
}
closeSocket(this.socket);
}
}
protected void runCompleted() {
closeSocket(this.socket);
}
}

View File

@ -7,70 +7,70 @@ import org.graylog2.syslog4j.impl.pool.AbstractSyslogPoolFactory;
import org.graylog2.syslog4j.impl.pool.generic.GenericSyslogPoolFactory;
/**
* PooledTCPNetSyslog is an extension of TCPNetSyslog which provides support
* for Apache Commons Pool.
*
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: PooledTCPNetSyslog.java,v 1.5 2008/12/10 04:30:15 cvs Exp $
*/
* PooledTCPNetSyslog is an extension of TCPNetSyslog which provides support
* for Apache Commons Pool.
* <p/>
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: PooledTCPNetSyslog.java,v 1.5 2008/12/10 04:30:15 cvs Exp $
*/
public class PooledTCPNetSyslog extends TCPNetSyslog {
private static final long serialVersionUID = 4279960451141784200L;
protected AbstractSyslogPoolFactory poolFactory = null;
private static final long serialVersionUID = 4279960451141784200L;
public void initialize() throws SyslogRuntimeException {
super.initialize();
this.poolFactory = createSyslogPoolFactory();
this.poolFactory.initialize(this);
}
protected AbstractSyslogPoolFactory createSyslogPoolFactory() {
AbstractSyslogPoolFactory syslogPoolFactory = new GenericSyslogPoolFactory();
return syslogPoolFactory;
}
protected AbstractSyslogPoolFactory poolFactory = null;
public AbstractSyslogWriter getWriter() {
try {
AbstractSyslogWriter syslogWriter = this.poolFactory.borrowSyslogWriter();
return syslogWriter;
} catch (Exception e) {
throw new SyslogRuntimeException(e);
}
}
public void initialize() throws SyslogRuntimeException {
super.initialize();
public void returnWriter(AbstractSyslogWriter syslogWriter) {
try {
this.poolFactory.returnSyslogWriter(syslogWriter);
} catch (Exception e) {
throw new SyslogRuntimeException(e);
}
}
this.poolFactory = createSyslogPoolFactory();
public void flush() throws SyslogRuntimeException {
try {
this.poolFactory.clear();
} catch (Exception e) {
//
}
}
this.poolFactory.initialize(this);
}
public void shutdown() throws SyslogRuntimeException {
try {
this.poolFactory.close();
} catch (Exception e) {
//
}
}
protected AbstractSyslogPoolFactory createSyslogPoolFactory() {
AbstractSyslogPoolFactory syslogPoolFactory = new GenericSyslogPoolFactory();
return syslogPoolFactory;
}
public AbstractSyslogWriter getWriter() {
try {
AbstractSyslogWriter syslogWriter = this.poolFactory.borrowSyslogWriter();
return syslogWriter;
} catch (Exception e) {
throw new SyslogRuntimeException(e);
}
}
public void returnWriter(AbstractSyslogWriter syslogWriter) {
try {
this.poolFactory.returnSyslogWriter(syslogWriter);
} catch (Exception e) {
throw new SyslogRuntimeException(e);
}
}
public void flush() throws SyslogRuntimeException {
try {
this.poolFactory.clear();
} catch (Exception e) {
//
}
}
public void shutdown() throws SyslogRuntimeException {
try {
this.poolFactory.close();
} catch (Exception e) {
//
}
}
}

View File

@ -5,168 +5,168 @@ import org.graylog2.syslog4j.SyslogPoolConfigIF;
import org.graylog2.syslog4j.impl.net.tcp.TCPNetSyslogConfig;
/**
* NetSyslogPoolFactory is an implementation of SyslogPoolConfigIF
* which provides configuration support for the Apache Commons Pool.
*
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: PooledTCPNetSyslogConfig.java,v 1.3 2008/11/26 15:01:47 cvs Exp $
*/
* NetSyslogPoolFactory is an implementation of SyslogPoolConfigIF
* which provides configuration support for the Apache Commons Pool.
* <p/>
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: PooledTCPNetSyslogConfig.java,v 1.3 2008/11/26 15:01:47 cvs Exp $
*/
public class PooledTCPNetSyslogConfig extends TCPNetSyslogConfig implements SyslogPoolConfigIF {
private static final long serialVersionUID = 2283355983363422888L;
protected int maxActive = SYSLOG_POOL_CONFIG_MAX_ACTIVE_DEFAULT;
protected int maxIdle = SYSLOG_POOL_CONFIG_MAX_IDLE_DEFAULT;
protected long maxWait = SYSLOG_POOL_CONFIG_MAX_WAIT_DEFAULT;
protected long minEvictableIdleTimeMillis = SYSLOG_POOL_CONFIG_MIN_EVICTABLE_IDLE_TIME_MILLIS_DEFAULT;
protected int minIdle = SYSLOG_POOL_CONFIG_MIN_IDLE_DEFAULT;
protected int numTestsPerEvictionRun = SYSLOG_POOL_CONFIG_NUM_TESTS_PER_EVICTION_RUN_DEFAULT;
protected long softMinEvictableIdleTimeMillis = SYSLOG_POOL_CONFIG_SOFT_MIN_EVICTABLE_IDLE_TIME_MILLIS_DEFAULT;
protected long timeBetweenEvictionRunsMillis = SYSLOG_POOL_CONFIG_TIME_BETWEEN_EVICTION_RUNS_MILLIS_DEFAULT;
protected byte whenExhaustedAction = GenericObjectPool.WHEN_EXHAUSTED_BLOCK;
protected boolean testOnBorrow = SYSLOG_POOL_CONFIG_TEST_ON_BORROW_DEFAULT;
protected boolean testOnReturn = SYSLOG_POOL_CONFIG_TEST_ON_RETURN_DEFAULT;
protected boolean testWhileIdle = SYSLOG_POOL_CONFIG_TEST_WHILE_IDLE_DEFAULT;
public PooledTCPNetSyslogConfig() {
//
}
private static final long serialVersionUID = 2283355983363422888L;
public PooledTCPNetSyslogConfig(int facility, String host, int port) {
super(facility, host, port);
}
protected int maxActive = SYSLOG_POOL_CONFIG_MAX_ACTIVE_DEFAULT;
protected int maxIdle = SYSLOG_POOL_CONFIG_MAX_IDLE_DEFAULT;
protected long maxWait = SYSLOG_POOL_CONFIG_MAX_WAIT_DEFAULT;
protected long minEvictableIdleTimeMillis = SYSLOG_POOL_CONFIG_MIN_EVICTABLE_IDLE_TIME_MILLIS_DEFAULT;
protected int minIdle = SYSLOG_POOL_CONFIG_MIN_IDLE_DEFAULT;
protected int numTestsPerEvictionRun = SYSLOG_POOL_CONFIG_NUM_TESTS_PER_EVICTION_RUN_DEFAULT;
protected long softMinEvictableIdleTimeMillis = SYSLOG_POOL_CONFIG_SOFT_MIN_EVICTABLE_IDLE_TIME_MILLIS_DEFAULT;
protected long timeBetweenEvictionRunsMillis = SYSLOG_POOL_CONFIG_TIME_BETWEEN_EVICTION_RUNS_MILLIS_DEFAULT;
protected byte whenExhaustedAction = GenericObjectPool.WHEN_EXHAUSTED_BLOCK;
protected boolean testOnBorrow = SYSLOG_POOL_CONFIG_TEST_ON_BORROW_DEFAULT;
protected boolean testOnReturn = SYSLOG_POOL_CONFIG_TEST_ON_RETURN_DEFAULT;
protected boolean testWhileIdle = SYSLOG_POOL_CONFIG_TEST_WHILE_IDLE_DEFAULT;
public PooledTCPNetSyslogConfig(int facility, String host) {
super(facility, host);
}
public PooledTCPNetSyslogConfig() {
//
}
public PooledTCPNetSyslogConfig(int facility) {
super(facility);
}
public PooledTCPNetSyslogConfig(int facility, String host, int port) {
super(facility, host, port);
}
public PooledTCPNetSyslogConfig(String host, int port) {
super(host, port);
}
public PooledTCPNetSyslogConfig(int facility, String host) {
super(facility, host);
}
public PooledTCPNetSyslogConfig(String host) {
super(host);
}
protected void configureThreadedValues(int value) {
if (isThreaded()) {
this.minIdle = value;
this.maxIdle = value;
this.maxActive = value;
}
}
public int getMaxActive() {
return this.maxActive;
}
public PooledTCPNetSyslogConfig(int facility) {
super(facility);
}
public void setMaxActive(int maxActive) {
configureThreadedValues(maxActive);
this.maxActive = maxActive;
}
public PooledTCPNetSyslogConfig(String host, int port) {
super(host, port);
}
public int getMaxIdle() {
return this.maxIdle;
}
public PooledTCPNetSyslogConfig(String host) {
super(host);
}
public void setMaxIdle(int maxIdle) {
configureThreadedValues(maxIdle);
this.maxIdle = maxIdle;
}
protected void configureThreadedValues(int value) {
if (isThreaded()) {
this.minIdle = value;
this.maxIdle = value;
this.maxActive = value;
}
}
public long getMaxWait() {
return this.maxWait;
}
public int getMaxActive() {
return this.maxActive;
}
public void setMaxWait(long maxWait) {
this.maxWait = maxWait;
}
public void setMaxActive(int maxActive) {
configureThreadedValues(maxActive);
public long getMinEvictableIdleTimeMillis() {
return this.minEvictableIdleTimeMillis;
}
this.maxActive = maxActive;
}
public void setMinEvictableIdleTimeMillis(long minEvictableIdleTimeMillis) {
this.minEvictableIdleTimeMillis = minEvictableIdleTimeMillis;
}
public int getMaxIdle() {
return this.maxIdle;
}
public int getMinIdle() {
return this.minIdle;
}
public void setMaxIdle(int maxIdle) {
configureThreadedValues(maxIdle);
public void setMinIdle(int minIdle) {
configureThreadedValues(minIdle);
this.minIdle = minIdle;
}
this.maxIdle = maxIdle;
}
public int getNumTestsPerEvictionRun() {
return this.numTestsPerEvictionRun;
}
public long getMaxWait() {
return this.maxWait;
}
public void setNumTestsPerEvictionRun(int numTestsPerEvictionRun) {
this.numTestsPerEvictionRun = numTestsPerEvictionRun;
}
public void setMaxWait(long maxWait) {
this.maxWait = maxWait;
}
public long getSoftMinEvictableIdleTimeMillis() {
return this.softMinEvictableIdleTimeMillis;
}
public long getMinEvictableIdleTimeMillis() {
return this.minEvictableIdleTimeMillis;
}
public void setSoftMinEvictableIdleTimeMillis(
long softMinEvictableIdleTimeMillis) {
this.softMinEvictableIdleTimeMillis = softMinEvictableIdleTimeMillis;
}
public void setMinEvictableIdleTimeMillis(long minEvictableIdleTimeMillis) {
this.minEvictableIdleTimeMillis = minEvictableIdleTimeMillis;
}
public long getTimeBetweenEvictionRunsMillis() {
return this.timeBetweenEvictionRunsMillis;
}
public int getMinIdle() {
return this.minIdle;
}
public void setTimeBetweenEvictionRunsMillis(long timeBetweenEvictionRunsMillis) {
this.timeBetweenEvictionRunsMillis = timeBetweenEvictionRunsMillis;
}
public void setMinIdle(int minIdle) {
configureThreadedValues(minIdle);
public byte getWhenExhaustedAction() {
return this.whenExhaustedAction;
}
this.minIdle = minIdle;
}
public void setWhenExhaustedAction(byte whenExhaustedAction) {
this.whenExhaustedAction = whenExhaustedAction;
}
public int getNumTestsPerEvictionRun() {
return this.numTestsPerEvictionRun;
}
public boolean isTestOnBorrow() {
return this.testOnBorrow;
}
public void setNumTestsPerEvictionRun(int numTestsPerEvictionRun) {
this.numTestsPerEvictionRun = numTestsPerEvictionRun;
}
public void setTestOnBorrow(boolean testOnBorrow) {
this.testOnBorrow = testOnBorrow;
}
public long getSoftMinEvictableIdleTimeMillis() {
return this.softMinEvictableIdleTimeMillis;
}
public boolean isTestOnReturn() {
return this.testOnReturn;
}
public void setSoftMinEvictableIdleTimeMillis(
long softMinEvictableIdleTimeMillis) {
this.softMinEvictableIdleTimeMillis = softMinEvictableIdleTimeMillis;
}
public void setTestOnReturn(boolean testOnReturn) {
this.testOnReturn = testOnReturn;
}
public long getTimeBetweenEvictionRunsMillis() {
return this.timeBetweenEvictionRunsMillis;
}
public boolean isTestWhileIdle() {
return this.testWhileIdle;
}
public void setTimeBetweenEvictionRunsMillis(long timeBetweenEvictionRunsMillis) {
this.timeBetweenEvictionRunsMillis = timeBetweenEvictionRunsMillis;
}
public void setTestWhileIdle(boolean testWhileIdle) {
this.testWhileIdle = testWhileIdle;
}
public byte getWhenExhaustedAction() {
return this.whenExhaustedAction;
}
public Class getSyslogClass() {
return PooledTCPNetSyslog.class;
}
public void setWhenExhaustedAction(byte whenExhaustedAction) {
this.whenExhaustedAction = whenExhaustedAction;
}
public boolean isTestOnBorrow() {
return this.testOnBorrow;
}
public void setTestOnBorrow(boolean testOnBorrow) {
this.testOnBorrow = testOnBorrow;
}
public boolean isTestOnReturn() {
return this.testOnReturn;
}
public void setTestOnReturn(boolean testOnReturn) {
this.testOnReturn = testOnReturn;
}
public boolean isTestWhileIdle() {
return this.testWhileIdle;
}
public void setTestWhileIdle(boolean testWhileIdle) {
this.testWhileIdle = testWhileIdle;
}
public Class getSyslogClass() {
return PooledTCPNetSyslog.class;
}
}

View File

@ -4,46 +4,46 @@ import org.graylog2.syslog4j.SyslogRuntimeException;
import org.graylog2.syslog4j.impl.net.tcp.TCPNetSyslog;
/**
* SSLTCPNetSyslog is an extension of AbstractSyslog that provides support for
* TCP/IP-based (over SSL/TLS) syslog clients.
*
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: SSLTCPNetSyslog.java,v 1.1 2009/03/29 17:38:58 cvs Exp $
*/
* SSLTCPNetSyslog is an extension of AbstractSyslog that provides support for
* TCP/IP-based (over SSL/TLS) syslog clients.
* <p/>
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: SSLTCPNetSyslog.java,v 1.1 2009/03/29 17:38:58 cvs Exp $
*/
public class SSLTCPNetSyslog extends TCPNetSyslog {
private static final long serialVersionUID = 2766654802524487317L;
private static final long serialVersionUID = 2766654802524487317L;
public void initialize() throws SyslogRuntimeException {
super.initialize();
SSLTCPNetSyslogConfigIF sslTcpNetSyslogConfig = (SSLTCPNetSyslogConfigIF) this.tcpNetSyslogConfig;
String keyStore = sslTcpNetSyslogConfig.getKeyStore();
if (keyStore != null && !"".equals(keyStore.trim())) {
System.setProperty("javax.net.ssl.keyStore",keyStore);
}
public void initialize() throws SyslogRuntimeException {
super.initialize();
String keyStorePassword = sslTcpNetSyslogConfig.getKeyStorePassword();
if (keyStorePassword != null && !"".equals(keyStorePassword.trim())) {
System.setProperty("javax.net.ssl.keyStorePassword",keyStorePassword);
}
SSLTCPNetSyslogConfigIF sslTcpNetSyslogConfig = (SSLTCPNetSyslogConfigIF) this.tcpNetSyslogConfig;
String trustStore = sslTcpNetSyslogConfig.getTrustStore();
if (trustStore != null && !"".equals(trustStore.trim())) {
System.setProperty("javax.net.ssl.trustStore",trustStore);
}
String keyStore = sslTcpNetSyslogConfig.getKeyStore();
String trustStorePassword = sslTcpNetSyslogConfig.getTrustStorePassword();
if (trustStorePassword != null && !"".equals(trustStorePassword.trim())) {
System.setProperty("javax.net.ssl.trustStorePassword",trustStorePassword);
}
}
if (keyStore != null && !"".equals(keyStore.trim())) {
System.setProperty("javax.net.ssl.keyStore", keyStore);
}
String keyStorePassword = sslTcpNetSyslogConfig.getKeyStorePassword();
if (keyStorePassword != null && !"".equals(keyStorePassword.trim())) {
System.setProperty("javax.net.ssl.keyStorePassword", keyStorePassword);
}
String trustStore = sslTcpNetSyslogConfig.getTrustStore();
if (trustStore != null && !"".equals(trustStore.trim())) {
System.setProperty("javax.net.ssl.trustStore", trustStore);
}
String trustStorePassword = sslTcpNetSyslogConfig.getTrustStorePassword();
if (trustStorePassword != null && !"".equals(trustStorePassword.trim())) {
System.setProperty("javax.net.ssl.trustStorePassword", trustStorePassword);
}
}
}

View File

@ -3,86 +3,86 @@ package org.graylog2.syslog4j.impl.net.tcp.ssl;
import org.graylog2.syslog4j.impl.net.tcp.TCPNetSyslogConfig;
/**
* SSLTCPNetSyslogConfig is an extension of TCPNetSyslogConfig that provides
* configuration support for TCP/IP-based (over SSL/TLS) syslog clients.
*
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: SSLTCPNetSyslogConfig.java,v 1.2 2009/03/29 17:38:58 cvs Exp $
*/
* SSLTCPNetSyslogConfig is an extension of TCPNetSyslogConfig that provides
* configuration support for TCP/IP-based (over SSL/TLS) syslog clients.
* <p/>
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: SSLTCPNetSyslogConfig.java,v 1.2 2009/03/29 17:38:58 cvs Exp $
*/
public class SSLTCPNetSyslogConfig extends TCPNetSyslogConfig implements SSLTCPNetSyslogConfigIF {
private static final long serialVersionUID = 5569086213824510834L;
private static final long serialVersionUID = 5569086213824510834L;
protected String keyStore = null;
protected String keyStorePassword = null;
protected String keyStore = null;
protected String keyStorePassword = null;
protected String trustStore = null;
protected String trustStorePassword = null;
protected String trustStore = null;
protected String trustStorePassword = null;
public SSLTCPNetSyslogConfig() {
//
}
public SSLTCPNetSyslogConfig() {
//
}
public SSLTCPNetSyslogConfig(int facility, String host, int port) {
super(facility, host, port);
}
public SSLTCPNetSyslogConfig(int facility, String host, int port) {
super(facility, host, port);
}
public SSLTCPNetSyslogConfig(int facility, String host) {
super(facility, host);
}
public SSLTCPNetSyslogConfig(int facility, String host) {
super(facility, host);
}
public SSLTCPNetSyslogConfig(int facility) {
super(facility);
}
public SSLTCPNetSyslogConfig(int facility) {
super(facility);
}
public SSLTCPNetSyslogConfig(String host, int port) {
super(host, port);
}
public SSLTCPNetSyslogConfig(String host, int port) {
super(host, port);
}
public SSLTCPNetSyslogConfig(String host) {
super(host);
}
public String getKeyStore() {
return this.keyStore;
}
public void setKeyStore(String keyStore) {
this.keyStore = keyStore;
}
public String getKeyStorePassword() {
return this.keyStorePassword;
}
public void setKeyStorePassword(String keyStorePassword) {
this.keyStorePassword = keyStorePassword;
}
public SSLTCPNetSyslogConfig(String host) {
super(host);
}
public String getTrustStore() {
return this.trustStore;
}
public String getKeyStore() {
return this.keyStore;
}
public void setTrustStore(String trustStore) {
this.trustStore = trustStore;
}
public void setKeyStore(String keyStore) {
this.keyStore = keyStore;
}
public String getTrustStorePassword() {
return this.trustStorePassword;
}
public String getKeyStorePassword() {
return this.keyStorePassword;
}
public void setTrustStorePassword(String trustStorePassword) {
this.trustStorePassword = trustStorePassword;
}
public void setKeyStorePassword(String keyStorePassword) {
this.keyStorePassword = keyStorePassword;
}
public Class getSyslogClass() {
return SSLTCPNetSyslog.class;
}
public String getTrustStore() {
return this.trustStore;
}
public Class getSyslogWriterClass() {
return SSLTCPNetSyslogWriter.class;
}
public void setTrustStore(String trustStore) {
this.trustStore = trustStore;
}
public String getTrustStorePassword() {
return this.trustStorePassword;
}
public void setTrustStorePassword(String trustStorePassword) {
this.trustStorePassword = trustStorePassword;
}
public Class getSyslogClass() {
return SSLTCPNetSyslog.class;
}
public Class getSyslogWriterClass() {
return SSLTCPNetSyslogWriter.class;
}
}

View File

@ -3,26 +3,30 @@ package org.graylog2.syslog4j.impl.net.tcp.ssl;
import org.graylog2.syslog4j.impl.net.tcp.TCPNetSyslogConfigIF;
/**
* SSLTCPNetSyslogConfigIF is a configuration interface supporting TCP/IP-based
* (over SSL/TLS) Syslog implementations.
*
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: SSLTCPNetSyslogConfigIF.java,v 1.1 2009/03/29 17:38:58 cvs Exp $
*/
* SSLTCPNetSyslogConfigIF is a configuration interface supporting TCP/IP-based
* (over SSL/TLS) Syslog implementations.
* <p/>
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: SSLTCPNetSyslogConfigIF.java,v 1.1 2009/03/29 17:38:58 cvs Exp $
*/
public interface SSLTCPNetSyslogConfigIF extends TCPNetSyslogConfigIF {
public String getKeyStore();
public void setKeyStore(String keyStore);
public String getKeyStorePassword();
public void setKeyStorePassword(String keyStorePassword);
public String getKeyStore();
public String getTrustStore();
public void setTrustStore(String trustStore);
public String getTrustStorePassword();
public void setTrustStorePassword(String trustStorePassword);
public void setKeyStore(String keyStore);
public String getKeyStorePassword();
public void setKeyStorePassword(String keyStorePassword);
public String getTrustStore();
public void setTrustStore(String trustStore);
public String getTrustStorePassword();
public void setTrustStorePassword(String trustStorePassword);
}

View File

@ -6,23 +6,23 @@ import javax.net.ssl.SSLSocketFactory;
import org.graylog2.syslog4j.impl.net.tcp.TCPNetSyslogWriter;
/**
* SSLTCPNetSyslogWriter is an implementation of Runnable that supports sending
* TCP/IP-based (over SSL/TLS) messages within a separate Thread.
*
* <p>When used in "threaded" mode (see TCPNetSyslogConfig for the option),
* a queuing mechanism is used (via LinkedList).</p>
*
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: SSLTCPNetSyslogWriter.java,v 1.4 2009/03/29 17:38:58 cvs Exp $
*/
* SSLTCPNetSyslogWriter is an implementation of Runnable that supports sending
* TCP/IP-based (over SSL/TLS) messages within a separate Thread.
* <p/>
* <p>When used in "threaded" mode (see TCPNetSyslogConfig for the option),
* a queuing mechanism is used (via LinkedList).</p>
* <p/>
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: SSLTCPNetSyslogWriter.java,v 1.4 2009/03/29 17:38:58 cvs Exp $
*/
public class SSLTCPNetSyslogWriter extends TCPNetSyslogWriter {
private static final long serialVersionUID = 8944446235285662244L;
private static final long serialVersionUID = 8944446235285662244L;
protected SocketFactory obtainSocketFactory() {
return SSLSocketFactory.getDefault();
}
protected SocketFactory obtainSocketFactory() {
return SSLSocketFactory.getDefault();
}
}

View File

@ -6,86 +6,86 @@ import org.graylog2.syslog4j.impl.net.tcp.ssl.SSLTCPNetSyslogConfigIF;
import org.graylog2.syslog4j.impl.net.tcp.ssl.SSLTCPNetSyslogWriter;
/**
* PooledSSLTCPNetSyslogConfig is an extension of PooledTCPNetSyslogConfig
* which provides configuration support for the Apache Commons Pool.
*
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: PooledSSLTCPNetSyslogConfig.java,v 1.2 2009/03/29 17:38:58 cvs Exp $
*/
* PooledSSLTCPNetSyslogConfig is an extension of PooledTCPNetSyslogConfig
* which provides configuration support for the Apache Commons Pool.
* <p/>
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: PooledSSLTCPNetSyslogConfig.java,v 1.2 2009/03/29 17:38:58 cvs Exp $
*/
public class PooledSSLTCPNetSyslogConfig extends PooledTCPNetSyslogConfig implements SSLTCPNetSyslogConfigIF {
private static final long serialVersionUID = 2092268298395023976L;
private static final long serialVersionUID = 2092268298395023976L;
protected String keyStore = null;
protected String keyStorePassword = null;
protected String keyStore = null;
protected String keyStorePassword = null;
protected String trustStore = null;
protected String trustStorePassword = null;
protected String trustStore = null;
protected String trustStorePassword = null;
public PooledSSLTCPNetSyslogConfig() {
super();
}
public PooledSSLTCPNetSyslogConfig() {
super();
}
public PooledSSLTCPNetSyslogConfig(int facility, String host, int port) {
super(facility, host, port);
}
public PooledSSLTCPNetSyslogConfig(int facility, String host, int port) {
super(facility, host, port);
}
public PooledSSLTCPNetSyslogConfig(int facility, String host) {
super(facility, host);
}
public PooledSSLTCPNetSyslogConfig(int facility, String host) {
super(facility, host);
}
public PooledSSLTCPNetSyslogConfig(int facility) {
super(facility);
}
public PooledSSLTCPNetSyslogConfig(int facility) {
super(facility);
}
public PooledSSLTCPNetSyslogConfig(String host, int port) {
super(host, port);
}
public PooledSSLTCPNetSyslogConfig(String host, int port) {
super(host, port);
}
public PooledSSLTCPNetSyslogConfig(String host) {
super(host);
}
public String getKeyStore() {
return this.keyStore;
}
public void setKeyStore(String keyStore) {
this.keyStore = keyStore;
}
public String getKeyStorePassword() {
return this.keyStorePassword;
}
public void setKeyStorePassword(String keyStorePassword) {
this.keyStorePassword = keyStorePassword;
}
public PooledSSLTCPNetSyslogConfig(String host) {
super(host);
}
public String getTrustStore() {
return this.trustStore;
}
public String getKeyStore() {
return this.keyStore;
}
public void setTrustStore(String trustStore) {
this.trustStore = trustStore;
}
public void setKeyStore(String keyStore) {
this.keyStore = keyStore;
}
public String getTrustStorePassword() {
return this.trustStorePassword;
}
public String getKeyStorePassword() {
return this.keyStorePassword;
}
public void setTrustStorePassword(String trustStorePassword) {
this.trustStorePassword = trustStorePassword;
}
public void setKeyStorePassword(String keyStorePassword) {
this.keyStorePassword = keyStorePassword;
}
public Class getSyslogClass() {
return SSLTCPNetSyslog.class;
}
public String getTrustStore() {
return this.trustStore;
}
public Class getSyslogWriterClass() {
return SSLTCPNetSyslogWriter.class;
}
public void setTrustStore(String trustStore) {
this.trustStore = trustStore;
}
public String getTrustStorePassword() {
return this.trustStorePassword;
}
public void setTrustStorePassword(String trustStorePassword) {
this.trustStorePassword = trustStorePassword;
}
public Class getSyslogClass() {
return SSLTCPNetSyslog.class;
}
public Class getSyslogWriterClass() {
return SSLTCPNetSyslogWriter.class;
}
}

View File

@ -11,94 +11,94 @@ import org.graylog2.syslog4j.impl.AbstractSyslogWriter;
import org.graylog2.syslog4j.impl.net.AbstractNetSyslog;
/**
* UDPNetSyslog is an extension of AbstractSyslog that provides support for
* UDP/IP-based syslog clients.
*
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: UDPNetSyslog.java,v 1.18 2010/10/27 06:18:10 cvs Exp $
*/
* UDPNetSyslog is an extension of AbstractSyslog that provides support for
* UDP/IP-based syslog clients.
* <p/>
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: UDPNetSyslog.java,v 1.18 2010/10/27 06:18:10 cvs Exp $
*/
public class UDPNetSyslog extends AbstractNetSyslog {
private static final long serialVersionUID = 5259485504549037999L;
protected DatagramSocket socket = null;
public void initialize() throws SyslogRuntimeException {
super.initialize();
createDatagramSocket(true);
}
protected synchronized void createDatagramSocket(boolean initialize) {
try {
this.socket = new DatagramSocket();
} catch (SocketException se) {
if (initialize) {
if (this.syslogConfig.isThrowExceptionOnInitialize()) {
throw new SyslogRuntimeException(se);
}
} else {
throw new SyslogRuntimeException(se);
}
}
if (this.socket == null) {
throw new SyslogRuntimeException("Cannot seem to get a Datagram socket");
}
}
private static final long serialVersionUID = 5259485504549037999L;
protected DatagramSocket socket = null;
public void initialize() throws SyslogRuntimeException {
super.initialize();
createDatagramSocket(true);
}
protected synchronized void createDatagramSocket(boolean initialize) {
try {
this.socket = new DatagramSocket();
} catch (SocketException se) {
if (initialize) {
if (this.syslogConfig.isThrowExceptionOnInitialize()) {
throw new SyslogRuntimeException(se);
}
} else {
throw new SyslogRuntimeException(se);
}
}
if (this.socket == null) {
throw new SyslogRuntimeException("Cannot seem to get a Datagram socket");
}
}
protected void write(int level, byte[] message) throws SyslogRuntimeException {
if (this.socket == null) {
createDatagramSocket(false);
}
InetAddress hostAddress = getHostAddress();
protected void write(int level, byte[] message) throws SyslogRuntimeException {
if (this.socket == null) {
createDatagramSocket(false);
}
InetAddress hostAddress = getHostAddress();
DatagramPacket packet = new DatagramPacket(
message,
message.length,
hostAddress,
this.syslogConfig.getPort()
message,
message.length,
hostAddress,
this.syslogConfig.getPort()
);
int attempts = 0;
while(attempts != -1 && attempts < (this.netSyslogConfig.getWriteRetries() + 1)) {
try {
this.socket.send(packet);
attempts = -1;
} catch (IOException ioe) {
if (attempts == (this.netSyslogConfig.getWriteRetries() + 1)) {
throw new SyslogRuntimeException(ioe);
}
}
while (attempts != -1 && attempts < (this.netSyslogConfig.getWriteRetries() + 1)) {
try {
this.socket.send(packet);
attempts = -1;
} catch (IOException ioe) {
if (attempts == (this.netSyslogConfig.getWriteRetries() + 1)) {
throw new SyslogRuntimeException(ioe);
}
}
}
}
}
public void flush() throws SyslogRuntimeException {
shutdown();
createDatagramSocket(true);
}
public void shutdown() throws SyslogRuntimeException {
if (this.socket != null) {
this.socket.close();
this.socket = null;
}
}
public void flush() throws SyslogRuntimeException {
shutdown();
public AbstractSyslogWriter getWriter() {
return null;
}
createDatagramSocket(true);
}
public void returnWriter(AbstractSyslogWriter syslogWriter) {
//
}
public void shutdown() throws SyslogRuntimeException {
if (this.socket != null) {
this.socket.close();
this.socket = null;
}
}
public AbstractSyslogWriter getWriter() {
return null;
}
public void returnWriter(AbstractSyslogWriter syslogWriter) {
//
}
}

View File

@ -3,44 +3,44 @@ package org.graylog2.syslog4j.impl.net.udp;
import org.graylog2.syslog4j.impl.net.AbstractNetSyslogConfig;
/**
* UDPNetSyslogConfig is an extension of AbstractNetSyslogConfig that provides
* configuration support for UDP/IP-based syslog clients.
*
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: UDPNetSyslogConfig.java,v 1.6 2008/11/14 04:32:00 cvs Exp $
*/
* UDPNetSyslogConfig is an extension of AbstractNetSyslogConfig that provides
* configuration support for UDP/IP-based syslog clients.
* <p/>
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: UDPNetSyslogConfig.java,v 1.6 2008/11/14 04:32:00 cvs Exp $
*/
public class UDPNetSyslogConfig extends AbstractNetSyslogConfig {
private static final long serialVersionUID = 4465067182562754345L;
public UDPNetSyslogConfig() {
super();
}
private static final long serialVersionUID = 4465067182562754345L;
public UDPNetSyslogConfig(int facility, String host, int port) {
super(facility,host,port);
}
public UDPNetSyslogConfig() {
super();
}
public UDPNetSyslogConfig(int facility, String host) {
super(facility,host);
}
public UDPNetSyslogConfig(int facility, String host, int port) {
super(facility, host, port);
}
public UDPNetSyslogConfig(int facility) {
super(facility);
}
public UDPNetSyslogConfig(int facility, String host) {
super(facility, host);
}
public UDPNetSyslogConfig(String host, int port) {
super(host,port);
}
public UDPNetSyslogConfig(int facility) {
super(facility);
}
public UDPNetSyslogConfig(String host) {
super(host);
}
public UDPNetSyslogConfig(String host, int port) {
super(host, port);
}
public Class getSyslogClass() {
return UDPNetSyslog.class;
}
public UDPNetSyslogConfig(String host) {
super(host);
}
public Class getSyslogClass() {
return UDPNetSyslog.class;
}
}

View File

@ -8,77 +8,77 @@ import org.graylog2.syslog4j.impl.AbstractSyslogConfigIF;
import org.graylog2.syslog4j.impl.AbstractSyslogWriter;
/**
* AbstractSyslogPoolFactory is an abstract implementation of the Apache Commons Pool
* BasePoolableObjectFactory.
*
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: AbstractSyslogPoolFactory.java,v 1.5 2008/12/10 04:15:11 cvs Exp $
* @see org.graylog2.syslog4j.impl.pool.generic.GenericSyslogPoolFactory
*/
* AbstractSyslogPoolFactory is an abstract implementation of the Apache Commons Pool
* BasePoolableObjectFactory.
* <p/>
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: AbstractSyslogPoolFactory.java,v 1.5 2008/12/10 04:15:11 cvs Exp $
* @see org.graylog2.syslog4j.impl.pool.generic.GenericSyslogPoolFactory
*/
public abstract class AbstractSyslogPoolFactory extends BasePoolableObjectFactory {
private static final long serialVersionUID = -7441569603980981508L;
protected AbstractSyslog syslog = null;
protected AbstractSyslogConfigIF syslogConfig = null;
protected ObjectPool pool = null;
public AbstractSyslogPoolFactory() {
//
}
private static final long serialVersionUID = -7441569603980981508L;
public void initialize(AbstractSyslog abstractSyslog) throws SyslogRuntimeException {
this.syslog = abstractSyslog;
try {
this.syslogConfig = (AbstractSyslogConfigIF) this.syslog.getConfig();
protected AbstractSyslog syslog = null;
protected AbstractSyslogConfigIF syslogConfig = null;
} catch (ClassCastException cce) {
throw new SyslogRuntimeException("config must implement AbstractSyslogConfigIF");
}
this.pool = createPool();
}
protected ObjectPool pool = null;
public Object makeObject() throws Exception {
AbstractSyslogWriter syslogWriter = this.syslog.createWriter();
if (this.syslogConfig.isThreaded()) {
this.syslog.createWriterThread(syslogWriter);
}
return syslogWriter;
}
public AbstractSyslogPoolFactory() {
//
}
public void destroyObject(Object obj) throws Exception {
AbstractSyslogWriter writer = (AbstractSyslogWriter) obj;
public void initialize(AbstractSyslog abstractSyslog) throws SyslogRuntimeException {
this.syslog = abstractSyslog;
writer.shutdown();
super.destroyObject(writer);
}
public abstract ObjectPool createPool() throws SyslogRuntimeException;
public AbstractSyslogWriter borrowSyslogWriter() throws Exception {
AbstractSyslogWriter syslogWriter = (AbstractSyslogWriter) this.pool.borrowObject();
return syslogWriter;
}
try {
this.syslogConfig = (AbstractSyslogConfigIF) this.syslog.getConfig();
public void returnSyslogWriter(AbstractSyslogWriter syslogWriter) throws Exception {
this.pool.returnObject(syslogWriter);
}
} catch (ClassCastException cce) {
throw new SyslogRuntimeException("config must implement AbstractSyslogConfigIF");
}
public void clear() throws Exception {
this.pool.clear();
}
public void close() throws Exception {
this.pool.close();
}
this.pool = createPool();
}
public Object makeObject() throws Exception {
AbstractSyslogWriter syslogWriter = this.syslog.createWriter();
if (this.syslogConfig.isThreaded()) {
this.syslog.createWriterThread(syslogWriter);
}
return syslogWriter;
}
public void destroyObject(Object obj) throws Exception {
AbstractSyslogWriter writer = (AbstractSyslogWriter) obj;
writer.shutdown();
super.destroyObject(writer);
}
public abstract ObjectPool createPool() throws SyslogRuntimeException;
public AbstractSyslogWriter borrowSyslogWriter() throws Exception {
AbstractSyslogWriter syslogWriter = (AbstractSyslogWriter) this.pool.borrowObject();
return syslogWriter;
}
public void returnSyslogWriter(AbstractSyslogWriter syslogWriter) throws Exception {
this.pool.returnObject(syslogWriter);
}
public void clear() throws Exception {
this.pool.clear();
}
public void close() throws Exception {
this.pool.close();
}
}

View File

@ -7,46 +7,46 @@ import org.graylog2.syslog4j.SyslogRuntimeException;
import org.graylog2.syslog4j.impl.pool.AbstractSyslogPoolFactory;
/**
* GenericSyslogPoolFactory is an implementation of the Apache Commons Pool
* BasePoolableObjectFactory using a GenericObjectPool.
*
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: GenericSyslogPoolFactory.java,v 1.5 2008/12/10 04:15:10 cvs Exp $
*/
* GenericSyslogPoolFactory is an implementation of the Apache Commons Pool
* BasePoolableObjectFactory using a GenericObjectPool.
* <p/>
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: GenericSyslogPoolFactory.java,v 1.5 2008/12/10 04:15:10 cvs Exp $
*/
public class GenericSyslogPoolFactory extends AbstractSyslogPoolFactory {
protected void configureGenericObjectPool(GenericObjectPool genericObjectPool) throws SyslogRuntimeException {
SyslogPoolConfigIF poolConfig = null;
try {
poolConfig = (SyslogPoolConfigIF) this.syslog.getConfig();
} catch (ClassCastException cce) {
throw new SyslogRuntimeException("config must implement interface SyslogPoolConfigIF");
}
genericObjectPool.setMaxActive(poolConfig.getMaxActive());
genericObjectPool.setMaxIdle(poolConfig.getMaxIdle());
genericObjectPool.setMaxWait(poolConfig.getMaxWait());
genericObjectPool.setMinEvictableIdleTimeMillis(poolConfig.getMinEvictableIdleTimeMillis());
genericObjectPool.setMinIdle(poolConfig.getMinIdle());
genericObjectPool.setNumTestsPerEvictionRun(poolConfig.getNumTestsPerEvictionRun());
genericObjectPool.setSoftMinEvictableIdleTimeMillis(poolConfig.getSoftMinEvictableIdleTimeMillis());
genericObjectPool.setTestOnBorrow(poolConfig.isTestOnBorrow());
genericObjectPool.setTestOnReturn(poolConfig.isTestOnReturn());
genericObjectPool.setTestWhileIdle(poolConfig.isTestWhileIdle());
genericObjectPool.setTimeBetweenEvictionRunsMillis(poolConfig.getTimeBetweenEvictionRunsMillis());
genericObjectPool.setWhenExhaustedAction(poolConfig.getWhenExhaustedAction());
}
public ObjectPool createPool() throws SyslogRuntimeException {
GenericObjectPool genericPool = new GenericObjectPool(this);
configureGenericObjectPool(genericPool);
return genericPool;
}
protected void configureGenericObjectPool(GenericObjectPool genericObjectPool) throws SyslogRuntimeException {
SyslogPoolConfigIF poolConfig = null;
try {
poolConfig = (SyslogPoolConfigIF) this.syslog.getConfig();
} catch (ClassCastException cce) {
throw new SyslogRuntimeException("config must implement interface SyslogPoolConfigIF");
}
genericObjectPool.setMaxActive(poolConfig.getMaxActive());
genericObjectPool.setMaxIdle(poolConfig.getMaxIdle());
genericObjectPool.setMaxWait(poolConfig.getMaxWait());
genericObjectPool.setMinEvictableIdleTimeMillis(poolConfig.getMinEvictableIdleTimeMillis());
genericObjectPool.setMinIdle(poolConfig.getMinIdle());
genericObjectPool.setNumTestsPerEvictionRun(poolConfig.getNumTestsPerEvictionRun());
genericObjectPool.setSoftMinEvictableIdleTimeMillis(poolConfig.getSoftMinEvictableIdleTimeMillis());
genericObjectPool.setTestOnBorrow(poolConfig.isTestOnBorrow());
genericObjectPool.setTestOnReturn(poolConfig.isTestOnReturn());
genericObjectPool.setTestWhileIdle(poolConfig.isTestWhileIdle());
genericObjectPool.setTimeBetweenEvictionRunsMillis(poolConfig.getTimeBetweenEvictionRunsMillis());
genericObjectPool.setWhenExhaustedAction(poolConfig.getWhenExhaustedAction());
}
public ObjectPool createPool() throws SyslogRuntimeException {
GenericObjectPool genericPool = new GenericObjectPool(this);
configureGenericObjectPool(genericPool);
return genericPool;
}
}

View File

@ -11,115 +11,117 @@ import com.sun.jna.Memory;
import com.sun.jna.Native;
/**
* UnixSyslog is an extension of AbstractSyslog that provides support for
* Unix-based syslog clients.
*
* <p>This class requires the JNA (Java Native Access) library to directly
* access the native C libraries utilized on Unix platforms.</p>
*
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: UnixSyslog.java,v 1.27 2010/10/25 04:21:19 cvs Exp $
*/
* UnixSyslog is an extension of AbstractSyslog that provides support for
* Unix-based syslog clients.
* <p/>
* <p>This class requires the JNA (Java Native Access) library to directly
* access the native C libraries utilized on Unix platforms.</p>
* <p/>
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: UnixSyslog.java,v 1.27 2010/10/25 04:21:19 cvs Exp $
*/
public class UnixSyslog extends AbstractSyslog {
private static final long serialVersionUID = 4973353204252276740L;
protected UnixSyslogConfig unixSyslogConfig = null;
private static final long serialVersionUID = 4973353204252276740L;
protected UnixSyslogConfig unixSyslogConfig = null;
protected interface CLibrary extends Library {
public void openlog(final Memory ident, int option, int facility);
public void syslog(int priority, final String format, final String message);
public void closelog();
}
protected static int currentFacility = -1;
protected static int currentFacility = -1;
protected static boolean openlogCalled = false;
protected static CLibrary libraryInstance = null;
protected static synchronized void loadLibrary(UnixSyslogConfig config) throws SyslogRuntimeException {
if (!OSDetectUtility.isUnix()) {
throw new SyslogRuntimeException("UnixSyslog not supported on non-Unix platforms");
}
if (libraryInstance == null) {
libraryInstance = (CLibrary) Native.loadLibrary(config.getLibrary(),CLibrary.class);
}
}
protected static synchronized void loadLibrary(UnixSyslogConfig config) throws SyslogRuntimeException {
if (!OSDetectUtility.isUnix()) {
throw new SyslogRuntimeException("UnixSyslog not supported on non-Unix platforms");
}
public void initialize() throws SyslogRuntimeException {
try {
this.unixSyslogConfig = (UnixSyslogConfig) this.syslogConfig;
} catch (ClassCastException cce) {
throw new SyslogRuntimeException("config must be of type UnixSyslogConfig");
}
loadLibrary(this.unixSyslogConfig);
}
protected static void write(int level, String message, UnixSyslogConfig config) throws SyslogRuntimeException {
synchronized(libraryInstance) {
if (currentFacility != config.getFacility()) {
if (openlogCalled) {
libraryInstance.closelog();
openlogCalled = false;
}
currentFacility = config.getFacility();
}
if (!openlogCalled) {
String ident = config.getIdent();
if (ident != null && "".equals(ident.trim())) {
ident = null;
}
Memory identBuffer = null;
if (ident != null) {
identBuffer = new Memory(128);
identBuffer.setString(0, ident, false);
}
libraryInstance.openlog(identBuffer,config.getOption(),currentFacility);
openlogCalled = true;
}
if (libraryInstance == null) {
libraryInstance = (CLibrary) Native.loadLibrary(config.getLibrary(), CLibrary.class);
}
}
int priority = currentFacility | level;
libraryInstance.syslog(priority,"%s",message);
}
}
public void initialize() throws SyslogRuntimeException {
try {
this.unixSyslogConfig = (UnixSyslogConfig) this.syslogConfig;
protected void write(int level, byte[] message) throws SyslogRuntimeException {
// NO-OP
}
} catch (ClassCastException cce) {
throw new SyslogRuntimeException("config must be of type UnixSyslogConfig");
}
public void log(SyslogMessageProcessorIF messageProcessor, int level, String message) {
write(level,message,this.unixSyslogConfig);
}
public void flush() throws SyslogRuntimeException {
synchronized(libraryInstance) {
libraryInstance.closelog();
openlogCalled = false;
}
}
loadLibrary(this.unixSyslogConfig);
}
public void shutdown() throws SyslogRuntimeException {
flush();
}
protected static void write(int level, String message, UnixSyslogConfig config) throws SyslogRuntimeException {
synchronized (libraryInstance) {
if (currentFacility != config.getFacility()) {
if (openlogCalled) {
libraryInstance.closelog();
openlogCalled = false;
}
public AbstractSyslogWriter getWriter() {
return null;
}
currentFacility = config.getFacility();
}
public void returnWriter(AbstractSyslogWriter syslogWriter) {
//
}
if (!openlogCalled) {
String ident = config.getIdent();
if (ident != null && "".equals(ident.trim())) {
ident = null;
}
Memory identBuffer = null;
if (ident != null) {
identBuffer = new Memory(128);
identBuffer.setString(0, ident, false);
}
libraryInstance.openlog(identBuffer, config.getOption(), currentFacility);
openlogCalled = true;
}
int priority = currentFacility | level;
libraryInstance.syslog(priority, "%s", message);
}
}
protected void write(int level, byte[] message) throws SyslogRuntimeException {
// NO-OP
}
public void log(SyslogMessageProcessorIF messageProcessor, int level, String message) {
write(level, message, this.unixSyslogConfig);
}
public void flush() throws SyslogRuntimeException {
synchronized (libraryInstance) {
libraryInstance.closelog();
openlogCalled = false;
}
}
public void shutdown() throws SyslogRuntimeException {
flush();
}
public AbstractSyslogWriter getWriter() {
return null;
}
public void returnWriter(AbstractSyslogWriter syslogWriter) {
//
}
}

View File

@ -4,68 +4,68 @@ import org.graylog2.syslog4j.SyslogRuntimeException;
import org.graylog2.syslog4j.impl.AbstractSyslogConfig;
/**
* UnixSyslogConfig is an extension of AbstractNetSyslogConfig that provides
* configuration support for Unix-based syslog clients.
*
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: UnixSyslogConfig.java,v 1.13 2010/10/25 03:50:25 cvs Exp $
*/
* UnixSyslogConfig is an extension of AbstractNetSyslogConfig that provides
* configuration support for Unix-based syslog clients.
* <p/>
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: UnixSyslogConfig.java,v 1.13 2010/10/25 03:50:25 cvs Exp $
*/
public class UnixSyslogConfig extends AbstractSyslogConfig {
private static final long serialVersionUID = -4805767812011660656L;
private static final long serialVersionUID = -4805767812011660656L;
protected String library = SYSLOG_LIBRARY_DEFAULT;
protected int option = OPTION_NONE;
public UnixSyslogConfig() {
// Unix-based syslog does not need localName sent
this.setSendLocalName(false);
}
protected String library = SYSLOG_LIBRARY_DEFAULT;
protected int option = OPTION_NONE;
public Class getSyslogClass() {
return UnixSyslog.class;
}
public UnixSyslogConfig() {
// Unix-based syslog does not need localName sent
this.setSendLocalName(false);
}
public String getHost() {
return null;
}
public Class getSyslogClass() {
return UnixSyslog.class;
}
public int getPort() {
return 0;
}
public String getHost() {
return null;
}
public void setHost(String host) throws SyslogRuntimeException {
throw new SyslogRuntimeException("Host not appropriate for class \"" + this.getClass().getName() + "\"");
}
public int getPort() {
return 0;
}
public void setPort(int port) throws SyslogRuntimeException {
throw new SyslogRuntimeException("Port not appropriate for class \"" + this.getClass().getName() + "\"");
}
public void setHost(String host) throws SyslogRuntimeException {
throw new SyslogRuntimeException("Host not appropriate for class \"" + this.getClass().getName() + "\"");
}
public String getLibrary() {
return this.library;
}
public void setPort(int port) throws SyslogRuntimeException {
throw new SyslogRuntimeException("Port not appropriate for class \"" + this.getClass().getName() + "\"");
}
public void setLibrary(String library) {
this.library = library;
}
public String getLibrary() {
return this.library;
}
public int getOption() {
return this.option;
}
public void setLibrary(String library) {
this.library = library;
}
public void setOption(int option) {
this.option = option;
}
public int getOption() {
return this.option;
}
public int getMaxQueueSize() {
throw new SyslogRuntimeException("UnixSyslog protocol does not uses a queueing mechanism");
}
public void setOption(int option) {
this.option = option;
}
public void setMaxQueueSize(int maxQueueSize) {
throw new SyslogRuntimeException("UnixSyslog protocol does not uses a queueing mechanism");
}
public int getMaxQueueSize() {
throw new SyslogRuntimeException("UnixSyslog protocol does not uses a queueing mechanism");
}
public void setMaxQueueSize(int maxQueueSize) {
throw new SyslogRuntimeException("UnixSyslog protocol does not uses a queueing mechanism");
}
}

View File

@ -12,132 +12,136 @@ import com.sun.jna.Native;
import com.sun.jna.Structure;
/**
* UnixSocketSyslog is an extension of AbstractSyslog that provides support for
* Unix socket-based syslog clients.
*
* <p>This class requires the JNA (Java Native Access) library to directly
* access the native C libraries utilized on Unix platforms.</p>
*
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: UnixSocketSyslog.java,v 1.13 2010/11/16 00:52:01 cvs Exp $
*/
* UnixSocketSyslog is an extension of AbstractSyslog that provides support for
* Unix socket-based syslog clients.
* <p/>
* <p>This class requires the JNA (Java Native Access) library to directly
* access the native C libraries utilized on Unix platforms.</p>
* <p/>
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: UnixSocketSyslog.java,v 1.13 2010/11/16 00:52:01 cvs Exp $
*/
public class UnixSocketSyslog extends AbstractSyslog {
private static final long serialVersionUID = 39878807911936785L;
protected static class SockAddr extends Structure {
public final static int SUN_PATH_SIZE = 108;
public final static byte[] ZERO_BYTE = new byte[] { 0 };
public short sun_family = 1;
public byte[] sun_path = new byte[SUN_PATH_SIZE];
public void setSunPath(String sunPath) {
System.arraycopy(sunPath.getBytes(), 0,this.sun_path, 0, sunPath.length());
System.arraycopy(ZERO_BYTE,0,this.sun_path,sunPath.length(),1);
}
}
private static final long serialVersionUID = 39878807911936785L;
protected static class SockAddr extends Structure {
public final static int SUN_PATH_SIZE = 108;
public final static byte[] ZERO_BYTE = new byte[]{0};
public short sun_family = 1;
public byte[] sun_path = new byte[SUN_PATH_SIZE];
public void setSunPath(String sunPath) {
System.arraycopy(sunPath.getBytes(), 0, this.sun_path, 0, sunPath.length());
System.arraycopy(ZERO_BYTE, 0, this.sun_path, sunPath.length(), 1);
}
}
protected interface CLibrary extends Library {
public int socket(int domain, int type, int protocol);
public int connect(int sockfd, SockAddr sockaddr, int addrlen);
public int write(int fd, ByteBuffer buffer, int count);
public int close(int fd);
public String strerror(int errno);
}
protected boolean libraryLoaded = false;
protected boolean libraryLoaded = false;
protected CLibrary libraryInstance = null;
protected UnixSocketSyslogConfig unixSocketSyslogConfig = null;
protected int fd = -1;
protected synchronized void loadLibrary() {
if (!OSDetectUtility.isUnix()) {
throw new SyslogRuntimeException("UnixSyslog not supported on non-Unix platforms");
}
if (!this.libraryLoaded) {
this.libraryInstance = (CLibrary) Native.loadLibrary(this.unixSocketSyslogConfig.getLibrary(),CLibrary.class);
this.libraryLoaded = true;
}
}
public void initialize() throws SyslogRuntimeException {
try {
this.unixSocketSyslogConfig = (UnixSocketSyslogConfig) this.syslogConfig;
} catch (ClassCastException cce) {
throw new SyslogRuntimeException("config must be of type UnixSocketSyslogConfig");
}
loadLibrary();
}
protected synchronized void connect() {
if (this.fd != -1) {
return;
}
this.fd = this.libraryInstance.socket(this.unixSocketSyslogConfig.getFamily(),this.unixSocketSyslogConfig.getType(),this.unixSocketSyslogConfig.getProtocol());
if (this.fd == -1) {
this.fd = -1;
return;
}
SockAddr sockAddr = new SockAddr();
sockAddr.sun_family = this.unixSocketSyslogConfig.getFamily();
sockAddr.setSunPath(this.unixSocketSyslogConfig.getPath());
int c = this.libraryInstance.connect(this.fd, sockAddr, sockAddr.size());
protected UnixSocketSyslogConfig unixSocketSyslogConfig = null;
protected int fd = -1;
if (c == -1) {
this.fd = -1;
return;
}
}
protected synchronized void loadLibrary() {
if (!OSDetectUtility.isUnix()) {
throw new SyslogRuntimeException("UnixSyslog not supported on non-Unix platforms");
}
protected void write(int level, byte[] message) throws SyslogRuntimeException {
if (this.fd == -1) {
connect();
}
if (this.fd == -1) {
return;
}
ByteBuffer byteBuffer = ByteBuffer.wrap(message);
this.libraryInstance.write(this.fd,byteBuffer,message.length);
}
if (!this.libraryLoaded) {
this.libraryInstance = (CLibrary) Native.loadLibrary(this.unixSocketSyslogConfig.getLibrary(), CLibrary.class);
this.libraryLoaded = true;
}
}
public void flush() throws SyslogRuntimeException {
shutdown();
this.fd = this.libraryInstance.socket(this.unixSocketSyslogConfig.getFamily(),this.unixSocketSyslogConfig.getType(),this.unixSocketSyslogConfig.getProtocol());
}
public void shutdown() throws SyslogRuntimeException {
if (this.fd == -1) {
return;
}
this.libraryInstance.close(this.fd);
this.fd = -1;
}
public AbstractSyslogWriter getWriter() {
return null;
}
public void initialize() throws SyslogRuntimeException {
try {
this.unixSocketSyslogConfig = (UnixSocketSyslogConfig) this.syslogConfig;
public void returnWriter(AbstractSyslogWriter syslogWriter) {
//
}
} catch (ClassCastException cce) {
throw new SyslogRuntimeException("config must be of type UnixSocketSyslogConfig");
}
loadLibrary();
}
protected synchronized void connect() {
if (this.fd != -1) {
return;
}
this.fd = this.libraryInstance.socket(this.unixSocketSyslogConfig.getFamily(), this.unixSocketSyslogConfig.getType(), this.unixSocketSyslogConfig.getProtocol());
if (this.fd == -1) {
this.fd = -1;
return;
}
SockAddr sockAddr = new SockAddr();
sockAddr.sun_family = this.unixSocketSyslogConfig.getFamily();
sockAddr.setSunPath(this.unixSocketSyslogConfig.getPath());
int c = this.libraryInstance.connect(this.fd, sockAddr, sockAddr.size());
if (c == -1) {
this.fd = -1;
return;
}
}
protected void write(int level, byte[] message) throws SyslogRuntimeException {
if (this.fd == -1) {
connect();
}
if (this.fd == -1) {
return;
}
ByteBuffer byteBuffer = ByteBuffer.wrap(message);
this.libraryInstance.write(this.fd, byteBuffer, message.length);
}
public void flush() throws SyslogRuntimeException {
shutdown();
this.fd = this.libraryInstance.socket(this.unixSocketSyslogConfig.getFamily(), this.unixSocketSyslogConfig.getType(), this.unixSocketSyslogConfig.getProtocol());
}
public void shutdown() throws SyslogRuntimeException {
if (this.fd == -1) {
return;
}
this.libraryInstance.close(this.fd);
this.fd = -1;
}
public AbstractSyslogWriter getWriter() {
return null;
}
public void returnWriter(AbstractSyslogWriter syslogWriter) {
//
}
}

View File

@ -4,138 +4,138 @@ import org.graylog2.syslog4j.SyslogRuntimeException;
import org.graylog2.syslog4j.impl.AbstractSyslogConfig;
/**
* UnixSocketSyslogConfig is an extension of AbstractNetSyslogConfig that provides
* configuration support for Unix socket-based syslog clients.
*
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: UnixSocketSyslogConfig.java,v 1.8 2010/11/12 03:43:12 cvs Exp $
*/
* UnixSocketSyslogConfig is an extension of AbstractNetSyslogConfig that provides
* configuration support for Unix socket-based syslog clients.
* <p/>
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: UnixSocketSyslogConfig.java,v 1.8 2010/11/12 03:43:12 cvs Exp $
*/
public class UnixSocketSyslogConfig extends AbstractSyslogConfig {
private static final long serialVersionUID = -3145794243736015707L;
private static final long serialVersionUID = -3145794243736015707L;
protected int type = SYSLOG_SOCKET_TYPE_DEFAULT;
protected short family = SYSLOG_SOCKET_FAMILY_DEFAULT;
protected int protocol = SYSLOG_SOCKET_PROTOCOL_DEFAULT;
protected String library = SYSLOG_SOCKET_LIBRARY_DEFAULT;
protected String path = SYSLOG_SOCKET_PATH_DEFAULT;
public UnixSocketSyslogConfig() {
// Unix-based socket does not need localName sent
this.setSendLocalName(false);
this.setIdent("java");
}
public Class getSyslogClass() {
return UnixSocketSyslog.class;
}
protected int type = SYSLOG_SOCKET_TYPE_DEFAULT;
protected short family = SYSLOG_SOCKET_FAMILY_DEFAULT;
protected int protocol = SYSLOG_SOCKET_PROTOCOL_DEFAULT;
protected String library = SYSLOG_SOCKET_LIBRARY_DEFAULT;
protected String path = SYSLOG_SOCKET_PATH_DEFAULT;
public UnixSocketSyslogConfig(int facility) {
this.facility = facility;
}
public UnixSocketSyslogConfig() {
// Unix-based socket does not need localName sent
this.setSendLocalName(false);
this.setIdent("java");
}
public UnixSocketSyslogConfig(int facility, String path) {
this.facility = facility;
this.path = path;
}
public Class getSyslogClass() {
return UnixSocketSyslog.class;
}
public UnixSocketSyslogConfig(String path) {
this.path = path;
}
public UnixSocketSyslogConfig(int facility) {
this.facility = facility;
}
public String getHost() {
return null;
}
public UnixSocketSyslogConfig(int facility, String path) {
this.facility = facility;
this.path = path;
}
public int getPort() {
return -1;
}
public UnixSocketSyslogConfig(String path) {
this.path = path;
}
public void setHost(String host) throws SyslogRuntimeException {
throw new SyslogRuntimeException("Host not appropriate for class \"" + this.getClass().getName() + "\"");
}
public String getHost() {
return null;
}
public void setPort(int port) throws SyslogRuntimeException {
throw new SyslogRuntimeException("Port not appropriate for class \"" + this.getClass().getName() + "\"");
}
public int getPort() {
return -1;
}
public String getLibrary() {
return this.library;
}
public void setHost(String host) throws SyslogRuntimeException {
throw new SyslogRuntimeException("Host not appropriate for class \"" + this.getClass().getName() + "\"");
}
public void setLibrary(String library) {
this.library = library;
}
public void setPort(int port) throws SyslogRuntimeException {
throw new SyslogRuntimeException("Port not appropriate for class \"" + this.getClass().getName() + "\"");
}
public String getPath() {
return this.path;
}
public String getLibrary() {
return this.library;
}
public void setPath(String path) {
this.path = path;
}
public int getType() {
return this.type;
}
public void setType(int type) {
this.type = type;
}
public void setType(String type) {
if (type == null) {
throw new SyslogRuntimeException("Type cannot be null for class \"" + this.getClass().getName() + "\"");
}
if ("SOCK_STREAM".equalsIgnoreCase(type.trim())) {
this.type = SOCK_STREAM;
} else if ("SOCK_DGRAM".equalsIgnoreCase(type.trim())) {
this.type = SOCK_DGRAM;
} else {
throw new SyslogRuntimeException("Type must be \"SOCK_STREAM\" or \"SOCK_DGRAM\" for class \"" + this.getClass().getName() + "\"");
}
}
public void setLibrary(String library) {
this.library = library;
}
public short getFamily() {
return this.family;
}
public String getPath() {
return this.path;
}
public void setFamily(short family) {
this.family = family;
}
public void setPath(String path) {
this.path = path;
}
public void setFamily(String family) {
if (family == null) {
throw new SyslogRuntimeException("Family cannot be null for class \"" + this.getClass().getName() + "\"");
}
if ("AF_UNIX".equalsIgnoreCase(family.trim())) {
this.family = AF_UNIX;
} else {
throw new SyslogRuntimeException("Family must be \"AF_UNIX\" for class \"" + this.getClass().getName() + "\"");
}
}
public int getType() {
return this.type;
}
public int getProtocol() {
return this.protocol;
}
public void setType(int type) {
this.type = type;
}
public void setProtocol(int protocol) {
this.protocol = protocol;
}
public void setType(String type) {
if (type == null) {
throw new SyslogRuntimeException("Type cannot be null for class \"" + this.getClass().getName() + "\"");
}
public int getMaxQueueSize() {
return -1;
}
if ("SOCK_STREAM".equalsIgnoreCase(type.trim())) {
this.type = SOCK_STREAM;
public void setMaxQueueSize(int maxQueueSize) {
throw new SyslogRuntimeException("UnixSyslog protocol does not uses a queueing mechanism");
}
} else if ("SOCK_DGRAM".equalsIgnoreCase(type.trim())) {
this.type = SOCK_DGRAM;
} else {
throw new SyslogRuntimeException("Type must be \"SOCK_STREAM\" or \"SOCK_DGRAM\" for class \"" + this.getClass().getName() + "\"");
}
}
public short getFamily() {
return this.family;
}
public void setFamily(short family) {
this.family = family;
}
public void setFamily(String family) {
if (family == null) {
throw new SyslogRuntimeException("Family cannot be null for class \"" + this.getClass().getName() + "\"");
}
if ("AF_UNIX".equalsIgnoreCase(family.trim())) {
this.family = AF_UNIX;
} else {
throw new SyslogRuntimeException("Family must be \"AF_UNIX\" for class \"" + this.getClass().getName() + "\"");
}
}
public int getProtocol() {
return this.protocol;
}
public void setProtocol(int protocol) {
this.protocol = protocol;
}
public int getMaxQueueSize() {
return -1;
}
public void setMaxQueueSize(int maxQueueSize) {
throw new SyslogRuntimeException("UnixSyslog protocol does not uses a queueing mechanism");
}
}

View File

@ -15,225 +15,225 @@ import org.graylog2.syslog4j.util.SyslogUtility;
/**
* This class provides a Singleton-based interface for Syslog4j
* server implementations.
*
* <p/>
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: SyslogServer.java,v 1.14 2011/01/23 20:49:12 cvs Exp $
*/
public class SyslogServer implements SyslogConstants {
private static final long serialVersionUID = -2260889360828258602L;
private static final long serialVersionUID = -2260889360828258602L;
private static boolean SUPPRESS_RUNTIME_EXCEPTIONS = false;
private static boolean SUPPRESS_RUNTIME_EXCEPTIONS = false;
protected static final Map instances = new Hashtable();
static {
initialize();
}
private SyslogServer() {
//
}
protected static final Map instances = new Hashtable();
/**
* @return Returns the current version identifier for Syslog4j.
*/
public static final String getVersion() {
return Syslog4jVersion.VERSION;
}
static {
initialize();
}
/**
* @param suppress - true to suppress throwing SyslogRuntimeException in many methods of this class, false to throw exceptions (default)
*/
public static void setSuppressRuntimeExceptions(boolean suppress) {
SUPPRESS_RUNTIME_EXCEPTIONS = suppress;
}
/**
* @return Returns whether or not to suppress throwing SyslogRuntimeException in many methods of this class
*/
public static boolean getSuppressRuntimeExceptions() {
return SUPPRESS_RUNTIME_EXCEPTIONS;
}
/**
* Throws SyslogRuntimeException unless it has been suppressed via setSuppressRuntimeException(boolean).
*
* @param message
* @throws SyslogRuntimeException
*/
private static void throwRuntimeException(String message) throws SyslogRuntimeException {
if (SUPPRESS_RUNTIME_EXCEPTIONS) {
return;
} else {
throw new SyslogRuntimeException(message.toString());
}
}
private SyslogServer() {
//
}
public static final SyslogServerIF getInstance(String protocol) throws SyslogRuntimeException {
String syslogProtocol = protocol.toLowerCase();
if (instances.containsKey(syslogProtocol)) {
return (SyslogServerIF) instances.get(syslogProtocol);
} else {
throwRuntimeException("SyslogServer instance \"" + syslogProtocol + "\" not defined; use \"tcp\" or \"udp\" or call SyslogServer.createInstance(protocol,config) first");
return null;
}
}
public static final SyslogServerIF getThreadedInstance(String protocol) throws SyslogRuntimeException {
SyslogServerIF server = getInstance(protocol);
/**
* @return Returns the current version identifier for Syslog4j.
*/
public static final String getVersion() {
return Syslog4jVersion.VERSION;
}
if (server.getThread() == null) {
Thread thread = new Thread(server);
thread.setName("SyslogServer: " + protocol);
thread.setDaemon(server.getConfig().isUseDaemonThread());
if (server.getConfig().getThreadPriority() > -1) {
thread.setPriority(server.getConfig().getThreadPriority());
}
server.setThread(thread);
thread.start();
}
return server;
}
public static final boolean exists(String protocol) {
if (protocol == null || "".equals(protocol.trim())) {
return false;
}
return instances.containsKey(protocol.toLowerCase());
}
public static final SyslogServerIF createInstance(String protocol, SyslogServerConfigIF config) throws SyslogRuntimeException {
if (protocol == null || "".equals(protocol.trim())) {
throwRuntimeException("Instance protocol cannot be null or empty");
return null;
}
if (config == null) {
throwRuntimeException("SyslogServerConfig cannot be null");
return null;
}
String syslogProtocol = protocol.toLowerCase();
SyslogServerIF syslogServer = null;
synchronized(instances) {
if (instances.containsKey(syslogProtocol)) {
throwRuntimeException("SyslogServer instance \"" + syslogProtocol + "\" already defined.");
return null;
}
try {
Class syslogClass = config.getSyslogServerClass();
syslogServer = (SyslogServerIF) syslogClass.newInstance();
} catch (ClassCastException cse) {
throw new SyslogRuntimeException(cse);
} catch (IllegalAccessException iae) {
throw new SyslogRuntimeException(iae);
} catch (InstantiationException ie) {
throw new SyslogRuntimeException(ie);
}
syslogServer.initialize(syslogProtocol,config);
instances.put(syslogProtocol,syslogServer);
}
return syslogServer;
}
/**
* @param suppress - true to suppress throwing SyslogRuntimeException in many methods of this class, false to throw exceptions (default)
*/
public static void setSuppressRuntimeExceptions(boolean suppress) {
SUPPRESS_RUNTIME_EXCEPTIONS = suppress;
}
public static final SyslogServerIF createThreadedInstance(String protocol, SyslogServerConfigIF config) throws SyslogRuntimeException {
createInstance(protocol,config);
SyslogServerIF server = getThreadedInstance(protocol);
return server;
}
/**
* @return Returns whether or not to suppress throwing SyslogRuntimeException in many methods of this class
*/
public static boolean getSuppressRuntimeExceptions() {
return SUPPRESS_RUNTIME_EXCEPTIONS;
}
public synchronized static final void destroyInstance(String protocol) {
if (protocol == null || "".equals(protocol.trim())) {
return;
}
/**
* Throws SyslogRuntimeException unless it has been suppressed via setSuppressRuntimeException(boolean).
*
* @param message
* @throws SyslogRuntimeException
*/
private static void throwRuntimeException(String message) throws SyslogRuntimeException {
if (SUPPRESS_RUNTIME_EXCEPTIONS) {
return;
String _protocol = protocol.toLowerCase();
if (instances.containsKey(_protocol)) {
SyslogUtility.sleep(SyslogConstants.THREAD_LOOP_INTERVAL_DEFAULT);
SyslogServerIF syslogServer = (SyslogServerIF) instances.get(_protocol);
} else {
throw new SyslogRuntimeException(message.toString());
}
}
try {
syslogServer.shutdown();
} finally {
instances.remove(_protocol);
}
} else {
throwRuntimeException("Cannot destroy server protocol \"" + protocol + "\" instance; call shutdown instead");
return;
}
}
public synchronized static final void destroyInstance(SyslogServerIF syslogServer) {
if (syslogServer == null) {
return;
}
String protocol = syslogServer.getProtocol().toLowerCase();
if (instances.containsKey(protocol)) {
SyslogUtility.sleep(SyslogConstants.THREAD_LOOP_INTERVAL_DEFAULT);
try {
syslogServer.shutdown();
} finally {
instances.remove(protocol);
}
} else {
throwRuntimeException("Cannot destroy server protocol \"" + protocol + "\" instance; call shutdown instead");
}
}
public synchronized static void initialize() {
createInstance(UDP,new UDPNetSyslogServerConfig());
createInstance(TCP,new TCPNetSyslogServerConfig());
}
public synchronized static final void shutdown() throws SyslogRuntimeException {
Set protocols = instances.keySet();
Iterator i = protocols.iterator();
while(i.hasNext()) {
String protocol = (String) i.next();
SyslogServerIF syslogServer = (SyslogServerIF) instances.get(protocol);
public static final SyslogServerIF getInstance(String protocol) throws SyslogRuntimeException {
String syslogProtocol = protocol.toLowerCase();
syslogServer.shutdown();
}
if (instances.containsKey(syslogProtocol)) {
return (SyslogServerIF) instances.get(syslogProtocol);
instances.clear();
}
public static void main(String[] args) throws Exception {
SyslogServerMain.main(args);
}
} else {
throwRuntimeException("SyslogServer instance \"" + syslogProtocol + "\" not defined; use \"tcp\" or \"udp\" or call SyslogServer.createInstance(protocol,config) first");
return null;
}
}
public static final SyslogServerIF getThreadedInstance(String protocol) throws SyslogRuntimeException {
SyslogServerIF server = getInstance(protocol);
if (server.getThread() == null) {
Thread thread = new Thread(server);
thread.setName("SyslogServer: " + protocol);
thread.setDaemon(server.getConfig().isUseDaemonThread());
if (server.getConfig().getThreadPriority() > -1) {
thread.setPriority(server.getConfig().getThreadPriority());
}
server.setThread(thread);
thread.start();
}
return server;
}
public static final boolean exists(String protocol) {
if (protocol == null || "".equals(protocol.trim())) {
return false;
}
return instances.containsKey(protocol.toLowerCase());
}
public static final SyslogServerIF createInstance(String protocol, SyslogServerConfigIF config) throws SyslogRuntimeException {
if (protocol == null || "".equals(protocol.trim())) {
throwRuntimeException("Instance protocol cannot be null or empty");
return null;
}
if (config == null) {
throwRuntimeException("SyslogServerConfig cannot be null");
return null;
}
String syslogProtocol = protocol.toLowerCase();
SyslogServerIF syslogServer = null;
synchronized (instances) {
if (instances.containsKey(syslogProtocol)) {
throwRuntimeException("SyslogServer instance \"" + syslogProtocol + "\" already defined.");
return null;
}
try {
Class syslogClass = config.getSyslogServerClass();
syslogServer = (SyslogServerIF) syslogClass.newInstance();
} catch (ClassCastException cse) {
throw new SyslogRuntimeException(cse);
} catch (IllegalAccessException iae) {
throw new SyslogRuntimeException(iae);
} catch (InstantiationException ie) {
throw new SyslogRuntimeException(ie);
}
syslogServer.initialize(syslogProtocol, config);
instances.put(syslogProtocol, syslogServer);
}
return syslogServer;
}
public static final SyslogServerIF createThreadedInstance(String protocol, SyslogServerConfigIF config) throws SyslogRuntimeException {
createInstance(protocol, config);
SyslogServerIF server = getThreadedInstance(protocol);
return server;
}
public synchronized static final void destroyInstance(String protocol) {
if (protocol == null || "".equals(protocol.trim())) {
return;
}
String _protocol = protocol.toLowerCase();
if (instances.containsKey(_protocol)) {
SyslogUtility.sleep(SyslogConstants.THREAD_LOOP_INTERVAL_DEFAULT);
SyslogServerIF syslogServer = (SyslogServerIF) instances.get(_protocol);
try {
syslogServer.shutdown();
} finally {
instances.remove(_protocol);
}
} else {
throwRuntimeException("Cannot destroy server protocol \"" + protocol + "\" instance; call shutdown instead");
return;
}
}
public synchronized static final void destroyInstance(SyslogServerIF syslogServer) {
if (syslogServer == null) {
return;
}
String protocol = syslogServer.getProtocol().toLowerCase();
if (instances.containsKey(protocol)) {
SyslogUtility.sleep(SyslogConstants.THREAD_LOOP_INTERVAL_DEFAULT);
try {
syslogServer.shutdown();
} finally {
instances.remove(protocol);
}
} else {
throwRuntimeException("Cannot destroy server protocol \"" + protocol + "\" instance; call shutdown instead");
}
}
public synchronized static void initialize() {
createInstance(UDP, new UDPNetSyslogServerConfig());
createInstance(TCP, new TCPNetSyslogServerConfig());
}
public synchronized static final void shutdown() throws SyslogRuntimeException {
Set protocols = instances.keySet();
Iterator i = protocols.iterator();
while (i.hasNext()) {
String protocol = (String) i.next();
SyslogServerIF syslogServer = (SyslogServerIF) instances.get(protocol);
syslogServer.shutdown();
}
instances.clear();
}
public static void main(String[] args) throws Exception {
SyslogServerMain.main(args);
}
}

View File

@ -7,44 +7,54 @@ import org.graylog2.syslog4j.SyslogConstants;
import org.graylog2.syslog4j.SyslogRuntimeException;
/**
* SyslogServerConfigIF provides a common, extensible configuration interface for all
* implementations of SyslogServerIF.
*
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: SyslogServerConfigIF.java,v 1.12 2011/01/11 05:11:13 cvs Exp $
*/
* SyslogServerConfigIF provides a common, extensible configuration interface for all
* implementations of SyslogServerIF.
* <p/>
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: SyslogServerConfigIF.java,v 1.12 2011/01/11 05:11:13 cvs Exp $
*/
public interface SyslogServerConfigIF extends SyslogConstants, SyslogCharSetIF {
public Class getSyslogServerClass();
public Class getSyslogServerClass();
public String getHost();
public void setHost(String host) throws SyslogRuntimeException;
public String getHost();
public int getPort();
public void setPort(int port) throws SyslogRuntimeException;
public boolean isUseDaemonThread();
public void setUseDaemonThread(boolean useDaemonThread);
public int getThreadPriority();
public void setThreadPriority(int threadPriority);
public List getEventHandlers();
public long getShutdownWait();
public void setShutdownWait(long shutdownWait);
public void addEventHandler(SyslogServerEventHandlerIF eventHandler);
public void insertEventHandler(int pos, SyslogServerEventHandlerIF eventHandler);
public void removeEventHandler(SyslogServerEventHandlerIF eventHandler);
public void removeAllEventHandlers();
public boolean isUseStructuredData();
public void setUseStructuredData(boolean useStructuredData);
public Object getDateTimeFormatter();
public void setDateTimeFormatter(Object dateTimeFormatter);
public void setHost(String host) throws SyslogRuntimeException;
public int getPort();
public void setPort(int port) throws SyslogRuntimeException;
public boolean isUseDaemonThread();
public void setUseDaemonThread(boolean useDaemonThread);
public int getThreadPriority();
public void setThreadPriority(int threadPriority);
public List getEventHandlers();
public long getShutdownWait();
public void setShutdownWait(long shutdownWait);
public void addEventHandler(SyslogServerEventHandlerIF eventHandler);
public void insertEventHandler(int pos, SyslogServerEventHandlerIF eventHandler);
public void removeEventHandler(SyslogServerEventHandlerIF eventHandler);
public void removeAllEventHandlers();
public boolean isUseStructuredData();
public void setUseStructuredData(boolean useStructuredData);
public Object getDateTimeFormatter();
public void setDateTimeFormatter(Object dateTimeFormatter);
}

View File

@ -3,6 +3,7 @@ package org.graylog2.syslog4j.server;
import java.io.Serializable;
public abstract interface SyslogServerEventHandlerIF extends Serializable {
public void initialize(SyslogServerIF syslogServer);
public void destroy(SyslogServerIF syslogServer);
public void initialize(SyslogServerIF syslogServer);
public void destroy(SyslogServerIF syslogServer);
}

View File

@ -5,37 +5,43 @@ import java.util.Date;
import org.graylog2.syslog4j.SyslogCharSetIF;
/**
* SyslogServerEventIF provides an extensible interface for Syslog4j
* server events.
*
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: SyslogServerEventIF.java,v 1.4 2010/11/28 01:38:08 cvs Exp $
*/
* SyslogServerEventIF provides an extensible interface for Syslog4j
* server events.
* <p/>
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: SyslogServerEventIF.java,v 1.4 2010/11/28 01:38:08 cvs Exp $
*/
public interface SyslogServerEventIF extends SyslogCharSetIF {
/**
* Note: getRaw() may use System.arraycopy(..) each time it is called; best to call it once and store the result.
*
* @return Returns the raw data received from the client.
*/
public byte[] getRaw();
public int getFacility();
public void setFacility(int facility);
/**
* Note: getRaw() may use System.arraycopy(..) each time it is called; best to call it once and store the result.
*
* @return Returns the raw data received from the client.
*/
public byte[] getRaw();
public Date getDate();
public void setDate(Date date);
public int getLevel();
public void setLevel(int level);
public String getHost();
public void setHost(String host);
public boolean isHostStrippedFromMessage();
public String getMessage();
public void setMessage(String message);
public int getFacility();
public void setFacility(int facility);
public Date getDate();
public void setDate(Date date);
public int getLevel();
public void setLevel(int level);
public String getHost();
public void setHost(String host);
public boolean isHostStrippedFromMessage();
public String getMessage();
public void setMessage(String message);
}

View File

@ -3,25 +3,27 @@ package org.graylog2.syslog4j.server;
import org.graylog2.syslog4j.SyslogRuntimeException;
/**
* SyslogServerIF provides a common interface for all Syslog4j server implementations.
*
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: SyslogServerIF.java,v 1.5 2008/11/07 15:15:41 cvs Exp $
*/
* SyslogServerIF provides a common interface for all Syslog4j server implementations.
* <p/>
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: SyslogServerIF.java,v 1.5 2008/11/07 15:15:41 cvs Exp $
*/
public interface SyslogServerIF extends Runnable {
public void initialize(String protocol, SyslogServerConfigIF config) throws SyslogRuntimeException;
public String getProtocol();
public SyslogServerConfigIF getConfig();
public void initialize(String protocol, SyslogServerConfigIF config) throws SyslogRuntimeException;
public void run();
public Thread getThread();
public void setThread(Thread thread);
public String getProtocol();
public void shutdown();
public SyslogServerConfigIF getConfig();
public void run();
public Thread getThread();
public void setThread(Thread thread);
public void shutdown();
}

View File

@ -8,158 +8,200 @@ import org.graylog2.syslog4j.util.SyslogUtility;
/**
* This class provides a command-line interface for Syslog4j
* server implementations.
*
* <p/>
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: SyslogServerMain.java,v 1.3 2010/11/28 01:38:08 cvs Exp $
*/
public class SyslogServerMain {
public static boolean CALL_SYSTEM_EXIT_ON_FAILURE = true;
public static class Options {
public String protocol = null;
public String fileName = null;
public boolean append = false;
public boolean quiet = false;
public String host = null;
public String port = null;
public String timeout = null;
public String usage = null;
}
public static void usage(String problem) {
if (problem != null) {
System.out.println("Error: " + problem);
System.out.println();
}
System.out.println("Usage:");
System.out.println();
System.out.println("SyslogServer [-h <host>] [-p <port>] [-o <file>] [-a] [-q] <protocol>");
System.out.println();
System.out.println("-h <host> host or IP to bind");
System.out.println("-p <port> port to bind");
System.out.println("-t <timeout> socket timeout (in milliseconds)");
System.out.println("-o <file> file to write entries (overwrites by default)");
System.out.println();
System.out.println("-a append to file (instead of overwrite)");
System.out.println("-q do not write anything to standard out");
System.out.println();
System.out.println("protocol Syslog4j protocol implementation (tcp, udp, ...)");
}
public static Options parseOptions(String[] args) {
Options options = new Options();
int i = 0;
while(i < args.length) {
String arg = args[i++];
boolean match = false;
if ("-h".equals(arg)) { if (i == args.length) { options.usage = "Must specify host with -h"; return options; } match = true; options.host = args[i++]; }
if ("-p".equals(arg)) { if (i == args.length) { options.usage = "Must specify port with -p"; return options; } match = true; options.port = args[i++]; }
if ("-t".equals(arg)) { if (i == args.length) { options.usage = "Must specify value (in milliseconds)"; return options; } match = true; options.timeout = args[i++]; }
if ("-o".equals(arg)) { if (i == args.length) { options.usage = "Must specify file with -o"; return options; } match = true; options.fileName = args[i++]; }
if ("-a".equals(arg)) { match = true; options.append = true; }
if ("-q".equals(arg)) { match = true; options.quiet = true; }
if (!match) {
if (options.protocol != null) {
options.usage = "Only one protocol definition allowed";
return options;
}
options.protocol = arg;
}
}
if (options.protocol == null) {
options.usage = "Must specify protocol";
return options;
}
if (options.fileName == null && options.append) {
options.usage = "Cannot specify -a without specifying -f <file>";
return options;
}
return options;
}
public static void main(String[] args) throws Exception {
Options options = parseOptions(args);
public static boolean CALL_SYSTEM_EXIT_ON_FAILURE = true;
if (options.usage != null) {
usage(options.usage);
if (CALL_SYSTEM_EXIT_ON_FAILURE) { System.exit(1); } else { return; }
}
if (!options.quiet) {
System.out.println("SyslogServer " + SyslogServer.getVersion());
}
if (!SyslogServer.exists(options.protocol)) {
usage("Protocol \"" + options.protocol + "\" not supported");
if (CALL_SYSTEM_EXIT_ON_FAILURE) { System.exit(1); } else { return; }
}
SyslogServerIF syslogServer = SyslogServer.getInstance(options.protocol);
SyslogServerConfigIF syslogServerConfig = syslogServer.getConfig();
if (options.host != null) {
syslogServerConfig.setHost(options.host);
if (!options.quiet) {
System.out.println("Listening on host: " + options.host);
}
}
public static class Options {
public String protocol = null;
public String fileName = null;
public boolean append = false;
public boolean quiet = false;
if (options.port != null) {
syslogServerConfig.setPort(Integer.parseInt(options.port));
if (!options.quiet) {
System.out.println("Listening on port: " + options.port);
}
}
public String host = null;
public String port = null;
public String timeout = null;
if (options.timeout != null) {
if (syslogServerConfig instanceof TCPNetSyslogServerConfigIF) {
((TCPNetSyslogServerConfigIF) syslogServerConfig).setTimeout(Integer.parseInt(options.timeout));
if (!options.quiet) {
System.out.println("Timeout: " + options.timeout);
}
} else {
System.err.println("Timeout not supported for protocol \"" + options.protocol + "\" (ignored)");
}
}
public String usage = null;
}
if (options.fileName != null) {
SyslogServerEventHandlerIF eventHandler = new FileSyslogServerEventHandler(options.fileName,options.append);
syslogServerConfig.addEventHandler(eventHandler);
if (!options.quiet) {
System.out.println((options.append ? "Appending" : "Writing") + " to file: " + options.fileName);
}
}
if (!options.quiet) {
SyslogServerEventHandlerIF eventHandler = SystemOutSyslogServerEventHandler.create();
syslogServerConfig.addEventHandler(eventHandler);
}
public static void usage(String problem) {
if (problem != null) {
System.out.println("Error: " + problem);
System.out.println();
}
if (!options.quiet) {
System.out.println();
}
System.out.println("Usage:");
System.out.println();
System.out.println("SyslogServer [-h <host>] [-p <port>] [-o <file>] [-a] [-q] <protocol>");
System.out.println();
System.out.println("-h <host> host or IP to bind");
System.out.println("-p <port> port to bind");
System.out.println("-t <timeout> socket timeout (in milliseconds)");
System.out.println("-o <file> file to write entries (overwrites by default)");
System.out.println();
System.out.println("-a append to file (instead of overwrite)");
System.out.println("-q do not write anything to standard out");
System.out.println();
System.out.println("protocol Syslog4j protocol implementation (tcp, udp, ...)");
}
SyslogServer.getThreadedInstance(options.protocol);
while(true) {
SyslogUtility.sleep(1000);
}
}
public static Options parseOptions(String[] args) {
Options options = new Options();
int i = 0;
while (i < args.length) {
String arg = args[i++];
boolean match = false;
if ("-h".equals(arg)) {
if (i == args.length) {
options.usage = "Must specify host with -h";
return options;
}
match = true;
options.host = args[i++];
}
if ("-p".equals(arg)) {
if (i == args.length) {
options.usage = "Must specify port with -p";
return options;
}
match = true;
options.port = args[i++];
}
if ("-t".equals(arg)) {
if (i == args.length) {
options.usage = "Must specify value (in milliseconds)";
return options;
}
match = true;
options.timeout = args[i++];
}
if ("-o".equals(arg)) {
if (i == args.length) {
options.usage = "Must specify file with -o";
return options;
}
match = true;
options.fileName = args[i++];
}
if ("-a".equals(arg)) {
match = true;
options.append = true;
}
if ("-q".equals(arg)) {
match = true;
options.quiet = true;
}
if (!match) {
if (options.protocol != null) {
options.usage = "Only one protocol definition allowed";
return options;
}
options.protocol = arg;
}
}
if (options.protocol == null) {
options.usage = "Must specify protocol";
return options;
}
if (options.fileName == null && options.append) {
options.usage = "Cannot specify -a without specifying -f <file>";
return options;
}
return options;
}
public static void main(String[] args) throws Exception {
Options options = parseOptions(args);
if (options.usage != null) {
usage(options.usage);
if (CALL_SYSTEM_EXIT_ON_FAILURE) {
System.exit(1);
} else {
return;
}
}
if (!options.quiet) {
System.out.println("SyslogServer " + SyslogServer.getVersion());
}
if (!SyslogServer.exists(options.protocol)) {
usage("Protocol \"" + options.protocol + "\" not supported");
if (CALL_SYSTEM_EXIT_ON_FAILURE) {
System.exit(1);
} else {
return;
}
}
SyslogServerIF syslogServer = SyslogServer.getInstance(options.protocol);
SyslogServerConfigIF syslogServerConfig = syslogServer.getConfig();
if (options.host != null) {
syslogServerConfig.setHost(options.host);
if (!options.quiet) {
System.out.println("Listening on host: " + options.host);
}
}
if (options.port != null) {
syslogServerConfig.setPort(Integer.parseInt(options.port));
if (!options.quiet) {
System.out.println("Listening on port: " + options.port);
}
}
if (options.timeout != null) {
if (syslogServerConfig instanceof TCPNetSyslogServerConfigIF) {
((TCPNetSyslogServerConfigIF) syslogServerConfig).setTimeout(Integer.parseInt(options.timeout));
if (!options.quiet) {
System.out.println("Timeout: " + options.timeout);
}
} else {
System.err.println("Timeout not supported for protocol \"" + options.protocol + "\" (ignored)");
}
}
if (options.fileName != null) {
SyslogServerEventHandlerIF eventHandler = new FileSyslogServerEventHandler(options.fileName, options.append);
syslogServerConfig.addEventHandler(eventHandler);
if (!options.quiet) {
System.out.println((options.append ? "Appending" : "Writing") + " to file: " + options.fileName);
}
}
if (!options.quiet) {
SyslogServerEventHandlerIF eventHandler = SystemOutSyslogServerEventHandler.create();
syslogServerConfig.addEventHandler(eventHandler);
}
if (!options.quiet) {
System.out.println();
}
SyslogServer.getThreadedInstance(options.protocol);
while (true) {
SyslogUtility.sleep(1000);
}
}
}

View File

@ -3,8 +3,11 @@ package org.graylog2.syslog4j.server;
import java.net.SocketAddress;
public interface SyslogServerSessionEventHandlerIF extends SyslogServerEventHandlerIF {
public Object sessionOpened(SyslogServerIF syslogServer, SocketAddress socketAddress);
public void event(Object session, SyslogServerIF syslogServer, SocketAddress socketAddress, SyslogServerEventIF event);
public void exception(Object session, SyslogServerIF syslogServer, SocketAddress socketAddress, Exception exception);
public void sessionClosed(Object session, SyslogServerIF syslogServer, SocketAddress socketAddress, boolean timeout);
public Object sessionOpened(SyslogServerIF syslogServer, SocketAddress socketAddress);
public void event(Object session, SyslogServerIF syslogServer, SocketAddress socketAddress, SyslogServerEventIF event);
public void exception(Object session, SyslogServerIF syslogServer, SocketAddress socketAddress, Exception exception);
public void sessionClosed(Object session, SyslogServerIF syslogServer, SocketAddress socketAddress, boolean timeout);
}

View File

@ -4,17 +4,18 @@ import java.net.SocketAddress;
/**
* SyslogServerEventHandlerIF provides an extensible interface for Syslog4j
* server event handlers.
*
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: SyslogServerSessionlessEventHandlerIF.java,v 1.1 2010/11/12 02:56:44 cvs Exp $
*/
* SyslogServerEventHandlerIF provides an extensible interface for Syslog4j
* server event handlers.
* <p/>
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: SyslogServerSessionlessEventHandlerIF.java,v 1.1 2010/11/12 02:56:44 cvs Exp $
*/
public interface SyslogServerSessionlessEventHandlerIF extends SyslogServerEventHandlerIF {
public void event(SyslogServerIF syslogServer, SocketAddress socketAddress, SyslogServerEventIF event);
public void exception(SyslogServerIF syslogServer, SocketAddress socketAddress, Exception exception);
public void event(SyslogServerIF syslogServer, SocketAddress socketAddress, SyslogServerEventIF event);
public void exception(SyslogServerIF syslogServer, SocketAddress socketAddress, Exception exception);
}

View File

@ -22,318 +22,318 @@ import org.graylog2.syslog4j.server.impl.event.structured.StructuredSyslogServer
import org.graylog2.syslog4j.util.SyslogUtility;
/**
* AbstractSyslogServer provides a base abstract implementation of the SyslogServerIF.
*
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: AbstractSyslogServer.java,v 1.12 2011/01/11 05:11:13 cvs Exp $
*/
* AbstractSyslogServer provides a base abstract implementation of the SyslogServerIF.
* <p/>
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: AbstractSyslogServer.java,v 1.12 2011/01/11 05:11:13 cvs Exp $
*/
public abstract class AbstractSyslogServer implements SyslogServerIF {
public static class Sessions extends HashMap {
private static final long serialVersionUID = -4438949276263772580L;
public static final Object syncObject = new Object();
public static class Sessions extends HashMap {
private static final long serialVersionUID = -4438949276263772580L;
public void addSocket(Socket socket) {
synchronized(syncObject) {
put(socket,new HashMap());
}
}
public Iterator getSockets() {
if (size() > 0) {
return keySet().iterator();
} else {
return null;
}
}
public static final Object syncObject = new Object();
public void addSession(Socket socket, SyslogServerEventHandlerIF eventHandler, Object session) {
synchronized(syncObject) {
Map handlerMap = getHandlerMap(socket);
if (handlerMap == null) {
handlerMap = new HashMap();
}
handlerMap.put(eventHandler,session);
}
}
public void addSocket(Socket socket) {
synchronized (syncObject) {
put(socket, new HashMap());
}
}
public void removeSocket(Socket socket) {
synchronized(syncObject) {
Map handlerMap = getHandlerMap(socket);
if (handlerMap != null) {
handlerMap.clear();
}
}
}
public Iterator getSockets() {
if (size() > 0) {
return keySet().iterator();
protected Map getHandlerMap(Socket socket) {
Map handlerMap = null;
if (containsKey(socket)) {
handlerMap = (Map) get(socket);
}
return handlerMap;
}
} else {
return null;
}
}
public Object getSession(Socket socket, SyslogServerEventHandlerIF eventHandler) {
synchronized(syncObject) {
Map handlerMap = getHandlerMap(socket);
Object session = handlerMap.get(eventHandler);
return session;
}
}
}
protected String syslogProtocol = null;
protected AbstractSyslogServerConfig syslogServerConfig = null;
protected Thread thread = null;
protected boolean shutdown = false;
public void initialize(String protocol, SyslogServerConfigIF config) throws SyslogRuntimeException {
this.syslogProtocol = protocol;
try {
this.syslogServerConfig = (AbstractSyslogServerConfig) config;
} catch (ClassCastException cce) {
throw new SyslogRuntimeException(cce);
}
initialize();
}
public String getProtocol() {
return this.syslogProtocol;
}
public void addSession(Socket socket, SyslogServerEventHandlerIF eventHandler, Object session) {
synchronized (syncObject) {
Map handlerMap = getHandlerMap(socket);
public SyslogServerConfigIF getConfig() {
return this.syslogServerConfig;
}
protected abstract void initialize() throws SyslogRuntimeException;
public void shutdown() throws SyslogRuntimeException {
this.shutdown = true;
}
if (handlerMap == null) {
handlerMap = new HashMap();
}
public Thread getThread() {
return this.thread;
}
handlerMap.put(eventHandler, session);
}
}
public void setThread(Thread thread) {
this.thread = thread;
}
protected static boolean isStructuredMessage(SyslogCharSetIF syslogCharSet, byte[] receiveData) {
String receiveDataString = SyslogUtility.newString(syslogCharSet, receiveData);
public void removeSocket(Socket socket) {
synchronized (syncObject) {
Map handlerMap = getHandlerMap(socket);
boolean isStructuredMessage = isStructuredMessage(syslogCharSet,receiveDataString);
return isStructuredMessage;
}
if (handlerMap != null) {
handlerMap.clear();
}
}
}
protected static boolean isStructuredMessage(SyslogCharSetIF syslogCharSet, String receiveData) {
int idx = receiveData.indexOf('>');
protected Map getHandlerMap(Socket socket) {
Map handlerMap = null;
if (idx != -1) {
// If there's a numerical VERSION field after the <priority>, return true.
if (receiveData.length() > idx + 1 && Character.isDigit(receiveData.charAt(idx + 1))) {
return true;
}
}
if (containsKey(socket)) {
handlerMap = (Map) get(socket);
}
return false;
}
return handlerMap;
}
protected static SyslogServerEventIF createEvent(SyslogServerConfigIF serverConfig, byte[] lineBytes, int lineBytesLength, InetAddress inetAddr) {
SyslogServerEventIF event = null;
if (serverConfig.isUseStructuredData() && AbstractSyslogServer.isStructuredMessage(serverConfig,lineBytes)) {
event = new StructuredSyslogServerEvent(lineBytes,lineBytesLength,inetAddr);
if (serverConfig.getDateTimeFormatter() != null) {
((StructuredSyslogServerEvent) event).setDateTimeFormatter(serverConfig.getDateTimeFormatter());
}
} else {
event = new SyslogServerEvent(lineBytes,lineBytesLength,inetAddr);
}
return event;
}
protected static SyslogServerEventIF createEvent(SyslogServerConfigIF serverConfig, String line, InetAddress inetAddr) {
SyslogServerEventIF event = null;
if (serverConfig.isUseStructuredData() && AbstractSyslogServer.isStructuredMessage(serverConfig,line)) {
event = new StructuredSyslogServerEvent(line,inetAddr);
} else {
event = new SyslogServerEvent(line,inetAddr);
}
return event;
}
public static void handleInitialize(SyslogServerIF syslogServer) {
List eventHandlers = syslogServer.getConfig().getEventHandlers();
for(int i=0; i<eventHandlers.size(); i++) {
SyslogServerEventHandlerIF eventHandler = (SyslogServerEventHandlerIF) eventHandlers.get(i);
public Object getSession(Socket socket, SyslogServerEventHandlerIF eventHandler) {
synchronized (syncObject) {
Map handlerMap = getHandlerMap(socket);
try {
eventHandler.initialize(syslogServer);
} catch (Exception exception) {
//
}
}
}
Object session = handlerMap.get(eventHandler);
public static void handleDestroy(SyslogServerIF syslogServer) {
List eventHandlers = syslogServer.getConfig().getEventHandlers();
for(int i=0; i<eventHandlers.size(); i++) {
SyslogServerEventHandlerIF eventHandler = (SyslogServerEventHandlerIF) eventHandlers.get(i);
return session;
}
}
}
try {
eventHandler.destroy(syslogServer);
} catch (Exception exception) {
//
}
}
}
protected String syslogProtocol = null;
protected AbstractSyslogServerConfig syslogServerConfig = null;
protected Thread thread = null;
public static void handleSessionOpen(Sessions sessions, SyslogServerIF syslogServer, Socket socket) {
List eventHandlers = syslogServer.getConfig().getEventHandlers();
for(int i=0; i<eventHandlers.size(); i++) {
SyslogServerEventHandlerIF eventHandler = (SyslogServerEventHandlerIF) eventHandlers.get(i);
if (eventHandler instanceof SyslogServerSessionEventHandlerIF) {
try {
Object session = ((SyslogServerSessionEventHandlerIF) eventHandler).sessionOpened(syslogServer,socket.getRemoteSocketAddress());
if (session != null) {
sessions.addSession(socket,eventHandler,session);
}
} catch (Exception exception) {
try {
((SyslogServerSessionEventHandlerIF) eventHandler).exception(null,syslogServer,socket.getRemoteSocketAddress(),exception);
} catch (Exception e) {
//
}
}
}
}
}
protected boolean shutdown = false;
public static void handleSessionClosed(Sessions sessions, SyslogServerIF syslogServer, Socket socket, boolean timeout) {
List eventHandlers = syslogServer.getConfig().getEventHandlers();
for(int i=0; i<eventHandlers.size(); i++) {
SyslogServerEventHandlerIF eventHandler = (SyslogServerEventHandlerIF) eventHandlers.get(i);
public void initialize(String protocol, SyslogServerConfigIF config) throws SyslogRuntimeException {
this.syslogProtocol = protocol;
if (eventHandler instanceof SyslogServerSessionEventHandlerIF) {
Object session = sessions.getSession(socket,eventHandler);
try {
((SyslogServerSessionEventHandlerIF) eventHandler).sessionClosed(session,syslogServer,socket.getRemoteSocketAddress(),timeout);
} catch (Exception exception) {
try {
((SyslogServerSessionEventHandlerIF) eventHandler).exception(session,syslogServer,socket.getRemoteSocketAddress(),exception);
} catch (Exception e) {
//
}
}
}
}
}
try {
this.syslogServerConfig = (AbstractSyslogServerConfig) config;
public static void handleEvent(Sessions sessions, SyslogServerIF syslogServer, DatagramPacket packet, SyslogServerEventIF event) {
handleEvent(sessions,syslogServer,null,packet.getSocketAddress(),event);
}
} catch (ClassCastException cce) {
throw new SyslogRuntimeException(cce);
}
public static void handleEvent(Sessions sessions, SyslogServerIF syslogServer, Socket socket, SyslogServerEventIF event) {
handleEvent(sessions,syslogServer,socket,socket.getRemoteSocketAddress(),event);
}
initialize();
}
protected static void handleEvent(Sessions sessions, SyslogServerIF syslogServer, Socket socket, SocketAddress socketAddress, SyslogServerEventIF event) {
List eventHandlers = syslogServer.getConfig().getEventHandlers();
for(int i=0; i<eventHandlers.size(); i++) {
SyslogServerEventHandlerIF eventHandler = (SyslogServerEventHandlerIF) eventHandlers.get(i);
Object session = (sessions != null && socket != null) ? sessions.getSession(socket,eventHandler) : null;
if (eventHandler instanceof SyslogServerSessionEventHandlerIF) {
try {
((SyslogServerSessionEventHandlerIF) eventHandler).event(session,syslogServer,socketAddress,event);
} catch (Exception exception) {
try {
((SyslogServerSessionEventHandlerIF) eventHandler).exception(session,syslogServer,socketAddress,exception);
} catch (Exception e) {
//
}
}
} else if (eventHandler instanceof SyslogServerSessionlessEventHandlerIF) {
try {
((SyslogServerSessionlessEventHandlerIF) eventHandler).event(syslogServer,socketAddress,event);
} catch (Exception exception) {
try {
((SyslogServerSessionlessEventHandlerIF) eventHandler).exception(syslogServer,socketAddress,exception);
} catch (Exception e) {
//
}
}
}
}
}
public String getProtocol() {
return this.syslogProtocol;
}
public static void handleException(Object session, SyslogServerIF syslogServer, SocketAddress socketAddress, Exception exception) {
List eventHandlers = syslogServer.getConfig().getEventHandlers();
for(int i=0; i<eventHandlers.size(); i++) {
SyslogServerEventHandlerIF eventHandler = (SyslogServerEventHandlerIF) eventHandlers.get(i);
public SyslogServerConfigIF getConfig() {
return this.syslogServerConfig;
}
if (eventHandler instanceof SyslogServerSessionEventHandlerIF) {
try {
((SyslogServerSessionEventHandlerIF) eventHandler).exception(session,syslogServer,socketAddress,exception);
} catch (Exception e) {
//
}
} else if (eventHandler instanceof SyslogServerSessionlessEventHandlerIF) {
try {
((SyslogServerSessionlessEventHandlerIF) eventHandler).exception(syslogServer,socketAddress,exception);
} catch (Exception e) {
//
}
}
}
}
protected abstract void initialize() throws SyslogRuntimeException;
public void shutdown() throws SyslogRuntimeException {
this.shutdown = true;
}
public Thread getThread() {
return this.thread;
}
public void setThread(Thread thread) {
this.thread = thread;
}
protected static boolean isStructuredMessage(SyslogCharSetIF syslogCharSet, byte[] receiveData) {
String receiveDataString = SyslogUtility.newString(syslogCharSet, receiveData);
boolean isStructuredMessage = isStructuredMessage(syslogCharSet, receiveDataString);
return isStructuredMessage;
}
protected static boolean isStructuredMessage(SyslogCharSetIF syslogCharSet, String receiveData) {
int idx = receiveData.indexOf('>');
if (idx != -1) {
// If there's a numerical VERSION field after the <priority>, return true.
if (receiveData.length() > idx + 1 && Character.isDigit(receiveData.charAt(idx + 1))) {
return true;
}
}
return false;
}
protected static SyslogServerEventIF createEvent(SyslogServerConfigIF serverConfig, byte[] lineBytes, int lineBytesLength, InetAddress inetAddr) {
SyslogServerEventIF event = null;
if (serverConfig.isUseStructuredData() && AbstractSyslogServer.isStructuredMessage(serverConfig, lineBytes)) {
event = new StructuredSyslogServerEvent(lineBytes, lineBytesLength, inetAddr);
if (serverConfig.getDateTimeFormatter() != null) {
((StructuredSyslogServerEvent) event).setDateTimeFormatter(serverConfig.getDateTimeFormatter());
}
} else {
event = new SyslogServerEvent(lineBytes, lineBytesLength, inetAddr);
}
return event;
}
protected static SyslogServerEventIF createEvent(SyslogServerConfigIF serverConfig, String line, InetAddress inetAddr) {
SyslogServerEventIF event = null;
if (serverConfig.isUseStructuredData() && AbstractSyslogServer.isStructuredMessage(serverConfig, line)) {
event = new StructuredSyslogServerEvent(line, inetAddr);
} else {
event = new SyslogServerEvent(line, inetAddr);
}
return event;
}
public static void handleInitialize(SyslogServerIF syslogServer) {
List eventHandlers = syslogServer.getConfig().getEventHandlers();
for (int i = 0; i < eventHandlers.size(); i++) {
SyslogServerEventHandlerIF eventHandler = (SyslogServerEventHandlerIF) eventHandlers.get(i);
try {
eventHandler.initialize(syslogServer);
} catch (Exception exception) {
//
}
}
}
public static void handleDestroy(SyslogServerIF syslogServer) {
List eventHandlers = syslogServer.getConfig().getEventHandlers();
for (int i = 0; i < eventHandlers.size(); i++) {
SyslogServerEventHandlerIF eventHandler = (SyslogServerEventHandlerIF) eventHandlers.get(i);
try {
eventHandler.destroy(syslogServer);
} catch (Exception exception) {
//
}
}
}
public static void handleSessionOpen(Sessions sessions, SyslogServerIF syslogServer, Socket socket) {
List eventHandlers = syslogServer.getConfig().getEventHandlers();
for (int i = 0; i < eventHandlers.size(); i++) {
SyslogServerEventHandlerIF eventHandler = (SyslogServerEventHandlerIF) eventHandlers.get(i);
if (eventHandler instanceof SyslogServerSessionEventHandlerIF) {
try {
Object session = ((SyslogServerSessionEventHandlerIF) eventHandler).sessionOpened(syslogServer, socket.getRemoteSocketAddress());
if (session != null) {
sessions.addSession(socket, eventHandler, session);
}
} catch (Exception exception) {
try {
((SyslogServerSessionEventHandlerIF) eventHandler).exception(null, syslogServer, socket.getRemoteSocketAddress(), exception);
} catch (Exception e) {
//
}
}
}
}
}
public static void handleSessionClosed(Sessions sessions, SyslogServerIF syslogServer, Socket socket, boolean timeout) {
List eventHandlers = syslogServer.getConfig().getEventHandlers();
for (int i = 0; i < eventHandlers.size(); i++) {
SyslogServerEventHandlerIF eventHandler = (SyslogServerEventHandlerIF) eventHandlers.get(i);
if (eventHandler instanceof SyslogServerSessionEventHandlerIF) {
Object session = sessions.getSession(socket, eventHandler);
try {
((SyslogServerSessionEventHandlerIF) eventHandler).sessionClosed(session, syslogServer, socket.getRemoteSocketAddress(), timeout);
} catch (Exception exception) {
try {
((SyslogServerSessionEventHandlerIF) eventHandler).exception(session, syslogServer, socket.getRemoteSocketAddress(), exception);
} catch (Exception e) {
//
}
}
}
}
}
public static void handleEvent(Sessions sessions, SyslogServerIF syslogServer, DatagramPacket packet, SyslogServerEventIF event) {
handleEvent(sessions, syslogServer, null, packet.getSocketAddress(), event);
}
public static void handleEvent(Sessions sessions, SyslogServerIF syslogServer, Socket socket, SyslogServerEventIF event) {
handleEvent(sessions, syslogServer, socket, socket.getRemoteSocketAddress(), event);
}
protected static void handleEvent(Sessions sessions, SyslogServerIF syslogServer, Socket socket, SocketAddress socketAddress, SyslogServerEventIF event) {
List eventHandlers = syslogServer.getConfig().getEventHandlers();
for (int i = 0; i < eventHandlers.size(); i++) {
SyslogServerEventHandlerIF eventHandler = (SyslogServerEventHandlerIF) eventHandlers.get(i);
Object session = (sessions != null && socket != null) ? sessions.getSession(socket, eventHandler) : null;
if (eventHandler instanceof SyslogServerSessionEventHandlerIF) {
try {
((SyslogServerSessionEventHandlerIF) eventHandler).event(session, syslogServer, socketAddress, event);
} catch (Exception exception) {
try {
((SyslogServerSessionEventHandlerIF) eventHandler).exception(session, syslogServer, socketAddress, exception);
} catch (Exception e) {
//
}
}
} else if (eventHandler instanceof SyslogServerSessionlessEventHandlerIF) {
try {
((SyslogServerSessionlessEventHandlerIF) eventHandler).event(syslogServer, socketAddress, event);
} catch (Exception exception) {
try {
((SyslogServerSessionlessEventHandlerIF) eventHandler).exception(syslogServer, socketAddress, exception);
} catch (Exception e) {
//
}
}
}
}
}
public static void handleException(Object session, SyslogServerIF syslogServer, SocketAddress socketAddress, Exception exception) {
List eventHandlers = syslogServer.getConfig().getEventHandlers();
for (int i = 0; i < eventHandlers.size(); i++) {
SyslogServerEventHandlerIF eventHandler = (SyslogServerEventHandlerIF) eventHandlers.get(i);
if (eventHandler instanceof SyslogServerSessionEventHandlerIF) {
try {
((SyslogServerSessionEventHandlerIF) eventHandler).exception(session, syslogServer, socketAddress, exception);
} catch (Exception e) {
//
}
} else if (eventHandler instanceof SyslogServerSessionlessEventHandlerIF) {
try {
((SyslogServerSessionlessEventHandlerIF) eventHandler).exception(syslogServer, socketAddress, exception);
} catch (Exception e) {
//
}
}
}
}
}

View File

@ -8,99 +8,99 @@ import org.graylog2.syslog4j.server.SyslogServerConfigIF;
import org.graylog2.syslog4j.server.SyslogServerEventHandlerIF;
/**
* AbstractSyslogServerConfig provides a base abstract implementation of the SyslogServerConfigIF
* configuration interface.
*
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: AbstractSyslogServerConfig.java,v 1.9 2011/01/11 05:11:13 cvs Exp $
*/
* AbstractSyslogServerConfig provides a base abstract implementation of the SyslogServerConfigIF
* configuration interface.
* <p/>
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: AbstractSyslogServerConfig.java,v 1.9 2011/01/11 05:11:13 cvs Exp $
*/
public abstract class AbstractSyslogServerConfig implements SyslogServerConfigIF {
private static final long serialVersionUID = 870248648801259856L;
public abstract Class getSyslogServerClass();
protected String charSet = CHAR_SET_DEFAULT;
protected long shutdownWait = SyslogConstants.SERVER_SHUTDOWN_WAIT_DEFAULT;
private static final long serialVersionUID = 870248648801259856L;
protected List eventHandlers = new ArrayList();
public abstract Class getSyslogServerClass();
protected boolean useStructuredData = USE_STRUCTURED_DATA_DEFAULT;
protected Object dateTimeFormatter = null;
protected boolean useDaemonThread = USE_DAEMON_THREAD_DEFAULT;
protected int threadPriority = THREAD_PRIORITY_DEFAULT;
protected String charSet = CHAR_SET_DEFAULT;
public String getCharSet() {
return this.charSet;
}
protected long shutdownWait = SyslogConstants.SERVER_SHUTDOWN_WAIT_DEFAULT;
public void setCharSet(String charSet) {
this.charSet = charSet;
}
protected List eventHandlers = new ArrayList();
public long getShutdownWait() {
return this.shutdownWait;
}
protected boolean useStructuredData = USE_STRUCTURED_DATA_DEFAULT;
public void setShutdownWait(long shutdownWait) {
this.shutdownWait = shutdownWait;
}
protected Object dateTimeFormatter = null;
public List getEventHandlers() {
return this.eventHandlers;
}
public void addEventHandler(SyslogServerEventHandlerIF eventHandler) {
this.eventHandlers.add(eventHandler);
}
protected boolean useDaemonThread = USE_DAEMON_THREAD_DEFAULT;
protected int threadPriority = THREAD_PRIORITY_DEFAULT;
public void insertEventHandler(int pos, SyslogServerEventHandlerIF eventHandler) {
this.eventHandlers.add(pos, eventHandler);
}
public String getCharSet() {
return this.charSet;
}
public void removeEventHandler(SyslogServerEventHandlerIF eventHandler) {
this.eventHandlers.remove(eventHandler);
}
public void setCharSet(String charSet) {
this.charSet = charSet;
}
public void removeAllEventHandlers() {
this.eventHandlers.clear();
}
public boolean isUseStructuredData() {
return useStructuredData;
}
public long getShutdownWait() {
return this.shutdownWait;
}
public void setUseStructuredData(boolean useStructuredData) {
this.useStructuredData = useStructuredData;
}
public void setShutdownWait(long shutdownWait) {
this.shutdownWait = shutdownWait;
}
public boolean isUseDaemonThread() {
return useDaemonThread;
}
public List getEventHandlers() {
return this.eventHandlers;
}
public Object getDateTimeFormatter() {
return dateTimeFormatter;
}
public void addEventHandler(SyslogServerEventHandlerIF eventHandler) {
this.eventHandlers.add(eventHandler);
}
public void setDateTimeFormatter(Object dateTimeFormatter) {
this.dateTimeFormatter = dateTimeFormatter;
}
public void insertEventHandler(int pos, SyslogServerEventHandlerIF eventHandler) {
this.eventHandlers.add(pos, eventHandler);
}
public void setUseDaemonThread(boolean useDaemonThread) {
this.useDaemonThread = useDaemonThread;
}
public void removeEventHandler(SyslogServerEventHandlerIF eventHandler) {
this.eventHandlers.remove(eventHandler);
}
public int getThreadPriority() {
return threadPriority;
}
public void removeAllEventHandlers() {
this.eventHandlers.clear();
}
public void setThreadPriority(int threadPriority) {
this.threadPriority = threadPriority;
}
public boolean isUseStructuredData() {
return useStructuredData;
}
public void setUseStructuredData(boolean useStructuredData) {
this.useStructuredData = useStructuredData;
}
public boolean isUseDaemonThread() {
return useDaemonThread;
}
public Object getDateTimeFormatter() {
return dateTimeFormatter;
}
public void setDateTimeFormatter(Object dateTimeFormatter) {
this.dateTimeFormatter = dateTimeFormatter;
}
public void setUseDaemonThread(boolean useDaemonThread) {
this.useDaemonThread = useDaemonThread;
}
public int getThreadPriority() {
return threadPriority;
}
public void setThreadPriority(int threadPriority) {
this.threadPriority = threadPriority;
}
}

View File

@ -12,202 +12,203 @@ import org.graylog2.syslog4j.server.SyslogServerEventIF;
import org.graylog2.syslog4j.util.SyslogUtility;
/**
* SyslogServerEvent provides an implementation of the SyslogServerEventIF interface.
*
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: SyslogServerEvent.java,v 1.9 2011/01/11 06:21:15 cvs Exp $
*/
* SyslogServerEvent provides an implementation of the SyslogServerEventIF interface.
* <p/>
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: SyslogServerEvent.java,v 1.9 2011/01/11 06:21:15 cvs Exp $
*/
public class SyslogServerEvent implements SyslogServerEventIF {
private static final long serialVersionUID = 6136043067089899962L;
public static final String DATE_FORMAT = "MMM dd HH:mm:ss yyyy";
public static final String DATE_FORMAT_S = "MMM d HH:mm:ss yyyy";
protected String charSet = SyslogConstants.CHAR_SET_DEFAULT;
protected String rawString = null;
protected byte[] rawBytes = null;
protected int rawLength = -1;
protected Date date = null;
protected int level = -1;
protected int facility = -1;
protected String host = null;
protected boolean isHostStrippedFromMessage = false;
protected String message = null;
protected InetAddress inetAddress = null;
protected SyslogServerEvent() { }
public SyslogServerEvent(final String message, InetAddress inetAddress) {
initialize(message,inetAddress);
parse();
}
public SyslogServerEvent(final byte[] message, int length, InetAddress inetAddress) {
initialize(message,length,inetAddress);
parse();
}
protected void initialize(final String message, InetAddress inetAddress) {
this.rawString = message;
this.rawLength = message.length();
this.inetAddress = inetAddress;
this.message = message;
}
private static final long serialVersionUID = 6136043067089899962L;
protected void initialize(final byte[] message, int length, InetAddress inetAddress) {
this.rawBytes = message;
this.rawLength = length;
this.inetAddress = inetAddress;
}
public static final String DATE_FORMAT = "MMM dd HH:mm:ss yyyy";
public static final String DATE_FORMAT_S = "MMM d HH:mm:ss yyyy";
protected void parseHost() {
int i = this.message.indexOf(' ');
if (i > -1) {
this.host = this.message.substring(0,i).trim();
}
}
protected String charSet = SyslogConstants.CHAR_SET_DEFAULT;
protected String rawString = null;
protected byte[] rawBytes = null;
protected int rawLength = -1;
protected Date date = null;
protected int level = -1;
protected int facility = -1;
protected String host = null;
protected boolean isHostStrippedFromMessage = false;
protected String message = null;
protected InetAddress inetAddress = null;
protected void parseDate() {
int datelength = 16;
String dateFormatS = DATE_FORMAT;
if (this.message.length() > datelength) {
// http://jira.graylog2.org/browse/SERVER-287
if (this.message.charAt(5) == ' ') {
datelength = 15;
dateFormatS = DATE_FORMAT_S;
}
protected SyslogServerEvent() {
}
String year = Integer.toString(Calendar.getInstance().get(Calendar.YEAR));
public SyslogServerEvent(final String message, InetAddress inetAddress) {
initialize(message, inetAddress);
String originalDate = this.message.substring(0,datelength-1) + " " + year;
DateFormat dateFormat = new SimpleDateFormat(dateFormatS);
try {
this.date = dateFormat.parse(originalDate);
parse();
}
this.message = this.message.substring(datelength);
public SyslogServerEvent(final byte[] message, int length, InetAddress inetAddress) {
initialize(message, length, inetAddress);
} catch (ParseException pe) {
this.date = new Date();
}
parse();
}
protected void initialize(final String message, InetAddress inetAddress) {
this.rawString = message;
this.rawLength = message.length();
this.inetAddress = inetAddress;
this.message = message;
}
protected void initialize(final byte[] message, int length, InetAddress inetAddress) {
this.rawBytes = message;
this.rawLength = length;
this.inetAddress = inetAddress;
}
protected void parseHost() {
int i = this.message.indexOf(' ');
if (i > -1) {
this.host = this.message.substring(0, i).trim();
}
}
protected void parseDate() {
int datelength = 16;
String dateFormatS = DATE_FORMAT;
if (this.message.length() > datelength) {
// http://jira.graylog2.org/browse/SERVER-287
if (this.message.charAt(5) == ' ') {
datelength = 15;
dateFormatS = DATE_FORMAT_S;
}
String year = Integer.toString(Calendar.getInstance().get(Calendar.YEAR));
String originalDate = this.message.substring(0, datelength - 1) + " " + year;
DateFormat dateFormat = new SimpleDateFormat(dateFormatS);
try {
this.date = dateFormat.parse(originalDate);
this.message = this.message.substring(datelength);
} catch (ParseException pe) {
this.date = new Date();
}
}
parseHost();
}
protected void parsePriority() {
if (this.message.charAt(0) == '<') {
int i = this.message.indexOf(">");
if (i <= 4 && i > -1) {
String priorityStr = this.message.substring(1, i);
int priority = 0;
try {
priority = Integer.parseInt(priorityStr);
this.facility = priority >> 3;
this.level = priority - (this.facility << 3);
this.message = this.message.substring(i + 1);
parseDate();
} catch (NumberFormatException nfe) {
//
}
parseHost();
}
protected void parsePriority() {
if (this.message.charAt(0) == '<') {
int i = this.message.indexOf(">");
if (i <= 4 && i > -1) {
String priorityStr = this.message.substring(1,i);
int priority = 0;
try {
priority = Integer.parseInt(priorityStr);
this.facility = priority >> 3;
this.level = priority - (this.facility << 3);
this.message = this.message.substring(i+1);
parseDate();
} catch (NumberFormatException nfe) {
//
}
parseHost();
}
}
}
protected void parse() {
if (this.message == null) {
this.message = SyslogUtility.newString(this,this.rawBytes,this.rawLength);
}
parsePriority();
}
public int getFacility() {
return this.facility;
}
public void setFacility(int facility) {
this.facility = facility;
}
parseHost();
}
}
}
public byte[] getRaw() {
if (this.rawString != null) {
byte[] rawStringBytes = SyslogUtility.getBytes(this,this.rawString);
return rawStringBytes;
} else if (this.rawBytes.length == this.rawLength) {
return this.rawBytes;
} else {
byte[] newRawBytes = new byte[this.rawLength];
System.arraycopy(this.rawBytes,0,newRawBytes,0,this.rawLength);
return newRawBytes;
}
}
public int getRawLength() {
return this.rawLength;
}
public Date getDate() {
return this.date;
}
protected void parse() {
if (this.message == null) {
this.message = SyslogUtility.newString(this, this.rawBytes, this.rawLength);
}
public void setDate(Date date) {
this.date = date;
}
public int getLevel() {
return this.level;
}
public void setLevel(int level) {
this.level = level;
}
public String getHost() {
return this.host;
}
public void setHost(String host) {
this.host = host;
}
public boolean isHostStrippedFromMessage() {
return isHostStrippedFromMessage;
}
parsePriority();
}
public String getMessage() {
return this.message;
}
public void setMessage(String message) {
this.message = message;
}
public int getFacility() {
return this.facility;
}
public String getCharSet() {
return this.charSet;
}
public void setFacility(int facility) {
this.facility = facility;
}
public void setCharSet(String charSet) {
this.charSet = charSet;
}
public byte[] getRaw() {
if (this.rawString != null) {
byte[] rawStringBytes = SyslogUtility.getBytes(this, this.rawString);
return rawStringBytes;
} else if (this.rawBytes.length == this.rawLength) {
return this.rawBytes;
} else {
byte[] newRawBytes = new byte[this.rawLength];
System.arraycopy(this.rawBytes, 0, newRawBytes, 0, this.rawLength);
return newRawBytes;
}
}
public int getRawLength() {
return this.rawLength;
}
public Date getDate() {
return this.date;
}
public void setDate(Date date) {
this.date = date;
}
public int getLevel() {
return this.level;
}
public void setLevel(int level) {
this.level = level;
}
public String getHost() {
return this.host;
}
public void setHost(String host) {
this.host = host;
}
public boolean isHostStrippedFromMessage() {
return isHostStrippedFromMessage;
}
public String getMessage() {
return this.message;
}
public void setMessage(String message) {
this.message = message;
}
public String getCharSet() {
return this.charSet;
}
public void setCharSet(String charSet) {
this.charSet = charSet;
}
}

View File

@ -7,23 +7,23 @@ import java.io.OutputStream;
import java.io.PrintStream;
public class FileSyslogServerEventHandler extends PrintStreamSyslogServerEventHandler {
private static final long serialVersionUID = -755824686809731430L;
private static final long serialVersionUID = -755824686809731430L;
protected static PrintStream createPrintStream(String fileName, boolean append) throws IOException {
File file = new File(fileName);
OutputStream os = new FileOutputStream(file,append);
PrintStream printStream = new PrintStream(os);
return printStream;
}
public FileSyslogServerEventHandler(String fileName) throws IOException {
super(createPrintStream(fileName,true));
}
public FileSyslogServerEventHandler(String fileName, boolean append) throws IOException {
super(createPrintStream(fileName,append));
}
protected static PrintStream createPrintStream(String fileName, boolean append) throws IOException {
File file = new File(fileName);
OutputStream os = new FileOutputStream(file, append);
PrintStream printStream = new PrintStream(os);
return printStream;
}
public FileSyslogServerEventHandler(String fileName) throws IOException {
super(createPrintStream(fileName, true));
}
public FileSyslogServerEventHandler(String fileName, boolean append) throws IOException {
super(createPrintStream(fileName, append));
}
}

View File

@ -10,50 +10,50 @@ import org.graylog2.syslog4j.server.SyslogServerSessionEventHandlerIF;
import org.graylog2.syslog4j.util.SyslogUtility;
/**
* SystemOutSyslogServerEventHandler provides a simple example implementation
* of the SyslogServerEventHandlerIF which writes the events to System.out.
*
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: PrintStreamSyslogServerEventHandler.java,v 1.7 2010/11/28 22:07:57 cvs Exp $
*/
* SystemOutSyslogServerEventHandler provides a simple example implementation
* of the SyslogServerEventHandlerIF which writes the events to System.out.
* <p/>
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: PrintStreamSyslogServerEventHandler.java,v 1.7 2010/11/28 22:07:57 cvs Exp $
*/
public class PrintStreamSyslogServerEventHandler implements SyslogServerSessionEventHandlerIF {
private static final long serialVersionUID = 6036415838696050746L;
protected PrintStream stream = null;
public PrintStreamSyslogServerEventHandler(PrintStream stream) {
this.stream = stream;
}
private static final long serialVersionUID = 6036415838696050746L;
public void initialize(SyslogServerIF syslogServer) {
return;
}
protected PrintStream stream = null;
public Object sessionOpened(SyslogServerIF syslogServer, SocketAddress socketAddress) {
return null;
}
public PrintStreamSyslogServerEventHandler(PrintStream stream) {
this.stream = stream;
}
public void event(Object session, SyslogServerIF syslogServer, SocketAddress socketAddress, SyslogServerEventIF event) {
String date = (event.getDate() == null ? new Date() : event.getDate()).toString();
String facility = SyslogUtility.getFacilityString(event.getFacility());
String level = SyslogUtility.getLevelString(event.getLevel());
this.stream.println("{" + facility + "} " + date + " " + level + " " + event.getMessage());
}
public void initialize(SyslogServerIF syslogServer) {
return;
}
public void exception(Object session, SyslogServerIF syslogServer, SocketAddress socketAddress, Exception exception) {
//
}
public Object sessionOpened(SyslogServerIF syslogServer, SocketAddress socketAddress) {
return null;
}
public void sessionClosed(Object session, SyslogServerIF syslogServer, SocketAddress socketAddress, boolean timeout) {
//
}
public void event(Object session, SyslogServerIF syslogServer, SocketAddress socketAddress, SyslogServerEventIF event) {
String date = (event.getDate() == null ? new Date() : event.getDate()).toString();
String facility = SyslogUtility.getFacilityString(event.getFacility());
String level = SyslogUtility.getLevelString(event.getLevel());
public void destroy(SyslogServerIF syslogServer) {
return;
}
this.stream.println("{" + facility + "} " + date + " " + level + " " + event.getMessage());
}
public void exception(Object session, SyslogServerIF syslogServer, SocketAddress socketAddress, Exception exception) {
//
}
public void sessionClosed(Object session, SyslogServerIF syslogServer, SocketAddress socketAddress, boolean timeout) {
//
}
public void destroy(SyslogServerIF syslogServer) {
return;
}
}

View File

@ -3,13 +3,13 @@ package org.graylog2.syslog4j.server.impl.event.printstream;
import org.graylog2.syslog4j.server.SyslogServerSessionEventHandlerIF;
public class SystemErrSyslogServerEventHandler extends PrintStreamSyslogServerEventHandler {
private static final long serialVersionUID = -3496862887351690575L;
private static final long serialVersionUID = -3496862887351690575L;
public static SyslogServerSessionEventHandlerIF create() {
return new SystemErrSyslogServerEventHandler();
}
public SystemErrSyslogServerEventHandler() {
super(System.err);
}
public static SyslogServerSessionEventHandlerIF create() {
return new SystemErrSyslogServerEventHandler();
}
public SystemErrSyslogServerEventHandler() {
super(System.err);
}
}

View File

@ -3,13 +3,13 @@ package org.graylog2.syslog4j.server.impl.event.printstream;
import org.graylog2.syslog4j.server.SyslogServerSessionEventHandlerIF;
public class SystemOutSyslogServerEventHandler extends PrintStreamSyslogServerEventHandler {
private static final long serialVersionUID = 1690551409588182601L;
private static final long serialVersionUID = 1690551409588182601L;
public static SyslogServerSessionEventHandlerIF create() {
return new SystemOutSyslogServerEventHandler();
}
public SystemOutSyslogServerEventHandler() {
super(System.out);
}
public static SyslogServerSessionEventHandlerIF create() {
return new SystemOutSyslogServerEventHandler();
}
public SystemOutSyslogServerEventHandler() {
super(System.out);
}
}

View File

@ -13,139 +13,139 @@ import org.graylog2.syslog4j.server.impl.event.SyslogServerEvent;
* SyslogServerStructuredEvent provides an implementation of the
* SyslogServerEventIF interface that supports receiving of structured syslog
* messages, as defined in:
*
* <p/>
* <p>
* http://tools.ietf.org/html/draft-ietf-syslog-protocol-23#section-6
* </p>
*
* <p/>
* <p>
* Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy of the
* LGPL license is available in the META-INF folder in all distributions of
* Syslog4j and in the base directory of the "doc" ZIP.
* </p>
*
*
* @author Manish Motwani
* @version $Id: StructuredSyslogServerEvent.java,v 1.6 2011/01/11 05:11:13 cvs Exp $
*/
public class StructuredSyslogServerEvent extends SyslogServerEvent {
private static final long serialVersionUID = 1676499796406044315L;
private static final long serialVersionUID = 1676499796406044315L;
protected String applicationName = SyslogConstants.STRUCTURED_DATA_APP_NAME_DEFAULT_VALUE;
protected String processId = null;
protected DateTime dateTime = null;
protected DateTimeFormatter dateTimeFormatter = null;
public StructuredSyslogServerEvent(final byte[] message, int length, InetAddress inetAddress) {
super();
initialize(message,length,inetAddress);
parse();
}
protected String applicationName = SyslogConstants.STRUCTURED_DATA_APP_NAME_DEFAULT_VALUE;
protected String processId = null;
protected DateTime dateTime = null;
protected DateTimeFormatter dateTimeFormatter = null;
public StructuredSyslogServerEvent(final String message, InetAddress inetAddress) {
super();
initialize(message,inetAddress);
parse();
}
public StructuredSyslogServerEvent(final byte[] message, int length, InetAddress inetAddress) {
super();
public DateTimeFormatter getDateTimeFormatter() {
if (dateTimeFormatter == null) {
this.dateTimeFormatter = ISODateTimeFormat.dateTime();
}
return dateTimeFormatter;
}
initialize(message, length, inetAddress);
parse();
}
public void setDateTimeFormatter(Object dateTimeFormatter) {
this.dateTimeFormatter = (DateTimeFormatter) dateTimeFormatter;
}
public StructuredSyslogServerEvent(final String message, InetAddress inetAddress) {
super();
protected void parseApplicationName() {
int i = this.message.indexOf(' ');
initialize(message, inetAddress);
parse();
}
if (i > -1) {
this.applicationName = this.message.substring(0, i).trim();
this.message = this.message.substring(i + 1);
parseProcessId();
}
public DateTimeFormatter getDateTimeFormatter() {
if (dateTimeFormatter == null) {
this.dateTimeFormatter = ISODateTimeFormat.dateTime();
}
if (SyslogConstants.STRUCTURED_DATA_NILVALUE.equals(this.applicationName)) {
this.applicationName = null;
}
}
return dateTimeFormatter;
}
protected void parseProcessId() {
int i = this.message.indexOf(' ');
public void setDateTimeFormatter(Object dateTimeFormatter) {
this.dateTimeFormatter = (DateTimeFormatter) dateTimeFormatter;
}
if (i > -1) {
this.processId = this.message.substring(0, i).trim();
this.message = this.message.substring(i + 1);
}
protected void parseApplicationName() {
int i = this.message.indexOf(' ');
if (SyslogConstants.STRUCTURED_DATA_NILVALUE.equals(this.processId)) {
this.processId = null;
}
}
if (i > -1) {
this.applicationName = this.message.substring(0, i).trim();
this.message = this.message.substring(i + 1);
parseProcessId();
}
protected void parseDate() {
// skip VERSION field
int i = this.message.indexOf(' ');
this.message = this.message.substring(i + 1);
if (SyslogConstants.STRUCTURED_DATA_NILVALUE.equals(this.applicationName)) {
this.applicationName = null;
}
}
// parse the date
i = this.message.indexOf(' ');
protected void parseProcessId() {
int i = this.message.indexOf(' ');
if (i > -1) {
String dateString = this.message.substring(0, i).trim();
try {
DateTimeFormatter formatter = getDateTimeFormatter();
this.dateTime = formatter.parseDateTime(dateString);
this.date = this.dateTime.toDate();
this.message = this.message.substring(dateString.length() + 1);
} catch (Exception e) {
// Not structured date format, try super one
super.parseDate();
}
}
}
if (i > -1) {
this.processId = this.message.substring(0, i).trim();
this.message = this.message.substring(i + 1);
}
protected void parseHost() {
int i = this.message.indexOf(' ');
if (i > -1) {
this.host = this.message.substring(0,i).trim();
this.message = this.message.substring(i+1);
parseApplicationName();
}
}
if (SyslogConstants.STRUCTURED_DATA_NILVALUE.equals(this.processId)) {
this.processId = null;
}
}
public String getApplicationName() {
return this.applicationName;
}
protected void parseDate() {
// skip VERSION field
int i = this.message.indexOf(' ');
this.message = this.message.substring(i + 1);
public String getProcessId() {
return this.processId;
}
public DateTime getDateTime() {
return this.dateTime;
}
// parse the date
i = this.message.indexOf(' ');
public StructuredSyslogMessage getStructuredMessage() {
try {
return StructuredSyslogMessage.fromString(getMessage());
if (i > -1) {
String dateString = this.message.substring(0, i).trim();
} catch (IllegalArgumentException e) {
// throw new SyslogRuntimeException(
// "Message received is not a valid structured message: "
// + getMessage(), e);
return new StructuredSyslogMessage(null,null,getMessage());
}
}
try {
DateTimeFormatter formatter = getDateTimeFormatter();
this.dateTime = formatter.parseDateTime(dateString);
this.date = this.dateTime.toDate();
this.message = this.message.substring(dateString.length() + 1);
} catch (Exception e) {
// Not structured date format, try super one
super.parseDate();
}
}
}
protected void parseHost() {
int i = this.message.indexOf(' ');
if (i > -1) {
this.host = this.message.substring(0, i).trim();
this.message = this.message.substring(i + 1);
parseApplicationName();
}
}
public String getApplicationName() {
return this.applicationName;
}
public String getProcessId() {
return this.processId;
}
public DateTime getDateTime() {
return this.dateTime;
}
public StructuredSyslogMessage getStructuredMessage() {
try {
return StructuredSyslogMessage.fromString(getMessage());
} catch (IllegalArgumentException e) {
// throw new SyslogRuntimeException(
// "Message received is not a valid structured message: "
// + getMessage(), e);
return new StructuredSyslogMessage(null, null, getMessage());
}
}
}

View File

@ -3,35 +3,35 @@ package org.graylog2.syslog4j.server.impl.net;
import org.graylog2.syslog4j.server.impl.AbstractSyslogServerConfig;
/**
* AbstractNetSyslogServerConfig provides a base abstract implementation of the AbstractSyslogServerConfig
* configuration interface.
*
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: AbstractNetSyslogServerConfig.java,v 1.4 2008/11/07 15:15:41 cvs Exp $
*/
* AbstractNetSyslogServerConfig provides a base abstract implementation of the AbstractSyslogServerConfig
* configuration interface.
* <p/>
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: AbstractNetSyslogServerConfig.java,v 1.4 2008/11/07 15:15:41 cvs Exp $
*/
public abstract class AbstractNetSyslogServerConfig extends AbstractSyslogServerConfig {
private static final long serialVersionUID = -3363374941938350263L;
protected String host = null;
protected int port = SYSLOG_PORT_DEFAULT;
public String getHost() {
return this.host;
}
private static final long serialVersionUID = -3363374941938350263L;
public void setHost(String host) {
this.host = host;
}
protected String host = null;
protected int port = SYSLOG_PORT_DEFAULT;
public int getPort() {
return this.port;
}
public String getHost() {
return this.host;
}
public void setPort(int port) {
this.port = port;
}
public void setHost(String host) {
this.host = host;
}
public int getPort() {
return this.port;
}
public void setPort(int port) {
this.port = port;
}
}

View File

@ -20,233 +20,233 @@ import org.graylog2.syslog4j.server.impl.AbstractSyslogServer;
import org.graylog2.syslog4j.util.SyslogUtility;
/**
* TCPNetSyslogServer provides a simple threaded TCP/IP server implementation.
*
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: TCPNetSyslogServer.java,v 1.23 2010/11/28 22:07:57 cvs Exp $
*/
* TCPNetSyslogServer provides a simple threaded TCP/IP server implementation.
* <p/>
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: TCPNetSyslogServer.java,v 1.23 2010/11/28 22:07:57 cvs Exp $
*/
public class TCPNetSyslogServer extends AbstractSyslogServer {
public static class TCPNetSyslogSocketHandler implements Runnable {
protected SyslogServerIF server = null;
protected Socket socket = null;
protected Sessions sessions = null;
public TCPNetSyslogSocketHandler(Sessions sessions, SyslogServerIF server, Socket socket) {
this.sessions = sessions;
this.server = server;
this.socket = socket;
synchronized(this.sessions) {
this.sessions.addSocket(socket);
}
}
public void run() {
boolean timeout = false;
try {
BufferedReader br = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
public static class TCPNetSyslogSocketHandler implements Runnable {
protected SyslogServerIF server = null;
protected Socket socket = null;
protected Sessions sessions = null;
String line = br.readLine();
if (line != null) {
AbstractSyslogServer.handleSessionOpen(this.sessions,this.server,this.socket);
}
while (line != null && line.length() != 0) {
SyslogServerEventIF event = createEvent(this.server.getConfig(),line,this.socket.getInetAddress());
AbstractSyslogServer.handleEvent(this.sessions,this.server,this.socket,event);
public TCPNetSyslogSocketHandler(Sessions sessions, SyslogServerIF server, Socket socket) {
this.sessions = sessions;
this.server = server;
this.socket = socket;
line = br.readLine();
}
} catch (SocketTimeoutException ste) {
timeout = true;
} catch (SocketException se) {
AbstractSyslogServer.handleException(this.sessions,this.server,this.socket.getRemoteSocketAddress(),se);
if ("Socket closed".equals(se.getMessage())) {
//
} else {
//
}
} catch (IOException ioe) {
AbstractSyslogServer.handleException(this.sessions,this.server,this.socket.getRemoteSocketAddress(),ioe);
}
try {
AbstractSyslogServer.handleSessionClosed(this.sessions,this.server,this.socket,timeout);
this.sessions.removeSocket(this.socket);
this.socket.close();
} catch (IOException ioe) {
AbstractSyslogServer.handleException(this.sessions,this.server,this.socket.getRemoteSocketAddress(),ioe);
}
}
}
synchronized (this.sessions) {
this.sessions.addSocket(socket);
}
}
protected ServerSocket serverSocket = null;
protected final Sessions sessions = new Sessions();
protected TCPNetSyslogServerConfigIF tcpNetSyslogServerConfig = null;
public void initialize() throws SyslogRuntimeException {
this.tcpNetSyslogServerConfig = null;
try {
this.tcpNetSyslogServerConfig = (TCPNetSyslogServerConfigIF) this.syslogServerConfig;
} catch (ClassCastException cce) {
throw new SyslogRuntimeException("config must be of type TCPNetSyslogServerConfig");
}
if (this.syslogServerConfig == null) {
throw new SyslogRuntimeException("config cannot be null");
}
public void run() {
boolean timeout = false;
if (this.tcpNetSyslogServerConfig.getBacklog() < 1) {
this.tcpNetSyslogServerConfig.setBacklog(SyslogConstants.SERVER_SOCKET_BACKLOG_DEFAULT);
}
}
public Sessions getSessions() {
return this.sessions;
}
public synchronized void shutdown() {
super.shutdown();
try {
if (this.serverSocket != null) {
if (this.syslogServerConfig.getShutdownWait() > 0) {
SyslogUtility.sleep(this.syslogServerConfig.getShutdownWait());
}
this.serverSocket.close();
}
synchronized(this.sessions) {
Iterator i = this.sessions.getSockets();
if (i != null) {
while(i.hasNext()) {
Socket s = (Socket) i.next();
s.close();
}
}
}
} catch (IOException ioe) {
//
}
if (this.thread != null) {
this.thread.interrupt();
this.thread = null;
}
}
try {
BufferedReader br = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
protected ServerSocketFactory getServerSocketFactory() throws IOException {
ServerSocketFactory serverSocketFactory = ServerSocketFactory.getDefault();
return serverSocketFactory;
}
protected ServerSocket createServerSocket() throws IOException {
ServerSocket newServerSocket = null;
ServerSocketFactory factory = getServerSocketFactory();
if (this.syslogServerConfig.getHost() != null) {
InetAddress inetAddress = InetAddress.getByName(this.syslogServerConfig.getHost());
newServerSocket = factory.createServerSocket(this.syslogServerConfig.getPort(),this.tcpNetSyslogServerConfig.getBacklog(),inetAddress);
} else {
if (this.tcpNetSyslogServerConfig.getBacklog() < 1) {
newServerSocket = factory.createServerSocket(this.syslogServerConfig.getPort());
} else {
newServerSocket = factory.createServerSocket(this.syslogServerConfig.getPort(),this.tcpNetSyslogServerConfig.getBacklog());
}
}
return newServerSocket;
}
String line = br.readLine();
public void run() {
try {
this.serverSocket = createServerSocket();
this.shutdown = false;
} catch (SocketException se) {
throw new SyslogRuntimeException(se);
if (line != null) {
AbstractSyslogServer.handleSessionOpen(this.sessions, this.server, this.socket);
}
} catch (IOException ioe) {
throw new SyslogRuntimeException(ioe);
}
while (line != null && line.length() != 0) {
SyslogServerEventIF event = createEvent(this.server.getConfig(), line, this.socket.getInetAddress());
handleInitialize(this);
while(!this.shutdown) {
try {
Socket socket = this.serverSocket.accept();
if (this.tcpNetSyslogServerConfig.getTimeout() > 0) {
socket.setSoTimeout(this.tcpNetSyslogServerConfig.getTimeout());
}
if (this.tcpNetSyslogServerConfig.getMaxActiveSockets() > 0 && this.sessions.size() >= this.tcpNetSyslogServerConfig.getMaxActiveSockets()) {
if (this.tcpNetSyslogServerConfig.getMaxActiveSocketsBehavior() == TCPNetSyslogServerConfigIF.MAX_ACTIVE_SOCKETS_BEHAVIOR_REJECT) {
try {
socket.close();
} catch (Exception e) {
//
}
socket = null;
} else if (this.tcpNetSyslogServerConfig.getMaxActiveSocketsBehavior() == TCPNetSyslogServerConfigIF.MAX_ACTIVE_SOCKETS_BEHAVIOR_BLOCK) {
while (!this.shutdown && this.sessions.size() >= this.tcpNetSyslogServerConfig.getMaxActiveSockets() && socket.isConnected() && !socket.isClosed()) {
SyslogUtility.sleep(SyslogConstants.THREAD_LOOP_INTERVAL_DEFAULT);
}
}
}
AbstractSyslogServer.handleEvent(this.sessions, this.server, this.socket, event);
if (socket != null) {
TCPNetSyslogSocketHandler handler = new TCPNetSyslogSocketHandler(this.sessions,this,socket);
Thread t = new Thread(handler);
t.start();
}
} catch (SocketException se) {
if ("Socket closed".equals(se.getMessage())) {
this.shutdown = true;
} else {
//
}
} catch (IOException ioe) {
//
}
}
handleDestroy(this);
}
line = br.readLine();
}
} catch (SocketTimeoutException ste) {
timeout = true;
} catch (SocketException se) {
AbstractSyslogServer.handleException(this.sessions, this.server, this.socket.getRemoteSocketAddress(), se);
if ("Socket closed".equals(se.getMessage())) {
//
} else {
//
}
} catch (IOException ioe) {
AbstractSyslogServer.handleException(this.sessions, this.server, this.socket.getRemoteSocketAddress(), ioe);
}
try {
AbstractSyslogServer.handleSessionClosed(this.sessions, this.server, this.socket, timeout);
this.sessions.removeSocket(this.socket);
this.socket.close();
} catch (IOException ioe) {
AbstractSyslogServer.handleException(this.sessions, this.server, this.socket.getRemoteSocketAddress(), ioe);
}
}
}
protected ServerSocket serverSocket = null;
protected final Sessions sessions = new Sessions();
protected TCPNetSyslogServerConfigIF tcpNetSyslogServerConfig = null;
public void initialize() throws SyslogRuntimeException {
this.tcpNetSyslogServerConfig = null;
try {
this.tcpNetSyslogServerConfig = (TCPNetSyslogServerConfigIF) this.syslogServerConfig;
} catch (ClassCastException cce) {
throw new SyslogRuntimeException("config must be of type TCPNetSyslogServerConfig");
}
if (this.syslogServerConfig == null) {
throw new SyslogRuntimeException("config cannot be null");
}
if (this.tcpNetSyslogServerConfig.getBacklog() < 1) {
this.tcpNetSyslogServerConfig.setBacklog(SyslogConstants.SERVER_SOCKET_BACKLOG_DEFAULT);
}
}
public Sessions getSessions() {
return this.sessions;
}
public synchronized void shutdown() {
super.shutdown();
try {
if (this.serverSocket != null) {
if (this.syslogServerConfig.getShutdownWait() > 0) {
SyslogUtility.sleep(this.syslogServerConfig.getShutdownWait());
}
this.serverSocket.close();
}
synchronized (this.sessions) {
Iterator i = this.sessions.getSockets();
if (i != null) {
while (i.hasNext()) {
Socket s = (Socket) i.next();
s.close();
}
}
}
} catch (IOException ioe) {
//
}
if (this.thread != null) {
this.thread.interrupt();
this.thread = null;
}
}
protected ServerSocketFactory getServerSocketFactory() throws IOException {
ServerSocketFactory serverSocketFactory = ServerSocketFactory.getDefault();
return serverSocketFactory;
}
protected ServerSocket createServerSocket() throws IOException {
ServerSocket newServerSocket = null;
ServerSocketFactory factory = getServerSocketFactory();
if (this.syslogServerConfig.getHost() != null) {
InetAddress inetAddress = InetAddress.getByName(this.syslogServerConfig.getHost());
newServerSocket = factory.createServerSocket(this.syslogServerConfig.getPort(), this.tcpNetSyslogServerConfig.getBacklog(), inetAddress);
} else {
if (this.tcpNetSyslogServerConfig.getBacklog() < 1) {
newServerSocket = factory.createServerSocket(this.syslogServerConfig.getPort());
} else {
newServerSocket = factory.createServerSocket(this.syslogServerConfig.getPort(), this.tcpNetSyslogServerConfig.getBacklog());
}
}
return newServerSocket;
}
public void run() {
try {
this.serverSocket = createServerSocket();
this.shutdown = false;
} catch (SocketException se) {
throw new SyslogRuntimeException(se);
} catch (IOException ioe) {
throw new SyslogRuntimeException(ioe);
}
handleInitialize(this);
while (!this.shutdown) {
try {
Socket socket = this.serverSocket.accept();
if (this.tcpNetSyslogServerConfig.getTimeout() > 0) {
socket.setSoTimeout(this.tcpNetSyslogServerConfig.getTimeout());
}
if (this.tcpNetSyslogServerConfig.getMaxActiveSockets() > 0 && this.sessions.size() >= this.tcpNetSyslogServerConfig.getMaxActiveSockets()) {
if (this.tcpNetSyslogServerConfig.getMaxActiveSocketsBehavior() == TCPNetSyslogServerConfigIF.MAX_ACTIVE_SOCKETS_BEHAVIOR_REJECT) {
try {
socket.close();
} catch (Exception e) {
//
}
socket = null;
} else if (this.tcpNetSyslogServerConfig.getMaxActiveSocketsBehavior() == TCPNetSyslogServerConfigIF.MAX_ACTIVE_SOCKETS_BEHAVIOR_BLOCK) {
while (!this.shutdown && this.sessions.size() >= this.tcpNetSyslogServerConfig.getMaxActiveSockets() && socket.isConnected() && !socket.isClosed()) {
SyslogUtility.sleep(SyslogConstants.THREAD_LOOP_INTERVAL_DEFAULT);
}
}
}
if (socket != null) {
TCPNetSyslogSocketHandler handler = new TCPNetSyslogSocketHandler(this.sessions, this, socket);
Thread t = new Thread(handler);
t.start();
}
} catch (SocketException se) {
if ("Socket closed".equals(se.getMessage())) {
this.shutdown = true;
} else {
//
}
} catch (IOException ioe) {
//
}
}
handleDestroy(this);
}
}

View File

@ -3,84 +3,84 @@ package org.graylog2.syslog4j.server.impl.net.tcp;
import org.graylog2.syslog4j.server.impl.net.AbstractNetSyslogServerConfig;
/**
* TCPNetSyslogServerConfig provides configuration for TCPNetSyslogServer.
*
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: TCPNetSyslogServerConfig.java,v 1.8 2010/11/28 01:38:08 cvs Exp $
*/
* TCPNetSyslogServerConfig provides configuration for TCPNetSyslogServer.
* <p/>
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: TCPNetSyslogServerConfig.java,v 1.8 2010/11/28 01:38:08 cvs Exp $
*/
public class TCPNetSyslogServerConfig extends AbstractNetSyslogServerConfig implements TCPNetSyslogServerConfigIF {
private static final long serialVersionUID = -1546696301177599370L;
protected int timeout = 0;
protected int backlog = 0;
protected int maxActiveSockets = TCP_MAX_ACTIVE_SOCKETS_DEFAULT;
protected byte maxActiveSocketsBehavior = TCP_MAX_ACTIVE_SOCKETS_BEHAVIOR_DEFAULT;
private static final long serialVersionUID = -1546696301177599370L;
public TCPNetSyslogServerConfig() {
//
}
protected int timeout = 0;
protected int backlog = 0;
protected int maxActiveSockets = TCP_MAX_ACTIVE_SOCKETS_DEFAULT;
protected byte maxActiveSocketsBehavior = TCP_MAX_ACTIVE_SOCKETS_BEHAVIOR_DEFAULT;
public TCPNetSyslogServerConfig(int port) {
this.port = port;
}
public TCPNetSyslogServerConfig() {
//
}
public TCPNetSyslogServerConfig(int port, int backlog) {
this.port = port;
this.backlog = backlog;
}
public TCPNetSyslogServerConfig(int port) {
this.port = port;
}
public TCPNetSyslogServerConfig(String host) {
this.host = host;
}
public TCPNetSyslogServerConfig(int port, int backlog) {
this.port = port;
this.backlog = backlog;
}
public TCPNetSyslogServerConfig(String host, int port) {
this.host = host;
this.port = port;
}
public TCPNetSyslogServerConfig(String host) {
this.host = host;
}
public TCPNetSyslogServerConfig(String host, int port, int backlog) {
this.host = host;
this.port = port;
this.backlog = backlog;
}
public TCPNetSyslogServerConfig(String host, int port) {
this.host = host;
this.port = port;
}
public Class getSyslogServerClass() {
return TCPNetSyslogServer.class;
}
public int getTimeout() {
return timeout;
}
public TCPNetSyslogServerConfig(String host, int port, int backlog) {
this.host = host;
this.port = port;
this.backlog = backlog;
}
public void setTimeout(int timeout) {
this.timeout = timeout;
}
public Class getSyslogServerClass() {
return TCPNetSyslogServer.class;
}
public int getBacklog() {
return this.backlog;
}
public int getTimeout() {
return timeout;
}
public void setBacklog(int backlog) {
this.backlog = backlog;
}
public void setTimeout(int timeout) {
this.timeout = timeout;
}
public int getMaxActiveSockets() {
return maxActiveSockets;
}
public int getBacklog() {
return this.backlog;
}
public void setMaxActiveSockets(int maxActiveSockets) {
this.maxActiveSockets = maxActiveSockets;
}
public void setBacklog(int backlog) {
this.backlog = backlog;
}
public byte getMaxActiveSocketsBehavior() {
return maxActiveSocketsBehavior;
}
public int getMaxActiveSockets() {
return maxActiveSockets;
}
public void setMaxActiveSocketsBehavior(byte maxActiveSocketsBehavior) {
this.maxActiveSocketsBehavior = maxActiveSocketsBehavior;
}
public void setMaxActiveSockets(int maxActiveSockets) {
this.maxActiveSockets = maxActiveSockets;
}
public byte getMaxActiveSocketsBehavior() {
return maxActiveSocketsBehavior;
}
public void setMaxActiveSocketsBehavior(byte maxActiveSocketsBehavior) {
this.maxActiveSocketsBehavior = maxActiveSocketsBehavior;
}
}

View File

@ -3,28 +3,32 @@ package org.graylog2.syslog4j.server.impl.net.tcp;
import org.graylog2.syslog4j.server.SyslogServerConfigIF;
/**
* TCPNetSyslogServerConfigIF provides configuration for TCPNetSyslogServer.
*
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: TCPNetSyslogServerConfigIF.java,v 1.3 2010/11/28 01:38:08 cvs Exp $
*/
* TCPNetSyslogServerConfigIF provides configuration for TCPNetSyslogServer.
* <p/>
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: TCPNetSyslogServerConfigIF.java,v 1.3 2010/11/28 01:38:08 cvs Exp $
*/
public interface TCPNetSyslogServerConfigIF extends SyslogServerConfigIF {
public final static byte MAX_ACTIVE_SOCKETS_BEHAVIOR_BLOCK = 0;
public final static byte MAX_ACTIVE_SOCKETS_BEHAVIOR_REJECT = 1;
public int getTimeout();
public void setTimeout(int timeout);
public int getBacklog();
public void setBacklog(int backlog);
public int getMaxActiveSockets();
public void setMaxActiveSockets(int maxActiveSockets);
public byte getMaxActiveSocketsBehavior();
public void setMaxActiveSocketsBehavior(byte maxActiveSocketsBehavior);
public final static byte MAX_ACTIVE_SOCKETS_BEHAVIOR_BLOCK = 0;
public final static byte MAX_ACTIVE_SOCKETS_BEHAVIOR_REJECT = 1;
public int getTimeout();
public void setTimeout(int timeout);
public int getBacklog();
public void setBacklog(int backlog);
public int getMaxActiveSockets();
public void setMaxActiveSockets(int maxActiveSockets);
public byte getMaxActiveSocketsBehavior();
public void setMaxActiveSocketsBehavior(byte maxActiveSocketsBehavior);
}

View File

@ -9,50 +9,50 @@ import org.graylog2.syslog4j.SyslogRuntimeException;
import org.graylog2.syslog4j.server.impl.net.tcp.TCPNetSyslogServer;
/**
* SSLTCPNetSyslogServer provides a simple threaded TCP/IP server implementation
* which uses SSL/TLS.
*
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: SSLTCPNetSyslogServer.java,v 1.1 2009/03/29 17:38:58 cvs Exp $
*/
* SSLTCPNetSyslogServer provides a simple threaded TCP/IP server implementation
* which uses SSL/TLS.
* <p/>
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: SSLTCPNetSyslogServer.java,v 1.1 2009/03/29 17:38:58 cvs Exp $
*/
public class SSLTCPNetSyslogServer extends TCPNetSyslogServer {
public void initialize() throws SyslogRuntimeException {
super.initialize();
SSLTCPNetSyslogServerConfigIF sslTcpNetSyslogServerConfig = (SSLTCPNetSyslogServerConfigIF) this.tcpNetSyslogServerConfig;
String keyStore = sslTcpNetSyslogServerConfig.getKeyStore();
if (keyStore != null && !"".equals(keyStore.trim())) {
System.setProperty("javax.net.ssl.keyStore",keyStore);
}
public void initialize() throws SyslogRuntimeException {
super.initialize();
String keyStorePassword = sslTcpNetSyslogServerConfig.getKeyStorePassword();
if (keyStorePassword != null && !"".equals(keyStorePassword.trim())) {
System.setProperty("javax.net.ssl.keyStorePassword",keyStorePassword);
}
SSLTCPNetSyslogServerConfigIF sslTcpNetSyslogServerConfig = (SSLTCPNetSyslogServerConfigIF) this.tcpNetSyslogServerConfig;
String trustStore = sslTcpNetSyslogServerConfig.getTrustStore();
if (trustStore != null && !"".equals(trustStore.trim())) {
System.setProperty("javax.net.ssl.trustStore",trustStore);
}
String keyStore = sslTcpNetSyslogServerConfig.getKeyStore();
String trustStorePassword = sslTcpNetSyslogServerConfig.getTrustStorePassword();
if (trustStorePassword != null && !"".equals(trustStorePassword.trim())) {
System.setProperty("javax.net.ssl.trustStorePassword",trustStorePassword);
}
}
if (keyStore != null && !"".equals(keyStore.trim())) {
System.setProperty("javax.net.ssl.keyStore", keyStore);
}
protected ServerSocketFactory getServerSocketFactory() throws IOException {
ServerSocketFactory serverSocketFactory = SSLServerSocketFactory.getDefault();
return serverSocketFactory;
}
String keyStorePassword = sslTcpNetSyslogServerConfig.getKeyStorePassword();
if (keyStorePassword != null && !"".equals(keyStorePassword.trim())) {
System.setProperty("javax.net.ssl.keyStorePassword", keyStorePassword);
}
String trustStore = sslTcpNetSyslogServerConfig.getTrustStore();
if (trustStore != null && !"".equals(trustStore.trim())) {
System.setProperty("javax.net.ssl.trustStore", trustStore);
}
String trustStorePassword = sslTcpNetSyslogServerConfig.getTrustStorePassword();
if (trustStorePassword != null && !"".equals(trustStorePassword.trim())) {
System.setProperty("javax.net.ssl.trustStorePassword", trustStorePassword);
}
}
protected ServerSocketFactory getServerSocketFactory() throws IOException {
ServerSocketFactory serverSocketFactory = SSLServerSocketFactory.getDefault();
return serverSocketFactory;
}
}

View File

@ -3,57 +3,57 @@ package org.graylog2.syslog4j.server.impl.net.tcp.ssl;
import org.graylog2.syslog4j.server.impl.net.tcp.TCPNetSyslogServerConfig;
/**
* SSLTCPNetSyslogServerConfig provides configuration for SSLTCPNetSyslogServer.
*
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: SSLTCPNetSyslogServerConfig.java,v 1.1 2009/03/29 17:38:58 cvs Exp $
*/
* SSLTCPNetSyslogServerConfig provides configuration for SSLTCPNetSyslogServer.
* <p/>
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: SSLTCPNetSyslogServerConfig.java,v 1.1 2009/03/29 17:38:58 cvs Exp $
*/
public class SSLTCPNetSyslogServerConfig extends TCPNetSyslogServerConfig implements SSLTCPNetSyslogServerConfigIF {
private static final long serialVersionUID = -840102682868286462L;
private static final long serialVersionUID = -840102682868286462L;
protected String keyStore = null;
protected String keyStorePassword = null;
protected String keyStore = null;
protected String keyStorePassword = null;
protected String trustStore = null;
protected String trustStorePassword = null;
protected String trustStore = null;
protected String trustStorePassword = null;
public String getKeyStore() {
return this.keyStore;
}
public void setKeyStore(String keyStore) {
this.keyStore = keyStore;
}
public String getKeyStorePassword() {
return this.keyStorePassword;
}
public void setKeyStorePassword(String keyStorePassword) {
this.keyStorePassword = keyStorePassword;
}
public String getKeyStore() {
return this.keyStore;
}
public String getTrustStore() {
return this.trustStore;
}
public void setKeyStore(String keyStore) {
this.keyStore = keyStore;
}
public void setTrustStore(String trustStore) {
this.trustStore = trustStore;
}
public String getKeyStorePassword() {
return this.keyStorePassword;
}
public String getTrustStorePassword() {
return this.trustStorePassword;
}
public void setKeyStorePassword(String keyStorePassword) {
this.keyStorePassword = keyStorePassword;
}
public void setTrustStorePassword(String trustStorePassword) {
this.trustStorePassword = trustStorePassword;
}
public String getTrustStore() {
return this.trustStore;
}
public Class getSyslogServerClass() {
return SSLTCPNetSyslogServer.class;
}
public void setTrustStore(String trustStore) {
this.trustStore = trustStore;
}
public String getTrustStorePassword() {
return this.trustStorePassword;
}
public void setTrustStorePassword(String trustStorePassword) {
this.trustStorePassword = trustStorePassword;
}
public Class getSyslogServerClass() {
return SSLTCPNetSyslogServer.class;
}
}

View File

@ -3,25 +3,29 @@ package org.graylog2.syslog4j.server.impl.net.tcp.ssl;
import org.graylog2.syslog4j.server.impl.net.tcp.TCPNetSyslogServerConfigIF;
/**
* SSLTCPNetSyslogServerConfigIF provides configuration for SSLTCPNetSyslogServer.
*
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: SSLTCPNetSyslogServerConfigIF.java,v 1.1 2009/03/29 17:38:58 cvs Exp $
*/
* SSLTCPNetSyslogServerConfigIF provides configuration for SSLTCPNetSyslogServer.
* <p/>
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: SSLTCPNetSyslogServerConfigIF.java,v 1.1 2009/03/29 17:38:58 cvs Exp $
*/
public interface SSLTCPNetSyslogServerConfigIF extends TCPNetSyslogServerConfigIF {
public String getKeyStore();
public void setKeyStore(String keyStore);
public String getKeyStorePassword();
public void setKeyStorePassword(String keyStorePassword);
public String getKeyStore();
public String getTrustStore();
public void setTrustStore(String trustStore);
public String getTrustStorePassword();
public void setTrustStorePassword(String trustStorePassword);
public void setKeyStore(String keyStore);
public String getKeyStorePassword();
public void setKeyStorePassword(String keyStorePassword);
public String getTrustStore();
public void setTrustStore(String trustStore);
public String getTrustStorePassword();
public void setTrustStorePassword(String trustStorePassword);
}

View File

@ -14,89 +14,89 @@ import org.graylog2.syslog4j.server.impl.AbstractSyslogServer;
import org.graylog2.syslog4j.util.SyslogUtility;
/**
* UDPNetSyslogServer provides a simple non-threaded UDP/IP server implementation.
*
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: UDPNetSyslogServer.java,v 1.16 2010/11/12 03:43:15 cvs Exp $
*/
* UDPNetSyslogServer provides a simple non-threaded UDP/IP server implementation.
* <p/>
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: UDPNetSyslogServer.java,v 1.16 2010/11/12 03:43:15 cvs Exp $
*/
public class UDPNetSyslogServer extends AbstractSyslogServer {
protected DatagramSocket ds = null;
protected DatagramSocket ds = null;
public void initialize() throws SyslogRuntimeException {
//
}
public void shutdown() {
super.shutdown();
if (this.syslogServerConfig.getShutdownWait() > 0) {
SyslogUtility.sleep(this.syslogServerConfig.getShutdownWait());
}
if (this.ds != null && !this.ds.isClosed()) {
this.ds.close();
}
}
protected DatagramSocket createDatagramSocket() throws SocketException, UnknownHostException {
DatagramSocket datagramSocket = null;
if (this.syslogServerConfig.getHost() != null) {
InetAddress inetAddress = InetAddress.getByName(this.syslogServerConfig.getHost());
datagramSocket = new DatagramSocket(this.syslogServerConfig.getPort(),inetAddress);
} else {
datagramSocket = new DatagramSocket(this.syslogServerConfig.getPort());
}
return datagramSocket;
}
public void initialize() throws SyslogRuntimeException {
//
}
public void run() {
try {
this.ds = createDatagramSocket();
this.shutdown = false;
} catch (SocketException se) {
return;
} catch (UnknownHostException uhe) {
return;
}
byte[] receiveData = new byte[SyslogConstants.SYSLOG_BUFFER_SIZE];
handleInitialize(this);
while(!this.shutdown) {
DatagramPacket dp = null;
try {
dp = new DatagramPacket(receiveData,receiveData.length);
this.ds.receive(dp);
SyslogServerEventIF event = createEvent(this.getConfig(),receiveData,dp.getLength(),dp.getAddress());
handleEvent(null,this,dp,event);
} catch (SocketException se) {
int i = se.getMessage() == null ? -1 : se.getMessage().toLowerCase().indexOf("socket closed");
if (i == -1) {
handleException(null,this,dp.getSocketAddress(),se);
}
} catch (IOException ioe) {
handleException(null,this,dp.getSocketAddress(),ioe);
}
}
handleDestroy(this);
}
public void shutdown() {
super.shutdown();
if (this.syslogServerConfig.getShutdownWait() > 0) {
SyslogUtility.sleep(this.syslogServerConfig.getShutdownWait());
}
if (this.ds != null && !this.ds.isClosed()) {
this.ds.close();
}
}
protected DatagramSocket createDatagramSocket() throws SocketException, UnknownHostException {
DatagramSocket datagramSocket = null;
if (this.syslogServerConfig.getHost() != null) {
InetAddress inetAddress = InetAddress.getByName(this.syslogServerConfig.getHost());
datagramSocket = new DatagramSocket(this.syslogServerConfig.getPort(), inetAddress);
} else {
datagramSocket = new DatagramSocket(this.syslogServerConfig.getPort());
}
return datagramSocket;
}
public void run() {
try {
this.ds = createDatagramSocket();
this.shutdown = false;
} catch (SocketException se) {
return;
} catch (UnknownHostException uhe) {
return;
}
byte[] receiveData = new byte[SyslogConstants.SYSLOG_BUFFER_SIZE];
handleInitialize(this);
while (!this.shutdown) {
DatagramPacket dp = null;
try {
dp = new DatagramPacket(receiveData, receiveData.length);
this.ds.receive(dp);
SyslogServerEventIF event = createEvent(this.getConfig(), receiveData, dp.getLength(), dp.getAddress());
handleEvent(null, this, dp, event);
} catch (SocketException se) {
int i = se.getMessage() == null ? -1 : se.getMessage().toLowerCase().indexOf("socket closed");
if (i == -1) {
handleException(null, this, dp.getSocketAddress(), se);
}
} catch (IOException ioe) {
handleException(null, this, dp.getSocketAddress(), ioe);
}
}
handleDestroy(this);
}
}

View File

@ -3,36 +3,36 @@ package org.graylog2.syslog4j.server.impl.net.udp;
import org.graylog2.syslog4j.server.impl.net.AbstractNetSyslogServerConfig;
/**
* UDPNetSyslogServerConfig provides configuration for UDPNetSyslogServer.
*
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: UDPNetSyslogServerConfig.java,v 1.6 2010/10/28 05:10:57 cvs Exp $
*/
* UDPNetSyslogServerConfig provides configuration for UDPNetSyslogServer.
* <p/>
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: UDPNetSyslogServerConfig.java,v 1.6 2010/10/28 05:10:57 cvs Exp $
*/
public class UDPNetSyslogServerConfig extends AbstractNetSyslogServerConfig {
private static final long serialVersionUID = -2005919161187055486L;
private static final long serialVersionUID = -2005919161187055486L;
public UDPNetSyslogServerConfig() {
//
}
public UDPNetSyslogServerConfig() {
//
}
public UDPNetSyslogServerConfig(int port) {
this.port = port;
}
public UDPNetSyslogServerConfig(int port) {
this.port = port;
}
public UDPNetSyslogServerConfig(String host) {
this.host = host;
}
public UDPNetSyslogServerConfig(String host) {
this.host = host;
}
public UDPNetSyslogServerConfig(String host, int port) {
this.host = host;
this.port = port;
}
public UDPNetSyslogServerConfig(String host, int port) {
this.host = host;
this.port = port;
}
public Class getSyslogServerClass() {
return UDPNetSyslogServer.class;
}
public Class getSyslogServerClass() {
return UDPNetSyslogServer.class;
}
}

File diff suppressed because it is too large Load Diff

View File

@ -1,77 +1,77 @@
package org.graylog2.syslog4j.util;
/**
* OSDetectUtility provides operating system detection used to determine
* whether Syslog4j is running on a Unix platform.
*
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: OSDetectUtility.java,v 1.4 2008/11/14 04:31:59 cvs Exp $
*/
* OSDetectUtility provides operating system detection used to determine
* whether Syslog4j is running on a Unix platform.
* <p/>
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author &lt;syslog4j@productivity.org&gt;
* @version $Id: OSDetectUtility.java,v 1.4 2008/11/14 04:31:59 cvs Exp $
*/
public final class OSDetectUtility {
private final static String[] UNIX_PLATFORMS = {
"Linux",
"Mac OS",
"Solaris",
"SunOS",
"MPE/iX",
"HP-UX",
"AIX",
"OS/390",
"FreeBSD",
"Irix",
"Digital Unix",
"FreeBSD",
"OSF1",
"OpenVMS"
};
private final static String[] UNIX_PLATFORMS = {
"Linux",
"Mac OS",
"Solaris",
"SunOS",
"MPE/iX",
"HP-UX",
"AIX",
"OS/390",
"FreeBSD",
"Irix",
"Digital Unix",
"FreeBSD",
"OSF1",
"OpenVMS"
};
private final static String[] WINDOWS_PLATFORMS = {
"Windows",
"OS/2"
};
private static boolean UNIX = false;
private static boolean WINDOWS = false;
private OSDetectUtility() {
//
}
private static boolean isMatch(String[] platforms) {
boolean match = false;
String osName = System.getProperty("os.name");
if (osName != null && !"".equals(osName.trim())) {
osName = osName.toLowerCase();
for(int i=0; i<platforms.length; i++) {
String platform = platforms[i].toLowerCase();
if (osName.indexOf(platform) > -1) {
match = true;
break;
}
}
}
return match;
}
private final static String[] WINDOWS_PLATFORMS = {
"Windows",
"OS/2"
};
static {
UNIX = isMatch(UNIX_PLATFORMS);
WINDOWS = isMatch(WINDOWS_PLATFORMS);
}
public static boolean isUnix() {
return UNIX;
}
private static boolean UNIX = false;
private static boolean WINDOWS = false;
public static boolean isWindows() {
return WINDOWS;
}
private OSDetectUtility() {
//
}
private static boolean isMatch(String[] platforms) {
boolean match = false;
String osName = System.getProperty("os.name");
if (osName != null && !"".equals(osName.trim())) {
osName = osName.toLowerCase();
for (int i = 0; i < platforms.length; i++) {
String platform = platforms[i].toLowerCase();
if (osName.indexOf(platform) > -1) {
match = true;
break;
}
}
}
return match;
}
static {
UNIX = isMatch(UNIX_PLATFORMS);
WINDOWS = isMatch(WINDOWS_PLATFORMS);
}
public static boolean isUnix() {
return UNIX;
}
public static boolean isWindows() {
return WINDOWS;
}
}

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