http://git-wip-us.apache.org/repos/asf/logging-chainsaw/blob/96ebd9ad/src/main/java/org/apache/log4j/helpers/MessageFormatter.java ---------------------------------------------------------------------- diff --git a/src/main/java/org/apache/log4j/helpers/MessageFormatter.java b/src/main/java/org/apache/log4j/helpers/MessageFormatter.java index 5f82d73..05a753d 100644 --- a/src/main/java/org/apache/log4j/helpers/MessageFormatter.java +++ b/src/main/java/org/apache/log4j/helpers/MessageFormatter.java @@ -5,9 +5,9 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,8 +20,8 @@ package org.apache.log4j.helpers; /** * Formats messages according to very simple rules. - * See {@link #format(String,Object)} and - * {@link #format(String,Object,Object)} for more details. + * See {@link #format(String, Object)} and + * {@link #format(String, Object, Object)} for more details. * * @author Ceki Gülcü */ @@ -45,17 +45,15 @@ public final class MessageFormatter { /** * Performs single argument substitution for the 'messagePattern' passed as * parameter. - * + * <p> * <p>For example, <code>MessageFormatter.format("Hi {}.", "there");</code> * will return the string "Hi there.". * </p> * The {} pair is called the formatting element. It serves to designate the * location where the argument needs to be inserted within the pattern. * - * @param messagePattern - * The message pattern which will be parsed and formatted - * @param argument - * The argument to be inserted instead of the formatting element + * @param messagePattern The message pattern which will be parsed and formatted + * @param argument The argument to be inserted instead of the formatting element * @return The formatted message */ public static String format(final String messagePattern, @@ -79,8 +77,8 @@ public final class MessageFormatter { return messagePattern; } else { String sbuf = messagePattern.substring(0, j) + - argument + - messagePattern.substring(j + 2); + argument + + messagePattern.substring(j + 2); return sbuf; } } @@ -90,7 +88,7 @@ public final class MessageFormatter { * /** * Performs a two argument substitution for the 'messagePattern' passed as * parameter. - * + * <p> * <p>For example, <code>MessageFormatter.format("Hi {}. My name is {}.", * "there", "David");</code> will return the string * "Hi there. My name is David.". @@ -99,12 +97,9 @@ public final class MessageFormatter { * location where the arguments need to be inserted within * the message pattern. * - * @param messagePattern - * The message pattern which will be parsed and formatted - * @param arg1 - * The first argument to replace the first formatting element - * @param arg2 - * The second argument to replace the second formatting element + * @param messagePattern The message pattern which will be parsed and formatted + * @param arg1 The first argument to replace the first formatting element + * @param arg2 The second argument to replace the second formatting element * @return The formatted message */ public static String format(final String messagePattern, @@ -126,7 +121,7 @@ public final class MessageFormatter { // add the tail string which contains no variables // and return the result. sbuf.append(messagePattern.substring(i, - messagePattern.length())); + messagePattern.length())); return sbuf.toString(); } } else { @@ -134,7 +129,7 @@ public final class MessageFormatter { if ((delimStop != DELIM_STOP)) { // invalid DELIM_START/DELIM_STOP pair sbuf.append(messagePattern.substring(i, - messagePattern.length())); + messagePattern.length())); return sbuf.toString(); } sbuf.append(messagePattern.substring(i, j));
http://git-wip-us.apache.org/repos/asf/logging-chainsaw/blob/96ebd9ad/src/main/java/org/apache/log4j/helpers/UtilLoggingLevel.java ---------------------------------------------------------------------- diff --git a/src/main/java/org/apache/log4j/helpers/UtilLoggingLevel.java b/src/main/java/org/apache/log4j/helpers/UtilLoggingLevel.java index 4fec74d..facba82 100644 --- a/src/main/java/org/apache/log4j/helpers/UtilLoggingLevel.java +++ b/src/main/java/org/apache/log4j/helpers/UtilLoggingLevel.java @@ -17,16 +17,15 @@ package org.apache.log4j.helpers; +import org.apache.log4j.Level; + import java.util.ArrayList; import java.util.List; -import org.apache.log4j.Level; - /** * An extension of the Level class that provides support for java.util.logging * Levels. * - * * @author Scott Deboy (sde...@apache.org) */ @@ -47,7 +46,7 @@ public class UtilLoggingLevel extends Level { public static final int WARNING_INT = 21000; //INFO level defined in parent as 20000..no need to redefine here - + /** * Numerical value for CONFIG. */ @@ -73,43 +72,44 @@ public class UtilLoggingLevel extends Level { * SEVERE. */ public static final UtilLoggingLevel SEVERE = - new UtilLoggingLevel(SEVERE_INT, "SEVERE", 0); + new UtilLoggingLevel(SEVERE_INT, "SEVERE", 0); /** * WARNING. */ public static final UtilLoggingLevel WARNING = - new UtilLoggingLevel(WARNING_INT, "WARNING", 4); + new UtilLoggingLevel(WARNING_INT, "WARNING", 4); /** * INFO. */ //note: we've aligned the int values of the java.util.logging INFO level with log4j's level public static final UtilLoggingLevel INFO = - new UtilLoggingLevel(INFO_INT, "INFO", 5); + new UtilLoggingLevel(INFO_INT, "INFO", 5); /** * CONFIG. */ public static final UtilLoggingLevel CONFIG = - new UtilLoggingLevel(CONFIG_INT, "CONFIG", 6); + new UtilLoggingLevel(CONFIG_INT, "CONFIG", 6); /** * FINE. */ public static final UtilLoggingLevel FINE = - new UtilLoggingLevel(FINE_INT, "FINE", 7); + new UtilLoggingLevel(FINE_INT, "FINE", 7); /** * FINER. */ public static final UtilLoggingLevel FINER = - new UtilLoggingLevel(FINER_INT, "FINER", 8); + new UtilLoggingLevel(FINER_INT, "FINER", 8); /** * FINEST. */ public static final UtilLoggingLevel FINEST = - new UtilLoggingLevel(FINEST_INT, "FINEST", 9); + new UtilLoggingLevel(FINEST_INT, "FINEST", 9); /** * Create new instance. - * @param level numeric value for level. - * @param levelStr symbolic name for level. + * + * @param level numeric value for level. + * @param levelStr symbolic name for level. * @param syslogEquivalent Equivalent syslog severity. */ protected UtilLoggingLevel(final int level, @@ -121,13 +121,14 @@ public class UtilLoggingLevel extends Level { /** * Convert an integer passed as argument to a level. If the * conversion fails, then this method returns the specified default. - * @param val numeric value. + * + * @param val numeric value. * @param defaultLevel level to be returned if no level matches - * numeric value. + * numeric value. * @return matching level or default level. */ public static UtilLoggingLevel toLevel(final int val, - final UtilLoggingLevel defaultLevel) { + final UtilLoggingLevel defaultLevel) { switch (val) { case SEVERE_INT: return SEVERE; @@ -157,8 +158,9 @@ public class UtilLoggingLevel extends Level { /** * Gets level matching numeric value. + * * @param val numeric value. - * @return matching level or UtilLoggerLevel.FINEST if no match. + * @return matching level or UtilLoggerLevel.FINEST if no match. */ public static Level toLevel(final int val) { return toLevel(val, FINEST); @@ -166,7 +168,8 @@ public class UtilLoggingLevel extends Level { /** * Gets list of supported levels. - * @return list of supported levels. + * + * @return list of supported levels. */ public static List<UtilLoggingLevel> getAllPossibleLevels() { ArrayList<UtilLoggingLevel> list = new ArrayList<>(); @@ -182,6 +185,7 @@ public class UtilLoggingLevel extends Level { /** * Get level with specified symbolic name. + * * @param s symbolic name. * @return matching level or Level.DEBUG if no match. */ @@ -192,7 +196,8 @@ public class UtilLoggingLevel extends Level { /** * Get level with specified symbolic name. - * @param sArg symbolic name. + * + * @param sArg symbolic name. * @param defaultLevel level to return if no match. * @return matching level or defaultLevel if no match. */ http://git-wip-us.apache.org/repos/asf/logging-chainsaw/blob/96ebd9ad/src/main/java/org/apache/log4j/net/AddressBased.java ---------------------------------------------------------------------- diff --git a/src/main/java/org/apache/log4j/net/AddressBased.java b/src/main/java/org/apache/log4j/net/AddressBased.java index ccd2e6a..f1d10c0 100644 --- a/src/main/java/org/apache/log4j/net/AddressBased.java +++ b/src/main/java/org/apache/log4j/net/AddressBased.java @@ -24,13 +24,13 @@ package org.apache.log4j.net; * interface so that they can be treated generically. * * @author Paul Smith (psm...@apache.org) - * */ public interface AddressBased extends NetworkBased { - /** - * Returns a String representation of the Address this instance - * encompasses. - * @return String representation of the Address - */ - String getAddress(); + /** + * Returns a String representation of the Address this instance + * encompasses. + * + * @return String representation of the Address + */ + String getAddress(); } http://git-wip-us.apache.org/repos/asf/logging-chainsaw/blob/96ebd9ad/src/main/java/org/apache/log4j/net/JMSReceiver.java ---------------------------------------------------------------------- diff --git a/src/main/java/org/apache/log4j/net/JMSReceiver.java b/src/main/java/org/apache/log4j/net/JMSReceiver.java index 1c21da9..8c1e7a6 100644 --- a/src/main/java/org/apache/log4j/net/JMSReceiver.java +++ b/src/main/java/org/apache/log4j/net/JMSReceiver.java @@ -5,9 +5,9 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,285 +17,283 @@ package org.apache.log4j.net; -import java.io.FileInputStream; -import java.util.Properties; - -import javax.jms.Message; -import javax.jms.MessageListener; -import javax.jms.TopicConnection; -import javax.jms.Topic; -import javax.jms.TopicConnectionFactory; -import javax.jms.TopicSubscriber; -import javax.jms.Session; -import javax.jms.TopicSession; -import javax.jms.ObjectMessage; +import org.apache.log4j.plugins.Plugin; +import org.apache.log4j.plugins.Receiver; +import org.apache.log4j.spi.LoggingEvent; -import javax.naming.InitialContext; +import javax.jms.*; import javax.naming.Context; +import javax.naming.InitialContext; import javax.naming.NameNotFoundException; import javax.naming.NamingException; - -import org.apache.log4j.spi.LoggingEvent; -import org.apache.log4j.plugins.Plugin; -import org.apache.log4j.plugins.Receiver; +import java.io.FileInputStream; +import java.util.Properties; /** - JMSReceiver receives a remote logging event on a configured - JSM topic and "posts" it to a LoggerRepository as if the event was - generated locally. This class is designed to receive events from - the JMSAppender class (or classes that send compatible events). - - <p>Once the event has been "posted", it will be handled by the - appenders currently configured in the LoggerRespository. - - <p>This implementation borrows heavily from the JMSSink - implementation. - - @author Mark Womack - @author Paul Smith - @author Stephen Pain -*/ + * JMSReceiver receives a remote logging event on a configured + * JSM topic and "posts" it to a LoggerRepository as if the event was + * generated locally. This class is designed to receive events from + * the JMSAppender class (or classes that send compatible events). + * <p> + * <p>Once the event has been "posted", it will be handled by the + * appenders currently configured in the LoggerRespository. + * <p> + * <p>This implementation borrows heavily from the JMSSink + * implementation. + * + * @author Mark Womack + * @author Paul Smith + * @author Stephen Pain + */ public class JMSReceiver extends Receiver implements MessageListener { - private boolean active = false; - - protected String topicFactoryName; - protected String topicName; - protected String userId; - protected String password; - protected TopicConnection topicConnection; - protected String jndiPath; - - private String remoteInfo; - private String providerUrl; - - public JMSReceiver() { } - - public JMSReceiver(String _topicFactoryName, String _topicName, - String _userId, String _password, String _jndiPath) { - topicFactoryName = _topicFactoryName; - topicName = _topicName; - userId = _userId; - password = _password; - jndiPath = _jndiPath; - } - - /** - * Sets the path to a properties file containing - * the initial context and jndi provider url - */ + private boolean active = false; + + protected String topicFactoryName; + protected String topicName; + protected String userId; + protected String password; + protected TopicConnection topicConnection; + protected String jndiPath; + + private String remoteInfo; + private String providerUrl; + + public JMSReceiver() { + } + + public JMSReceiver(String _topicFactoryName, String _topicName, + String _userId, String _password, String _jndiPath) { + topicFactoryName = _topicFactoryName; + topicName = _topicName; + userId = _userId; + password = _password; + jndiPath = _jndiPath; + } + + /** + * Sets the path to a properties file containing + * the initial context and jndi provider url + */ public void setJndiPath(String _jndiPath) { - jndiPath = _jndiPath; + jndiPath = _jndiPath; } - - /** - * Gets the path to a properties file containing - * the initial context and jndi provider url - */ - public String getJndiPath() { - return jndiPath; - } - - /** - Sets the JMS topic factory name to use when creating the - JMS connection. */ - public void setTopicFactoryName(String _topicFactoryName) { - topicFactoryName = _topicFactoryName; - } - - /** - Gets the curernt JMS topic factory name property. */ - public String getTopicFactoryName() { - return topicFactoryName; - } - - /** - * Sets the JMS topic name to use when creating the - * JMS connection. - */ - public void setTopicName(String _topicName) { - topicName = _topicName; - } - - /** - * Gets the curernt JMS topic name property. - */ - public String getTopicName() { - return topicName; - } - - /** - Sets the user id to use when creating the - JMS connection. */ - public void setUserId(String _userId) { - userId = _userId; - } - - /** - * Gets the current user id property. - */ - public String getUserId() { - return userId; - } - - /** - * Sets the password to use when creating the - * JMS connection. - */ - public void setPassword(String _password) { - password = _password; - } - - /** - * Gets the curernt password property. - */ - public String getPassword() { - return password; - } - - /** - * Returns true if the receiver is the same class and they are - * configured for the same properties, and super class also considers - * them to be equivalent. This is used by PluginRegistry when determining - * if the a similarly configured receiver is being started. - * - * @param testPlugin The plugin to test equivalency against. - * @return boolean True if the testPlugin is equivalent to this plugin. - */ - public boolean isEquivalent(Plugin testPlugin) { - // only do full check if an instance of this class - if (testPlugin instanceof JMSReceiver) { - - JMSReceiver receiver = (JMSReceiver)testPlugin; - - // check for same topic name and super class equivalency - return ( - topicFactoryName.equals(receiver.getTopicFactoryName()) && - (jndiPath == null || jndiPath.equals(receiver.getJndiPath())) && - super.isEquivalent(testPlugin) - ); + + /** + * Gets the path to a properties file containing + * the initial context and jndi provider url + */ + public String getJndiPath() { + return jndiPath; + } + + /** + * Sets the JMS topic factory name to use when creating the + * JMS connection. + */ + public void setTopicFactoryName(String _topicFactoryName) { + topicFactoryName = _topicFactoryName; } - - return false; - } - - /** - Returns true if this receiver is active. */ - public synchronized boolean isActive() { - return active; - } - - /** - Sets the flag to indicate if receiver is active or not. */ - protected synchronized void setActive(boolean _active) { - active = _active; - } - - /** - Starts the JMSReceiver with the current options. */ - public void activateOptions() { - if (!isActive()) { - try { - remoteInfo = topicFactoryName + ":" + topicName; - - Context ctx; - if (jndiPath == null || jndiPath.equals("")) { - ctx = new InitialContext(); - } else { - FileInputStream is = new FileInputStream(jndiPath); - Properties p = new Properties(); - p.load(is); - is.close(); - ctx = new InitialContext(p); + + /** + * Gets the curernt JMS topic factory name property. + */ + public String getTopicFactoryName() { + return topicFactoryName; + } + + /** + * Sets the JMS topic name to use when creating the + * JMS connection. + */ + public void setTopicName(String _topicName) { + topicName = _topicName; + } + + /** + * Gets the curernt JMS topic name property. + */ + public String getTopicName() { + return topicName; + } + + /** + * Sets the user id to use when creating the + * JMS connection. + */ + public void setUserId(String _userId) { + userId = _userId; + } + + /** + * Gets the current user id property. + */ + public String getUserId() { + return userId; + } + + /** + * Sets the password to use when creating the + * JMS connection. + */ + public void setPassword(String _password) { + password = _password; + } + + /** + * Gets the curernt password property. + */ + public String getPassword() { + return password; + } + + /** + * Returns true if the receiver is the same class and they are + * configured for the same properties, and super class also considers + * them to be equivalent. This is used by PluginRegistry when determining + * if the a similarly configured receiver is being started. + * + * @param testPlugin The plugin to test equivalency against. + * @return boolean True if the testPlugin is equivalent to this plugin. + */ + public boolean isEquivalent(Plugin testPlugin) { + // only do full check if an instance of this class + if (testPlugin instanceof JMSReceiver) { + + JMSReceiver receiver = (JMSReceiver) testPlugin; + + // check for same topic name and super class equivalency + return ( + topicFactoryName.equals(receiver.getTopicFactoryName()) && + (jndiPath == null || jndiPath.equals(receiver.getJndiPath())) && + super.isEquivalent(testPlugin) + ); } - // give some more flexibility about the choice of a tab name - providerUrl = (String)ctx.getEnvironment().get(Context.PROVIDER_URL); - TopicConnectionFactory topicConnectionFactory; - topicConnectionFactory = - (TopicConnectionFactory) lookup(ctx, topicFactoryName); - - if (userId != null && password != null) { - topicConnection = - topicConnectionFactory.createTopicConnection(userId, password); - } else { - topicConnection = - topicConnectionFactory.createTopicConnection(); + return false; + } + + /** + * Returns true if this receiver is active. + */ + public synchronized boolean isActive() { + return active; + } + + /** + * Sets the flag to indicate if receiver is active or not. + */ + protected synchronized void setActive(boolean _active) { + active = _active; + } + + /** + * Starts the JMSReceiver with the current options. + */ + public void activateOptions() { + if (!isActive()) { + try { + remoteInfo = topicFactoryName + ":" + topicName; + + Context ctx; + if (jndiPath == null || jndiPath.equals("")) { + ctx = new InitialContext(); + } else { + FileInputStream is = new FileInputStream(jndiPath); + Properties p = new Properties(); + p.load(is); + is.close(); + ctx = new InitialContext(p); + } + + // give some more flexibility about the choice of a tab name + providerUrl = (String) ctx.getEnvironment().get(Context.PROVIDER_URL); + TopicConnectionFactory topicConnectionFactory; + topicConnectionFactory = + (TopicConnectionFactory) lookup(ctx, topicFactoryName); + + if (userId != null && password != null) { + topicConnection = + topicConnectionFactory.createTopicConnection(userId, password); + } else { + topicConnection = + topicConnectionFactory.createTopicConnection(); + } + + TopicSession topicSession = + topicConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE); + + Topic topic = (Topic) ctx.lookup(topicName); + + TopicSubscriber topicSubscriber = topicSession.createSubscriber(topic); + + topicSubscriber.setMessageListener(this); + + topicConnection.start(); + + setActive(true); + } catch (Exception e) { + setActive(false); + if (topicConnection != null) { + try { + topicConnection.close(); + } catch (Exception e2) { + // do nothing + } + topicConnection = null; + } + getLogger().error("Could not start JMSReceiver.", e); + } } - - TopicSession topicSession = - topicConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE); - - Topic topic = (Topic)ctx.lookup(topicName); - - TopicSubscriber topicSubscriber = topicSession.createSubscriber(topic); - - topicSubscriber.setMessageListener(this); - - topicConnection.start(); - - setActive(true); - } catch(Exception e) { - setActive(false); - if (topicConnection != null) { - try { - topicConnection.close(); - } catch (Exception e2) { - // do nothing - } - topicConnection = null; + } + + /** + * Called when the receiver should be stopped. + */ + public synchronized void shutdown() { + if (isActive()) { + // mark this as no longer running + setActive(false); + + if (topicConnection != null) { + try { + topicConnection.close(); + } catch (Exception e) { + // do nothing + } + topicConnection = null; + } } - getLogger().error("Could not start JMSReceiver.", e); - } } - } - - /** - Called when the receiver should be stopped. */ - public synchronized void shutdown() { - if (isActive()) { - // mark this as no longer running - setActive(false); - - if (topicConnection != null) { + + public void onMessage(Message message) { try { - topicConnection.close(); + if (message instanceof ObjectMessage) { + // get the logging event and post it to the repository + ObjectMessage objectMessage = (ObjectMessage) message; + LoggingEvent event = (LoggingEvent) objectMessage.getObject(); + + // store the known remote info in an event property + event.setProperty("log4j.remoteSourceInfo", remoteInfo); + event.setProperty("log4j.jmsProviderUrl", providerUrl); + + doPost(event); + } else { + getLogger().warn("Received message is of type " + message.getJMSType() + + ", was expecting ObjectMessage."); + } } catch (Exception e) { - // do nothing + getLogger().error("Exception thrown while processing incoming message.", e); } - topicConnection = null; - } } - } - - public void onMessage(Message message) { - try { - if(message instanceof ObjectMessage) { - // get the logging event and post it to the repository - ObjectMessage objectMessage = (ObjectMessage) message; - LoggingEvent event = (LoggingEvent) objectMessage.getObject(); - - // store the known remote info in an event property - event.setProperty("log4j.remoteSourceInfo", remoteInfo); - event.setProperty("log4j.jmsProviderUrl", providerUrl); - - doPost(event); - } else { - getLogger().warn("Received message is of type "+message.getJMSType() - +", was expecting ObjectMessage."); - } - } catch(Exception e) { - getLogger().error("Exception thrown while processing incoming message.", e); - } - } - - protected Object lookup(Context ctx, String name) throws NamingException { - try { - return ctx.lookup(name); - } catch(NameNotFoundException e) { - getLogger().error("Could not find name ["+name+"]."); - throw e; + + protected Object lookup(Context ctx, String name) throws NamingException { + try { + return ctx.lookup(name); + } catch (NameNotFoundException e) { + getLogger().error("Could not find name [" + name + "]."); + throw e; + } } - } } http://git-wip-us.apache.org/repos/asf/logging-chainsaw/blob/96ebd9ad/src/main/java/org/apache/log4j/net/JMSReceiverBeanInfo.java ---------------------------------------------------------------------- diff --git a/src/main/java/org/apache/log4j/net/JMSReceiverBeanInfo.java b/src/main/java/org/apache/log4j/net/JMSReceiverBeanInfo.java index 4bff41f..dae522f 100644 --- a/src/main/java/org/apache/log4j/net/JMSReceiverBeanInfo.java +++ b/src/main/java/org/apache/log4j/net/JMSReceiverBeanInfo.java @@ -5,9 +5,9 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -24,7 +24,6 @@ import java.beans.SimpleBeanInfo; * BeanInfo class for the JMSReceiver. * * @author Paul Smith <psm...@apache.org> - * */ public class JMSReceiverBeanInfo extends SimpleBeanInfo { @@ -35,14 +34,14 @@ public class JMSReceiverBeanInfo extends SimpleBeanInfo { try { - return new PropertyDescriptor[] { + return new PropertyDescriptor[]{ new PropertyDescriptor("name", JMSReceiver.class), new PropertyDescriptor("topicFactoryName", JMSReceiver.class), new PropertyDescriptor("topicName", JMSReceiver.class), new PropertyDescriptor("threshold", JMSReceiver.class), new PropertyDescriptor("jndiPath", JMSReceiver.class), new PropertyDescriptor("userId", - JMSReceiver.class), + JMSReceiver.class), }; } catch (Exception e) { } http://git-wip-us.apache.org/repos/asf/logging-chainsaw/blob/96ebd9ad/src/main/java/org/apache/log4j/net/MulticastAppender.java ---------------------------------------------------------------------- diff --git a/src/main/java/org/apache/log4j/net/MulticastAppender.java b/src/main/java/org/apache/log4j/net/MulticastAppender.java index 2e4cff8..c8b9fa1 100644 --- a/src/main/java/org/apache/log4j/net/MulticastAppender.java +++ b/src/main/java/org/apache/log4j/net/MulticastAppender.java @@ -5,9 +5,9 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,6 +17,12 @@ package org.apache.log4j.net; +import org.apache.log4j.AppenderSkeleton; +import org.apache.log4j.helpers.Constants; +import org.apache.log4j.helpers.LogLog; +import org.apache.log4j.spi.LoggingEvent; +import org.apache.log4j.xml.XMLLayout; + import java.io.IOException; import java.net.DatagramPacket; import java.net.InetAddress; @@ -25,320 +31,315 @@ import java.net.UnknownHostException; import java.util.HashMap; import java.util.Map; -import org.apache.log4j.AppenderSkeleton; -import org.apache.log4j.helpers.Constants; -import org.apache.log4j.spi.LoggingEvent; -import org.apache.log4j.helpers.LogLog; -import org.apache.log4j.xml.XMLLayout; - /** - * Multicast-based Appender. Works in conjunction with the MulticastReceiver, which expects - * a LoggingEvent encoded using XMLLayout. - * - * Sends log information as a multicast datagrams. - * - * <p>Messages are not sent as LoggingEvent objects but as text after - * applying XMLLayout. - * - * <p>The port and remoteHost properties can be set in configuration properties. - * By setting the remoteHost to a broadcast address any number of clients can - * listen for log messages. - * - * <p>This was inspired and really extended/copied from {@link SocketAppender}. Please - * see the docs for the proper credit to the authors of that class. + * Multicast-based Appender. Works in conjunction with the MulticastReceiver, which expects + * a LoggingEvent encoded using XMLLayout. + * <p> + * Sends log information as a multicast datagrams. + * <p> + * <p>Messages are not sent as LoggingEvent objects but as text after + * applying XMLLayout. + * <p> + * <p>The port and remoteHost properties can be set in configuration properties. + * By setting the remoteHost to a broadcast address any number of clients can + * listen for log messages. + * <p> + * <p>This was inspired and really extended/copied from {@link SocketAppender}. Please + * see the docs for the proper credit to the authors of that class. * - * @author <a href="mailto:kbr...@versatilesolutions.com">Kevin Brown</a> - * @author Scott Deboy <sde...@apache.org> - * + * @author <a href="mailto:kbr...@versatilesolutions.com">Kevin Brown</a> + * @author Scott Deboy <sde...@apache.org> */ public class MulticastAppender extends AppenderSkeleton implements PortBased { - /** - The default port number for the multicast packets. (9991). - */ - static final int DEFAULT_PORT = 9991; - - /** - * The MulticastDNS zone advertised by a MulticastAppender - * the MulticastAppender also adds a 'multicastAddress' property with the multicast address value as a string - */ - public static final String ZONE = "_log4j_xml_mcast_appender.local."; - - /** - We remember host name as String in addition to the resolved - InetAddress so that it can be returned via getOption(). - */ - String hostname; - String remoteHost; - String application; - int timeToLive; - InetAddress address; - int port = DEFAULT_PORT; - MulticastSocket outSocket; - private String encoding; - - private boolean locationInfo = false; - private boolean advertiseViaMulticastDNS; - private ZeroConfSupport zeroConf; - - public MulticastAppender() { - super(false); - } - - /** - Open the multicast sender for the <b>RemoteHost</b> and <b>Port</b>. - */ - public void activateOptions() { - try { - hostname = InetAddress.getLocalHost().getHostName(); - } catch (UnknownHostException uhe) { - try { - hostname = InetAddress.getLocalHost().getHostAddress(); - } catch (UnknownHostException uhe2) { - hostname = "unknown"; - } + /** + * The default port number for the multicast packets. (9991). + */ + static final int DEFAULT_PORT = 9991; + + /** + * The MulticastDNS zone advertised by a MulticastAppender + * the MulticastAppender also adds a 'multicastAddress' property with the multicast address value as a string + */ + public static final String ZONE = "_log4j_xml_mcast_appender.local."; + + /** + * We remember host name as String in addition to the resolved + * InetAddress so that it can be returned via getOption(). + */ + String hostname; + String remoteHost; + String application; + int timeToLive; + InetAddress address; + int port = DEFAULT_PORT; + MulticastSocket outSocket; + private String encoding; + + private boolean locationInfo = false; + private boolean advertiseViaMulticastDNS; + private ZeroConfSupport zeroConf; + + public MulticastAppender() { + super(false); + } + + /** + * Open the multicast sender for the <b>RemoteHost</b> and <b>Port</b>. + */ + public void activateOptions() { + try { + hostname = InetAddress.getLocalHost().getHostName(); + } catch (UnknownHostException uhe) { + try { + hostname = InetAddress.getLocalHost().getHostAddress(); + } catch (UnknownHostException uhe2) { + hostname = "unknown"; + } + } + + //allow system property of application to be primary + if (application == null) { + application = System.getProperty(Constants.APPLICATION_KEY); + } else { + if (System.getProperty(Constants.APPLICATION_KEY) != null) { + application = application + "-" + System.getProperty(Constants.APPLICATION_KEY); + } + } + + if (remoteHost != null) { + address = getAddressByName(remoteHost); + } else { + String err = "The RemoteHost property is required for MulticastAppender named " + name; + LogLog.error(err); + throw new IllegalStateException(err); + } + + if (layout == null) { + layout = new XMLLayout(); + } + + if (advertiseViaMulticastDNS) { + Map<String, String> properties = new HashMap<>(); + properties.put("multicastAddress", remoteHost); + zeroConf = new ZeroConfSupport(ZONE, port, getName(), properties); + zeroConf.advertise(); + } + connect(); + super.activateOptions(); } - //allow system property of application to be primary - if (application == null) { - application = System.getProperty(Constants.APPLICATION_KEY); - } else { - if (System.getProperty(Constants.APPLICATION_KEY) != null) { - application = application + "-" + System.getProperty(Constants.APPLICATION_KEY); - } + /** + * Close this appender. + * <p>This will mark the appender as closed and + * call then {@link #cleanUp} method. + */ + public synchronized void close() { + if (closed) { + return; + } + + this.closed = true; + if (advertiseViaMulticastDNS) { + zeroConf.unadvertise(); + } + cleanUp(); } - if(remoteHost != null) { - address = getAddressByName(remoteHost); - } else { - String err = "The RemoteHost property is required for MulticastAppender named "+ name; - LogLog.error(err); - throw new IllegalStateException(err); + /** + * Close the Socket and release the underlying + * connector thread if it has been created + */ + public void cleanUp() { + if (outSocket != null) { + try { + outSocket.close(); + } catch (Exception e) { + LogLog.error("Could not close outSocket.", e); + } + + outSocket = null; + } } - if (layout == null) { - layout = new XMLLayout(); + void connect() { + if (this.address == null) { + return; + } + + try { + // First, close the previous connection if any. + cleanUp(); + outSocket = new MulticastSocket(); + outSocket.setTimeToLive(timeToLive); + } catch (IOException e) { + LogLog.error("Error in connect method of MulticastAppender named " + name, e); + } } - - if (advertiseViaMulticastDNS) { - Map<String, String> properties = new HashMap<>(); - properties.put("multicastAddress", remoteHost); - zeroConf = new ZeroConfSupport(ZONE, port, getName(), properties); - zeroConf.advertise(); + + public void append(LoggingEvent event) { + if (event == null) { + return; + } + + if (locationInfo) { + event.getLocationInformation(); + } + + if (outSocket != null) { + event.setProperty(Constants.HOSTNAME_KEY, hostname); + + if (application != null) { + event.setProperty(Constants.APPLICATION_KEY, application); + } + + if (locationInfo) { + event.getLocationInformation(); + } + + + try { + StringBuilder buf = new StringBuilder(layout.format(event)); + + byte[] payload; + if (encoding == null) { + payload = buf.toString().getBytes(); + } else { + payload = buf.toString().getBytes(encoding); + } + + DatagramPacket dp = + new DatagramPacket(payload, payload.length, address, port); + outSocket.send(dp); + } catch (IOException e) { + outSocket = null; + LogLog.warn("Detected problem with Multicast connection: " + e); + } + } } - connect(); - super.activateOptions(); - } - - /** - Close this appender. - <p>This will mark the appender as closed and - call then {@link #cleanUp} method. - */ - public synchronized void close() { - if (closed) { - return; + + InetAddress getAddressByName(String host) { + try { + return InetAddress.getByName(host); + } catch (Exception e) { + LogLog.error("Could not find address of [" + host + "].", e); + return null; + } } - this.closed = true; - if (advertiseViaMulticastDNS) { - zeroConf.unadvertise(); + /** + * The <b>RemoteHost</b> option takes a string value which should be + * the host name or ipaddress to send the multicast packets. + */ + public void setRemoteHost(String host) { + remoteHost = host; } - cleanUp(); - } - - /** - Close the Socket and release the underlying - connector thread if it has been created - */ - public void cleanUp() { - if (outSocket != null) { - try { - outSocket.close(); - } catch (Exception e) { - LogLog.error("Could not close outSocket.", e); - } - - outSocket = null; + + /** + * Returns value of the <b>RemoteHost</b> option. + */ + public String getRemoteHost() { + return remoteHost; } - } - void connect() { - if (this.address == null) { - return; + /** + * The <b>LocationInfo</b> option takes a boolean value. If true, + * the information sent to the remote host will include location + * information. By default no location information is sent to the server. + */ + public void setLocationInfo(boolean locationInfo) { + this.locationInfo = locationInfo; } - try { - // First, close the previous connection if any. - cleanUp(); - outSocket = new MulticastSocket(); - outSocket.setTimeToLive(timeToLive); - } catch (IOException e) { - LogLog.error("Error in connect method of MulticastAppender named "+name, e); + /** + * Returns value of the <b>LocationInfo</b> option. + */ + public boolean getLocationInfo() { + return locationInfo; } - } - public void append(LoggingEvent event) { - if (event == null) { - return; + /** + * The <b>Encoding</b> option specifies how the bytes are encoded. If this option is not specified, + * the System encoding is used. + */ + public void setEncoding(String encoding) { + this.encoding = encoding; } - if(locationInfo) { - event.getLocationInformation(); - } + /** + * Returns value of the <b>Encoding</b> option. + */ + public String getEncoding() { + return encoding; + } - if (outSocket != null) { - event.setProperty(Constants.HOSTNAME_KEY, hostname); + /** + * The <b>App</b> option takes a string value which should be the name of the application getting logged. + * If property was already set (via system property), don't set here. + */ + public void setApplication(String app) { + this.application = app; + } - if (application != null) { - event.setProperty(Constants.APPLICATION_KEY, application); - } - - if(locationInfo) { - event.getLocationInformation(); - } + /** + * Returns value of the <b>App</b> option. + */ + public String getApplication() { + return application; + } + /** + * The <b>Time to live</b> option takes a positive integer representing + * the time to live value. + */ + public void setTimeToLive(int timeToLive) { + this.timeToLive = timeToLive; + } - try { - StringBuilder buf = new StringBuilder(layout.format(event)); + /** + * Returns value of the <b>Time to Live</b> option. + */ + public int getTimeToLive() { + return timeToLive; + } - byte[] payload; - if(encoding == null) { - payload = buf.toString().getBytes(); - } else { - payload = buf.toString().getBytes(encoding); - } + /** + * The <b>Port</b> option takes a positive integer representing + * the port where multicast packets will be sent. + */ + public void setPort(int port) { + this.port = port; + } - DatagramPacket dp = - new DatagramPacket(payload, payload.length, address, port); - outSocket.send(dp); - } catch (IOException e) { - outSocket = null; - LogLog.warn("Detected problem with Multicast connection: " + e); - } + /** + * Returns value of the <b>Port</b> option. + */ + public int getPort() { + return port; } - } - - InetAddress getAddressByName(String host) { - try { - return InetAddress.getByName(host); - } catch (Exception e) { - LogLog.error("Could not find address of [" + host + "].", e); - return null; + + /* (non-Javadoc) + * @see org.apache.log4j.net.NetworkBased#isActive() + */ + public boolean isActive() { + // TODO handle active/inactive + return true; } - } - - /** - The <b>RemoteHost</b> option takes a string value which should be - the host name or ipaddress to send the multicast packets. - */ - public void setRemoteHost(String host) { - remoteHost = host; - } - - /** - Returns value of the <b>RemoteHost</b> option. - */ - public String getRemoteHost() { - return remoteHost; - } - - /** - The <b>LocationInfo</b> option takes a boolean value. If true, - the information sent to the remote host will include location - information. By default no location information is sent to the server. - */ - public void setLocationInfo(boolean locationInfo) { - this.locationInfo = locationInfo; - } - - /** - * Returns value of the <b>LocationInfo</b> option. - */ - public boolean getLocationInfo() { - return locationInfo; - } - - /** - The <b>Encoding</b> option specifies how the bytes are encoded. If this option is not specified, - the System encoding is used. - */ - public void setEncoding(String encoding) { - this.encoding = encoding; - } - - /** - Returns value of the <b>Encoding</b> option. - */ - public String getEncoding() { - return encoding; - } - /** - The <b>App</b> option takes a string value which should be the name of the application getting logged. - If property was already set (via system property), don't set here. - */ - public void setApplication(String app) { - this.application = app; - } - - /** - Returns value of the <b>App</b> option. - */ - public String getApplication() { - return application; - } - - /** - The <b>Time to live</b> option takes a positive integer representing - the time to live value. - */ - public void setTimeToLive(int timeToLive) { - this.timeToLive = timeToLive; - } - - /** - Returns value of the <b>Time to Live</b> option. - */ - public int getTimeToLive() { - return timeToLive; - } - - /** - The <b>Port</b> option takes a positive integer representing - the port where multicast packets will be sent. - */ - public void setPort(int port) { - this.port = port; - } - - /** - Returns value of the <b>Port</b> option. - */ - public int getPort() { - return port; - } - - /* (non-Javadoc) - * @see org.apache.log4j.net.NetworkBased#isActive() - */ - public boolean isActive() { - // TODO handle active/inactive - return true; - } /** * Gets whether appender requires a layout. + * * @return false */ - public boolean requiresLayout() { - return true; - } + public boolean requiresLayout() { + return true; + } - public boolean isAdvertiseViaMulticastDNS() { - return advertiseViaMulticastDNS; - } + public boolean isAdvertiseViaMulticastDNS() { + return advertiseViaMulticastDNS; + } - public void setAdvertiseViaMulticastDNS(boolean advertiseViaMulticastDNS) { - this.advertiseViaMulticastDNS = advertiseViaMulticastDNS; - } + public void setAdvertiseViaMulticastDNS(boolean advertiseViaMulticastDNS) { + this.advertiseViaMulticastDNS = advertiseViaMulticastDNS; + } } http://git-wip-us.apache.org/repos/asf/logging-chainsaw/blob/96ebd9ad/src/main/java/org/apache/log4j/net/MulticastReceiver.java ---------------------------------------------------------------------- diff --git a/src/main/java/org/apache/log4j/net/MulticastReceiver.java b/src/main/java/org/apache/log4j/net/MulticastReceiver.java index 69b33ec..6e7ba3c 100644 --- a/src/main/java/org/apache/log4j/net/MulticastReceiver.java +++ b/src/main/java/org/apache/log4j/net/MulticastReceiver.java @@ -5,9 +5,9 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,255 +17,250 @@ package org.apache.log4j.net; -import java.io.IOException; -import java.net.DatagramPacket; -import java.net.InetAddress; -import java.net.MulticastSocket; -import java.net.SocketException; -import java.net.UnknownHostException; -import java.util.ArrayList; -import java.util.List; - import org.apache.log4j.plugins.Pauseable; import org.apache.log4j.plugins.Receiver; import org.apache.log4j.spi.Decoder; import org.apache.log4j.spi.LoggingEvent; +import java.io.IOException; +import java.net.*; +import java.util.ArrayList; +import java.util.List; + /** - * Multicast-based receiver. Accepts LoggingEvents encoded using - * MulticastAppender and XMLLayout. The the XML data is converted - * back to a LoggingEvent and is posted. - * - * @author Scott Deboy <sde...@apache.org> + * Multicast-based receiver. Accepts LoggingEvents encoded using + * MulticastAppender and XMLLayout. The the XML data is converted + * back to a LoggingEvent and is posted. * + * @author Scott Deboy <sde...@apache.org> */ public class MulticastReceiver extends Receiver implements PortBased, - AddressBased, Pauseable { - private static final int PACKET_LENGTH = 16384; - private int port; - private String address; - private String encoding; - private MulticastSocket socket = null; - - //default to log4j xml decoder - private String decoder = "org.apache.log4j.xml.XMLDecoder"; - private Decoder decoderImpl; - private MulticastHandlerThread handlerThread; - private MulticastReceiverThread receiverThread; - private boolean paused; - private boolean advertiseViaMulticastDNS; - private ZeroConfSupport zeroConf; - - /** - * The MulticastDNS zone advertised by a MulticastReceiver - */ - public static final String ZONE = "_log4j_xml_mcast_receiver.local."; - - public String getDecoder() { - return decoder; - } - - public void setDecoder(String decoder) { - this.decoder = decoder; - } - - public int getPort() { - return port; - } - - public void setPort(int port) { - this.port = port; - } - - public String getAddress() { - return address; - } - - /** - The <b>Encoding</b> option specifies how the bytes are encoded. If this option is not specified, - the system encoding will be used. - */ - public void setEncoding(String encoding) { - this.encoding = encoding; - } - - /** - Returns value of the <b>Encoding</b> option. - */ - public String getEncoding() { - return encoding; - } - - public synchronized void shutdown() { - active = false; - if (advertiseViaMulticastDNS) { - zeroConf.unadvertise(); - } - if (handlerThread != null) { - handlerThread.interrupt(); + AddressBased, Pauseable { + private static final int PACKET_LENGTH = 16384; + private int port; + private String address; + private String encoding; + private MulticastSocket socket = null; + + //default to log4j xml decoder + private String decoder = "org.apache.log4j.xml.XMLDecoder"; + private Decoder decoderImpl; + private MulticastHandlerThread handlerThread; + private MulticastReceiverThread receiverThread; + private boolean paused; + private boolean advertiseViaMulticastDNS; + private ZeroConfSupport zeroConf; + + /** + * The MulticastDNS zone advertised by a MulticastReceiver + */ + public static final String ZONE = "_log4j_xml_mcast_receiver.local."; + + public String getDecoder() { + return decoder; } - if (receiverThread != null) { - receiverThread.interrupt(); + + public void setDecoder(String decoder) { + this.decoder = decoder; } - if (socket != null) { - socket.close(); + + public int getPort() { + return port; } - } - - public void setAddress(String address) { - this.address = address; - } - - public boolean isPaused() { - return paused; - } - - public void setPaused(boolean b) { - paused = b; - } - - public void activateOptions() { - InetAddress addr = null; - - try { - Class c = Class.forName(decoder); - Object o = c.newInstance(); - - if (o instanceof Decoder) { - this.decoderImpl = (Decoder) o; - } - } catch (ClassNotFoundException cnfe) { - getLogger().warn("Unable to find decoder", cnfe); - } catch (IllegalAccessException | InstantiationException iae) { - getLogger().warn("Could not construct decoder", iae); + + public void setPort(int port) { + this.port = port; } - try { - addr = InetAddress.getByName(address); - } catch (UnknownHostException uhe) { - uhe.printStackTrace(); + public String getAddress() { + return address; } - try { - active = true; - socket = new MulticastSocket(port); - socket.joinGroup(addr); - receiverThread = new MulticastReceiverThread(); - receiverThread.start(); - handlerThread = new MulticastHandlerThread(); - handlerThread.start(); - if (advertiseViaMulticastDNS) { - zeroConf = new ZeroConfSupport(ZONE, port, getName()); - zeroConf.advertise(); - } - - } catch (IOException ioe) { - ioe.printStackTrace(); + /** + * The <b>Encoding</b> option specifies how the bytes are encoded. If this option is not specified, + * the system encoding will be used. + */ + public void setEncoding(String encoding) { + this.encoding = encoding; } - } - public void setAdvertiseViaMulticastDNS(boolean advertiseViaMulticastDNS) { - this.advertiseViaMulticastDNS = advertiseViaMulticastDNS; + /** + * Returns value of the <b>Encoding</b> option. + */ + public String getEncoding() { + return encoding; } - public boolean isAdvertiseViaMulticastDNS() { - return advertiseViaMulticastDNS; + public synchronized void shutdown() { + active = false; + if (advertiseViaMulticastDNS) { + zeroConf.unadvertise(); + } + if (handlerThread != null) { + handlerThread.interrupt(); + } + if (receiverThread != null) { + receiverThread.interrupt(); + } + if (socket != null) { + socket.close(); + } } - class MulticastHandlerThread extends Thread { - private final List<String> list = new ArrayList<>(); + public void setAddress(String address) { + this.address = address; + } - public MulticastHandlerThread() { - setDaemon(true); + public boolean isPaused() { + return paused; } - public void append(String data) { - synchronized (list) { - list.add(data); - list.notify(); - } + public void setPaused(boolean b) { + paused = b; } - public void run() { - ArrayList<String> list2 = new ArrayList<>(); + public void activateOptions() { + InetAddress addr = null; + + try { + Class c = Class.forName(decoder); + Object o = c.newInstance(); - while (isAlive()) { - synchronized (list) { - try { - while (list.size() == 0) { - list.wait(); + if (o instanceof Decoder) { + this.decoderImpl = (Decoder) o; } + } catch (ClassNotFoundException cnfe) { + getLogger().warn("Unable to find decoder", cnfe); + } catch (IllegalAccessException | InstantiationException iae) { + getLogger().warn("Could not construct decoder", iae); + } + + try { + addr = InetAddress.getByName(address); + } catch (UnknownHostException uhe) { + uhe.printStackTrace(); + } - if (list.size() > 0) { - list2.addAll(list); - list.clear(); + try { + active = true; + socket = new MulticastSocket(port); + socket.joinGroup(addr); + receiverThread = new MulticastReceiverThread(); + receiverThread.start(); + handlerThread = new MulticastHandlerThread(); + handlerThread.start(); + if (advertiseViaMulticastDNS) { + zeroConf = new ZeroConfSupport(ZONE, port, getName()); + zeroConf.advertise(); } - } catch (InterruptedException ie) { - } + + } catch (IOException ioe) { + ioe.printStackTrace(); + } + } + + public void setAdvertiseViaMulticastDNS(boolean advertiseViaMulticastDNS) { + this.advertiseViaMulticastDNS = advertiseViaMulticastDNS; + } + + public boolean isAdvertiseViaMulticastDNS() { + return advertiseViaMulticastDNS; + } + + class MulticastHandlerThread extends Thread { + private final List<String> list = new ArrayList<>(); + + public MulticastHandlerThread() { + setDaemon(true); } - if (list2.size() > 0) { + public void append(String data) { + synchronized (list) { + list.add(data); + list.notify(); + } + } - for (Object aList2 : list2) { - String data = (String) aList2; - List<LoggingEvent> v = decoderImpl.decodeEvents(data.trim()); + public void run() { + ArrayList<String> list2 = new ArrayList<>(); - if (v != null) { + while (isAlive()) { + synchronized (list) { + try { + while (list.size() == 0) { + list.wait(); + } - for (Object aV : v) { - if (!isPaused()) { - doPost((LoggingEvent) aV); + if (list.size() > 0) { + list2.addAll(list); + list.clear(); } + } catch (InterruptedException ie) { } } - } - list2.clear(); - } else { - try { - synchronized (this) { - wait(1000); + if (list2.size() > 0) { + + for (Object aList2 : list2) { + String data = (String) aList2; + List<LoggingEvent> v = decoderImpl.decodeEvents(data.trim()); + + if (v != null) { + + for (Object aV : v) { + if (!isPaused()) { + doPost((LoggingEvent) aV); + } + } + } + } + + list2.clear(); + } else { + try { + synchronized (this) { + wait(1000); + } + } catch (InterruptedException ie) { + } + } } - } catch (InterruptedException ie) { - } } - } } - } - class MulticastReceiverThread extends Thread { - public MulticastReceiverThread() { - setDaemon(true); - } + class MulticastReceiverThread extends Thread { + public MulticastReceiverThread() { + setDaemon(true); + } - public void run() { - active = true; + public void run() { + active = true; - byte[] b = new byte[PACKET_LENGTH]; - DatagramPacket p = new DatagramPacket(b, b.length); + byte[] b = new byte[PACKET_LENGTH]; + DatagramPacket p = new DatagramPacket(b, b.length); - while (active) { - try { - socket.receive(p); - - //this string constructor which accepts a charset throws an exception if it is - //null - if (encoding == null) { - handlerThread.append( - new String(p.getData(), 0, p.getLength())); - } else { - handlerThread.append( - new String(p.getData(), 0, p.getLength(), encoding)); - } - } catch (SocketException se) { - //disconnected - } catch (IOException ioe) { - ioe.printStackTrace(); - } - } + while (active) { + try { + socket.receive(p); + + //this string constructor which accepts a charset throws an exception if it is + //null + if (encoding == null) { + handlerThread.append( + new String(p.getData(), 0, p.getLength())); + } else { + handlerThread.append( + new String(p.getData(), 0, p.getLength(), encoding)); + } + } catch (SocketException se) { + //disconnected + } catch (IOException ioe) { + ioe.printStackTrace(); + } + } - getLogger().debug("{}'s thread is ending.", MulticastReceiver.this.getName()); + getLogger().debug("{}'s thread is ending.", MulticastReceiver.this.getName()); + } } - } } http://git-wip-us.apache.org/repos/asf/logging-chainsaw/blob/96ebd9ad/src/main/java/org/apache/log4j/net/MulticastReceiverBeanInfo.java ---------------------------------------------------------------------- diff --git a/src/main/java/org/apache/log4j/net/MulticastReceiverBeanInfo.java b/src/main/java/org/apache/log4j/net/MulticastReceiverBeanInfo.java index 80a54c2..ec986c8 100644 --- a/src/main/java/org/apache/log4j/net/MulticastReceiverBeanInfo.java +++ b/src/main/java/org/apache/log4j/net/MulticastReceiverBeanInfo.java @@ -5,9 +5,9 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -24,7 +24,6 @@ import java.beans.SimpleBeanInfo; * BeanInfo class for the meta-data of the MulticastReceiver. * * @author Paul Smith <psm...@apache.org> - * */ public class MulticastReceiverBeanInfo extends SimpleBeanInfo { @@ -35,7 +34,7 @@ public class MulticastReceiverBeanInfo extends SimpleBeanInfo { try { - return new PropertyDescriptor[] { + return new PropertyDescriptor[]{ new PropertyDescriptor("name", MulticastReceiver.class), new PropertyDescriptor("address", MulticastReceiver.class), new PropertyDescriptor("port", MulticastReceiver.class), http://git-wip-us.apache.org/repos/asf/logging-chainsaw/blob/96ebd9ad/src/main/java/org/apache/log4j/net/NetworkBased.java ---------------------------------------------------------------------- diff --git a/src/main/java/org/apache/log4j/net/NetworkBased.java b/src/main/java/org/apache/log4j/net/NetworkBased.java index 9c5153f..8bd3908 100644 --- a/src/main/java/org/apache/log4j/net/NetworkBased.java +++ b/src/main/java/org/apache/log4j/net/NetworkBased.java @@ -21,19 +21,20 @@ package org.apache.log4j.net; * The parent of all the Network based interfaces. * * @author Paul Smith (psm...@apache.org) - * */ public interface NetworkBased { /** * Get name. + * * @return name. */ - String getName(); + String getName(); /** * Get if item is active. + * * @return if true, item is active. */ - boolean isActive(); + boolean isActive(); } http://git-wip-us.apache.org/repos/asf/logging-chainsaw/blob/96ebd9ad/src/main/java/org/apache/log4j/net/PortBased.java ---------------------------------------------------------------------- diff --git a/src/main/java/org/apache/log4j/net/PortBased.java b/src/main/java/org/apache/log4j/net/PortBased.java index c7c1f97..98a9b3e 100644 --- a/src/main/java/org/apache/log4j/net/PortBased.java +++ b/src/main/java/org/apache/log4j/net/PortBased.java @@ -23,12 +23,12 @@ package org.apache.log4j.net; * interface so that they can be treated generically. * * @author Paul Smith (psm...@apache.org) - * */ public interface PortBased extends NetworkBased { - /** - * Returns the Port # that this net based thing is using. - * @return int port number - */ - int getPort(); + /** + * Returns the Port # that this net based thing is using. + * + * @return int port number + */ + int getPort(); } http://git-wip-us.apache.org/repos/asf/logging-chainsaw/blob/96ebd9ad/src/main/java/org/apache/log4j/net/SocketHubReceiver.java ---------------------------------------------------------------------- diff --git a/src/main/java/org/apache/log4j/net/SocketHubReceiver.java b/src/main/java/org/apache/log4j/net/SocketHubReceiver.java index 5bef1e1..7cc398d 100644 --- a/src/main/java/org/apache/log4j/net/SocketHubReceiver.java +++ b/src/main/java/org/apache/log4j/net/SocketHubReceiver.java @@ -28,381 +28,401 @@ import java.util.Collections; import java.util.List; /** - SocketHubReceiver receives a remote logging event on a configured - socket and "posts" it to a LoggerRepository as if the event was - generated locally. This class is designed to receive events from - the SocketHubAppender class (or classes that send compatible events). - - <p>Once the event has been "posted", it will be handled by the - appenders currently configured in the LoggerRespository. - - @author Mark Womack - @author Ceki Gülcü - @author Paul Smith (psm...@apache.org) -*/ + * SocketHubReceiver receives a remote logging event on a configured + * socket and "posts" it to a LoggerRepository as if the event was + * generated locally. This class is designed to receive events from + * the SocketHubAppender class (or classes that send compatible events). + * <p> + * <p>Once the event has been "posted", it will be handled by the + * appenders currently configured in the LoggerRespository. + * + * @author Mark Womack + * @author Ceki Gülcü + * @author Paul Smith (psm...@apache.org) + */ public class SocketHubReceiver -extends Receiver implements SocketNodeEventListener, PortBased { + extends Receiver implements SocketNodeEventListener, PortBased { /** * Default reconnection delay. */ - static final int DEFAULT_RECONNECTION_DELAY = 30000; + static final int DEFAULT_RECONNECTION_DELAY = 30000; /** * Host. */ - protected String host; + protected String host; /** * Port. */ - protected int port; + protected int port; /** * Reconnection delay. */ - protected int reconnectionDelay = DEFAULT_RECONNECTION_DELAY; + protected int reconnectionDelay = DEFAULT_RECONNECTION_DELAY; - /** - * The MulticastDNS zone advertised by a SocketHubReceiver - */ - public static final String ZONE = "_log4j_obj_tcpconnect_receiver.local."; + /** + * The MulticastDNS zone advertised by a SocketHubReceiver + */ + public static final String ZONE = "_log4j_obj_tcpconnect_receiver.local."; /** * Active. */ - protected boolean active = false; + protected boolean active = false; /** * Connector. */ - protected Connector connector; + protected Connector connector; /** * Socket. */ - protected SocketNode13 socketNode; + protected SocketNode13 socketNode; /** * Listener list. */ - private final List listenerList = Collections.synchronizedList(new ArrayList()); + private final List listenerList = Collections.synchronizedList(new ArrayList()); - private boolean advertiseViaMulticastDNS; - private ZeroConfSupport zeroConf; + private boolean advertiseViaMulticastDNS; + private ZeroConfSupport zeroConf; /** * Create new instance. */ - public SocketHubReceiver() { - super(); - } + public SocketHubReceiver() { + super(); + } /** * Create new instance. + * * @param h host * @param p port */ - public SocketHubReceiver(final String h, - final int p) { - super(); - host = h; - port = p; - } + public SocketHubReceiver(final String h, + final int p) { + super(); + host = h; + port = p; + } /** * Create new instance. - * @param h host - * @param p port + * + * @param h host + * @param p port * @param repo logger repository */ - public SocketHubReceiver(final String h, - final int p, - final LoggerRepository repo) { - super(); - host = h; - port = p; - repository = repo; - } - - /** - * Adds a SocketNodeEventListener to this receiver to be notified - * of SocketNode events. - * @param l listener - */ - public void addSocketNodeEventListener(final SocketNodeEventListener l) { - listenerList.add(l); - } - - /** - * Removes a specific SocketNodeEventListener from this instance - * so that it will no longer be notified of SocketNode events. - * @param l listener - */ - public void removeSocketNodeEventListener( - final SocketNodeEventListener l) { - listenerList.remove(l); - } - - /** - Get the remote host to connect to for logging events. - @return host - */ - public String getHost() { - return host; - } - - /** - * Configures the Host property, this will require activateOptions - * to be called for this to take effect. - * @param remoteHost address of remote host. - */ - public void setHost(final String remoteHost) { - this.host = remoteHost; - } - /** - Set the remote host to connect to for logging events. - Equivalent to setHost. - @param remoteHost address of remote host. - */ - public void setPort(final String remoteHost) { - host = remoteHost; - } - - /** - Get the remote port to connect to for logging events. - @return port - */ - public int getPort() { - return port; - } - - /** - Set the remote port to connect to for logging events. - @param p port - */ - public void setPort(final int p) { - this.port = p; - } - - /** - The <b>ReconnectionDelay</b> option takes a positive integer - representing the number of milliseconds to wait between each - failed connection attempt to the server. The default value of - this option is 30000 which corresponds to 30 seconds. - - <p>Setting this option to zero turns off reconnection - capability. - @param delay milliseconds to wait or zero to not reconnect. - */ - public void setReconnectionDelay(final int delay) { - int oldValue = this.reconnectionDelay; - this.reconnectionDelay = delay; - firePropertyChange("reconnectionDelay", oldValue, this.reconnectionDelay); - } - - /** - Returns value of the <b>ReconnectionDelay</b> option. - @return value of reconnection delay option. - */ - public int getReconnectionDelay() { - return reconnectionDelay; - } - - /** - * Returns true if the receiver is the same class and they are - * configured for the same properties, and super class also considers - * them to be equivalent. This is used by PluginRegistry when determining - * if the a similarly configured receiver is being started. - * - * @param testPlugin The plugin to test equivalency against. - * @return boolean True if the testPlugin is equivalent to this plugin. - */ - public boolean isEquivalent(final Plugin testPlugin) { - if (testPlugin != null && testPlugin instanceof SocketHubReceiver) { - SocketHubReceiver sReceiver = (SocketHubReceiver) testPlugin; - - return (port == sReceiver.getPort() - && host.equals(sReceiver.getHost()) - && reconnectionDelay == sReceiver.getReconnectionDelay() - && super.isEquivalent(testPlugin)); + public SocketHubReceiver(final String h, + final int p, + final LoggerRepository repo) { + super(); + host = h; + port = p; + repository = repo; + } + + /** + * Adds a SocketNodeEventListener to this receiver to be notified + * of SocketNode events. + * + * @param l listener + */ + public void addSocketNodeEventListener(final SocketNodeEventListener l) { + listenerList.add(l); + } + + /** + * Removes a specific SocketNodeEventListener from this instance + * so that it will no longer be notified of SocketNode events. + * + * @param l listener + */ + public void removeSocketNodeEventListener( + final SocketNodeEventListener l) { + listenerList.remove(l); + } + + /** + * Get the remote host to connect to for logging events. + * + * @return host + */ + public String getHost() { + return host; + } + + /** + * Configures the Host property, this will require activateOptions + * to be called for this to take effect. + * + * @param remoteHost address of remote host. + */ + public void setHost(final String remoteHost) { + this.host = remoteHost; + } + + /** + * Set the remote host to connect to for logging events. + * Equivalent to setHost. + * + * @param remoteHost address of remote host. + */ + public void setPort(final String remoteHost) { + host = remoteHost; + } + + /** + * Get the remote port to connect to for logging events. + * + * @return port + */ + public int getPort() { + return port; + } + + /** + * Set the remote port to connect to for logging events. + * + * @param p port + */ + public void setPort(final int p) { + this.port = p; + } + + /** + * The <b>ReconnectionDelay</b> option takes a positive integer + * representing the number of milliseconds to wait between each + * failed connection attempt to the server. The default value of + * this option is 30000 which corresponds to 30 seconds. + * <p> + * <p>Setting this option to zero turns off reconnection + * capability. + * + * @param delay milliseconds to wait or zero to not reconnect. + */ + public void setReconnectionDelay(final int delay) { + int oldValue = this.reconnectionDelay; + this.reconnectionDelay = delay; + firePropertyChange("reconnectionDelay", oldValue, this.reconnectionDelay); } - return false; - } - - /** - Sets the flag to indicate if receiver is active or not. - @param b new value - */ - protected synchronized void setActive(final boolean b) { - active = b; - } - - /** - Starts the SocketReceiver with the current options. */ - public void activateOptions() { - if (!isActive()) { - setActive(true); - if (advertiseViaMulticastDNS) { - zeroConf = new ZeroConfSupport(ZONE, port, getName()); - zeroConf.advertise(); - } - - fireConnector(false); + + /** + * Returns value of the <b>ReconnectionDelay</b> option. + * + * @return value of reconnection delay option. + */ + public int getReconnectionDelay() { + return reconnectionDelay; } - } - - /** - Called when the receiver should be stopped. Closes the socket */ - public synchronized void shutdown() { - // mark this as no longer running - active = false; - - // close the socket - try { - if (socketNode != null) { - socketNode.close(); - socketNode = null; - } - } catch (Exception e) { - getLogger().info("Excpetion closing socket", e); - // ignore for now + + /** + * Returns true if the receiver is the same class and they are + * configured for the same properties, and super class also considers + * them to be equivalent. This is used by PluginRegistry when determining + * if the a similarly configured receiver is being started. + * + * @param testPlugin The plugin to test equivalency against. + * @return boolean True if the testPlugin is equivalent to this plugin. + */ + public boolean isEquivalent(final Plugin testPlugin) { + if (testPlugin != null && testPlugin instanceof SocketHubReceiver) { + SocketHubReceiver sReceiver = (SocketHubReceiver) testPlugin; + + return (port == sReceiver.getPort() + && host.equals(sReceiver.getHost()) + && reconnectionDelay == sReceiver.getReconnectionDelay() + && super.isEquivalent(testPlugin)); + } + return false; } - // stop the connector - if (connector != null) { - connector.interrupted = true; - connector = null; // allow gc + /** + * Sets the flag to indicate if receiver is active or not. + * + * @param b new value + */ + protected synchronized void setActive(final boolean b) { + active = b; } - if (advertiseViaMulticastDNS) { - zeroConf.unadvertise(); + + /** + * Starts the SocketReceiver with the current options. + */ + public void activateOptions() { + if (!isActive()) { + setActive(true); + if (advertiseViaMulticastDNS) { + zeroConf = new ZeroConfSupport(ZONE, port, getName()); + zeroConf.advertise(); + } + + fireConnector(false); + } } - } - - /** - Listen for a socketClosedEvent from the SocketNode. Reopen the - socket if this receiver is still active. - @param e exception not used. - */ - public void socketClosedEvent(final Exception e) { - // if it is a non-normal closed event - // we clear the connector object here - // so that it actually does reconnect if the - // remote socket dies. - if (e != null) { - connector = null; - fireConnector(true); + + /** + * Called when the receiver should be stopped. Closes the socket + */ + public synchronized void shutdown() { + // mark this as no longer running + active = false; + + // close the socket + try { + if (socketNode != null) { + socketNode.close(); + socketNode = null; + } + } catch (Exception e) { + getLogger().info("Excpetion closing socket", e); + // ignore for now + } + + // stop the connector + if (connector != null) { + connector.interrupted = true; + connector = null; // allow gc + } + if (advertiseViaMulticastDNS) { + zeroConf.unadvertise(); + } + } + + /** + * Listen for a socketClosedEvent from the SocketNode. Reopen the + * socket if this receiver is still active. + * + * @param e exception not used. + */ + public void socketClosedEvent(final Exception e) { + // if it is a non-normal closed event + // we clear the connector object here + // so that it actually does reconnect if the + // remote socket dies. + if (e != null) { + connector = null; + fireConnector(true); + } } - } /** * Fire connectors. + * * @param isReconnect true if reconnect. */ - private synchronized void fireConnector(final boolean isReconnect) { - if (active && connector == null) { - getLogger().debug("Starting a new connector thread."); - connector = new Connector(isReconnect); - connector.setDaemon(true); - connector.setPriority(Thread.MIN_PRIORITY); - connector.start(); + private synchronized void fireConnector(final boolean isReconnect) { + if (active && connector == null) { + getLogger().debug("Starting a new connector thread."); + connector = new Connector(isReconnect); + connector.setDaemon(true); + connector.setPriority(Thread.MIN_PRIORITY); + connector.start(); + } } - } /** * Set socket. + * * @param newSocket new value for socket. */ - private synchronized void setSocket(final Socket newSocket) { - connector = null; - socketNode = new SocketNode13(newSocket, this); - socketNode.addSocketNodeEventListener(this); - - synchronized (listenerList) { - for (Object aListenerList : listenerList) { - SocketNodeEventListener listener = + private synchronized void setSocket(final Socket newSocket) { + connector = null; + socketNode = new SocketNode13(newSocket, this); + socketNode.addSocketNodeEventListener(this); + + synchronized (listenerList) { + for (Object aListenerList : listenerList) { + SocketNodeEventListener listener = (SocketNodeEventListener) aListenerList; - socketNode.addSocketNodeEventListener(listener); + socketNode.addSocketNodeEventListener(listener); + } } + new Thread(socketNode).start(); } - new Thread(socketNode).start(); - } - - public void setAdvertiseViaMulticastDNS(boolean advertiseViaMulticastDNS) { - this.advertiseViaMulticastDNS = advertiseViaMulticastDNS; - } - - public boolean isAdvertiseViaMulticastDNS() { - return advertiseViaMulticastDNS; - } - - /** - The Connector will reconnect when the server becomes available - again. It does this by attempting to open a new connection every - <code>reconnectionDelay</code> milliseconds. - - <p>It stops trying whenever a connection is established. It will - restart to try reconnect to the server when previpously open - connection is droppped. - - @author Ceki Gülcü - */ - private final class Connector extends Thread { - - /** - * Interruption status. - */ - boolean interrupted = false; - /** - * If true, then delay on next iteration. - */ - boolean doDelay; - - /** - * Create new instance. - * @param isReconnect true if reconnecting. - */ - public Connector(final boolean isReconnect) { - super(); - doDelay = isReconnect; + + public void setAdvertiseViaMulticastDNS(boolean advertiseViaMulticastDNS) { + this.advertiseViaMulticastDNS = advertiseViaMulticastDNS; } - /** - * Attempt to connect until interrupted. - */ - public void run() { - while (!interrupted) { - try { - if (doDelay) { - getLogger().debug("waiting for " + reconnectionDelay - + " milliseconds before reconnecting."); - sleep(reconnectionDelay); - } - doDelay = true; - getLogger().debug("Attempting connection to " + host); - Socket s = new Socket(host, port); - setSocket(s); - getLogger().debug( - "Connection established. Exiting connector thread."); - break; - } catch (InterruptedException e) { - getLogger().debug("Connector interrupted. Leaving loop."); - return; - } catch (java.net.ConnectException e) { - getLogger().debug("Remote host {} refused connection.", host); - } catch (IOException e) { - getLogger().debug("Could not connect to {}. Exception is {}.", - host, e); + public boolean isAdvertiseViaMulticastDNS() { + return advertiseViaMulticastDNS; + } + + /** + * The Connector will reconnect when the server becomes available + * again. It does this by attempting to open a new connection every + * <code>reconnectionDelay</code> milliseconds. + * <p> + * <p>It stops trying whenever a connection is established. It will + * restart to try reconnect to the server when previpously open + * connection is droppped. + * + * @author Ceki Gülcü + */ + private final class Connector extends Thread { + + /** + * Interruption status. + */ + boolean interrupted = false; + /** + * If true, then delay on next iteration. + */ + boolean doDelay; + + /** + * Create new instance. + * + * @param isReconnect true if reconnecting. + */ + public Connector(final boolean isReconnect) { + super(); + doDelay = isReconnect; + } + + /** + * Attempt to connect until interrupted. + */ + public void run() { + while (!interrupted) { + try { + if (doDelay) { + getLogger().debug("waiting for " + reconnectionDelay + + " milliseconds before reconnecting."); + sleep(reconnectionDelay); + } + doDelay = true; + getLogger().debug("Attempting connection to " + host); + Socket s = new Socket(host, port); + setSocket(s); + getLogger().debug( + "Connection established. Exiting connector thread."); + break; + } catch (InterruptedException e) { + getLogger().debug("Connector interrupted. Leaving loop."); + return; + } catch (java.net.ConnectException e) { + getLogger().debug("Remote host {} refused connection.", host); + } catch (IOException e) { + getLogger().debug("Could not connect to {}. Exception is {}.", + host, e); + } + } } - } } - } /** * This method does nothing. + * * @param remoteInfo remote info. */ - public void socketOpened(final String remoteInfo) { + public void socketOpened(final String remoteInfo) { - // This method does nothing. - } + // This method does nothing. + } }