You are viewing a plain text version of this content. The canonical link for it is here.
Posted to log4j-dev@logging.apache.org by rg...@apache.org on 2010/05/13 08:31:09 UTC
svn commit: r943816 [5/9] - in
/logging/log4j/branches/BRANCH_2_0_EXPERIMENTAL/rgoers: ./ log4j12-api/
log4j12-api/src/ log4j12-api/src/main/ log4j12-api/src/main/java/
log4j12-api/src/main/java/org/ log4j12-api/src/main/java/org/apache/
log4j12-api/sr...
Added: logging/log4j/branches/BRANCH_2_0_EXPERIMENTAL/rgoers/log4j2-core/src/main/java/org/apache/logging/log4j/core/config/BaseConfiguration.java
URL: http://svn.apache.org/viewvc/logging/log4j/branches/BRANCH_2_0_EXPERIMENTAL/rgoers/log4j2-core/src/main/java/org/apache/logging/log4j/core/config/BaseConfiguration.java?rev=943816&view=auto
==============================================================================
--- logging/log4j/branches/BRANCH_2_0_EXPERIMENTAL/rgoers/log4j2-core/src/main/java/org/apache/logging/log4j/core/config/BaseConfiguration.java (added)
+++ logging/log4j/branches/BRANCH_2_0_EXPERIMENTAL/rgoers/log4j2-core/src/main/java/org/apache/logging/log4j/core/config/BaseConfiguration.java Thu May 13 06:31:04 2010
@@ -0,0 +1,418 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache license, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the license for the specific language governing permissions and
+ * limitations under the license.
+ */
+package org.apache.logging.log4j.core.config;
+
+import org.apache.logging.log4j.Logger;
+import org.apache.logging.log4j.core.Appender;
+import org.apache.logging.log4j.core.Filter;
+import org.apache.logging.log4j.core.config.plugins.Plugin;
+import org.apache.logging.log4j.core.config.plugins.PluginFactory;
+import org.apache.logging.log4j.core.config.plugins.PluginManager;
+import org.apache.logging.log4j.core.config.plugins.PluginType;
+import org.apache.logging.log4j.internal.StatusLogger;
+
+import java.lang.reflect.Method;
+import java.lang.reflect.Modifier;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentMap;
+import java.util.concurrent.CopyOnWriteArrayList;
+
+/**
+ *
+ */
+public class BaseConfiguration implements Configuration {
+
+ private String name;
+
+ private ConcurrentMap<String, Appender> appenders = new ConcurrentHashMap<String, Appender>();
+
+ private ConcurrentMap<String, LoggerConfig> loggers = new ConcurrentHashMap<String, LoggerConfig>();
+
+ private LoggerConfig root = new LoggerConfig();
+
+ private List<Filter> filters = new CopyOnWriteArrayList<Filter>();
+
+ private boolean hasFilters = false;
+
+ private boolean started = false;
+
+ protected Node rootNode;
+
+ protected PluginManager pluginManager;
+
+ protected final static Logger logger = StatusLogger.getLogger();
+
+ protected BaseConfiguration() {
+ pluginManager = new PluginManager("Core");
+ rootNode = new Node(this);
+ }
+
+ public void start() {
+ pluginManager.collectPlugins();
+ setup();
+ doConfigure();
+ for (Appender appender : appenders.values()) {
+ appender.start();
+ }
+
+ for (Filter filter : filters) {
+ filter.start();
+ }
+ }
+
+ public void stop() {
+ for (LoggerConfig logger : loggers.values()) {
+ logger.clearAppenders();
+ }
+ for (Appender appender : appenders.values()) {
+ appender.stop();
+ }
+ for (Filter filter : filters) {
+ filter.stop();
+ }
+ }
+
+ protected void setup() {
+ }
+
+ protected void doConfigure() {
+ createConfiguration(rootNode);
+ for (Node child : rootNode.getChildren()) {
+ if (child.getObject() == null) {
+ continue;
+ }
+ if (child.getName().equals("appenders")) {
+ appenders = (ConcurrentMap<String, Appender>) child.getObject();
+ } else if (child.getName().equals("filters")) {
+ filters = new CopyOnWriteArrayList((Filter[]) child.getObject());
+ } else if (child.getName().equals("loggers")) {
+ Loggers l = (Loggers) child.getObject();
+ loggers = l.map;
+ root = l.root;
+ }
+ }
+
+ for (Map.Entry<String, LoggerConfig> entry : loggers.entrySet()) {
+ LoggerConfig l = entry.getValue();
+ for (String ref : l.getAppenderRefs()) {
+ Appender app = appenders.get(ref);
+ if (app != null) {
+ l.addAppender(app);
+ } else {
+ logger.error("Unable to locate appender " + ref + " for logger " + l.getName());
+ }
+ }
+ }
+
+ setParents();
+ }
+
+ protected PluginManager getPluginManager() {
+ return pluginManager;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public Appender getAppender(String name) {
+ return appenders.get(name);
+ }
+
+ public Map<String, Appender> getAppenders() {
+ return appenders;
+ }
+
+ public void addAppender(Appender appender) {
+ appenders.put(appender.getName(), appender);
+ }
+
+ public void addLoggerAppender(String name, Appender appender) {
+ LoggerConfig lc = getLoggerConfig(name);
+ if (lc.getName().equals(name)) {
+ lc.addAppender(appender);
+ } else {
+ LoggerConfig nlc = new LoggerConfig(name, lc.getLevel(), lc.isAdditive());
+ nlc.addAppender(appender);
+ nlc.setParent(lc);
+ loggers.putIfAbsent(name, nlc);
+ setParents();
+ }
+ }
+
+ public void removeAppender(String name) {
+ for (LoggerConfig logger : loggers.values()) {
+ logger.removeAppender(name);
+ }
+ Appender app = appenders.remove(name);
+
+ if (app != null) {
+ app.stop();
+ }
+ }
+
+ public LoggerConfig getLoggerConfig(String name) {
+ if (loggers.containsKey(name)) {
+ return loggers.get(name);
+ }
+ int i = 0;
+ String substr = name;
+ while ((i = substr.lastIndexOf(".")) > 0) {
+ substr = name.substring(0, i);
+ if (loggers.containsKey(substr)) {
+ return loggers.get(substr);
+ }
+ }
+ return root;
+ }
+
+ public LoggerConfig getRootLogger() {
+ return root;
+ }
+
+ public Map<String, LoggerConfig> getLoggers() {
+ return Collections.unmodifiableMap(loggers);
+ }
+
+ public LoggerConfig getLogger(String name) {
+ return loggers.get(name);
+ }
+
+ /**
+ * Adding a logger cannot be done atomically so is not allowed in an active configuration. Adding
+ * or removing a Logger requires creating a new configuration and then switching.
+ *
+ * @param name The name of the Logger.
+ * @param loggerConfig The LoggerConfig.
+ */
+ public void addLogger(String name, LoggerConfig loggerConfig) {
+ if (started) {
+ String msg = "Cannot add logger " + name + " to an active configuration";
+ logger.warn(msg);
+ throw new IllegalStateException(msg);
+ }
+ loggers.put(name, loggerConfig);
+ setParents();
+ }
+
+ /**
+ * Removing a logger cannot be done atomically so is not allowed in an active configuration. Adding
+ * or removing a Logger requires creating a new configuration and then switching.
+ *
+ * @param name The name of the Logger.
+ */
+ public void removeLogger(String name) {
+ if (started) {
+ String msg = "Cannot remove logger " + name + " in an active configuration";
+ logger.warn(msg);
+ throw new IllegalStateException(msg);
+ }
+ loggers.remove(name);
+ }
+
+ public Iterator<Filter> getFilters() {
+ return filters.iterator();
+ }
+
+ public void addFilter(Filter filter) {
+ filters.add(filter);
+ hasFilters = filters.size() > 0;
+ }
+
+ public void removeFilter(Filter filter) {
+ filters.remove(filter);
+ hasFilters = filters.size() > 0;
+ }
+
+ public boolean hasFilters() {
+ return hasFilters;
+ }
+
+ private void createConfiguration(Node node) {
+ for (Node child : node.getChildren()) {
+ createConfiguration(child);
+ }
+ PluginType type = pluginManager.getPluginType(node.getName());
+ if (type == null) {
+ if (node.getParent() != null) {
+ logger.error("Unable to locate plugin for " + node.getName());
+ }
+ } else {
+ node.setObject(createPlugin(type, node));
+ }
+ }
+ /*
+ * Retrieve a static public 'method taking a Node parameter on a class specified by its name.
+ * @param classClass the class.
+ * @return the instantiate method or null if there is none by that
+ * description.
+ */
+ public static Object createPlugin(PluginType type, Node node)
+ {
+ Class clazz = type.getPluginClass();
+
+ if (Map.class.isAssignableFrom(clazz)) {
+ try {
+ Map map = (Map) clazz.newInstance();
+ for (Node child : node.getChildren()) {
+ map.put(child.getName(), child.getObject());
+ }
+ return map;
+ } catch (Exception ex) {
+
+ }
+ }
+
+ if (List.class.isAssignableFrom(clazz)) {
+ try {
+ List list = (List) clazz.newInstance();
+ for (Node child : node.getChildren()) {
+ list.add(child.getObject());
+ }
+ return list;
+ } catch (Exception ex) {
+
+ }
+ }
+
+ Method factoryMethod = null;
+
+ for (Method method : clazz.getMethods()) {
+ if (method.isAnnotationPresent(PluginFactory.class)) {
+ factoryMethod = method;
+ }
+ }
+ if (factoryMethod == null) {
+ return null;
+ }
+
+ try
+ {
+ int mod = factoryMethod.getModifiers();
+ if (!Modifier.isStatic(mod))
+ {
+ logger.error(factoryMethod.getName() + " method is not static on class " +
+ clazz.getName() + " for element " + node.getName());
+ return null;
+ }
+ logger.debug("Calling " + factoryMethod.getName() + " on class " + clazz.getName() + " for element " +
+ node.getName());
+ return factoryMethod.invoke(null, node);
+ }
+ catch (Exception e)
+ {
+ logger.error("Unable to invoke method " + factoryMethod.getName() + " in class " +
+ clazz.getName() + " for element " + node.getName(), e);
+ }
+ return null;
+ }
+
+ private void setParents() {
+ for (Map.Entry<String, LoggerConfig> entry : loggers.entrySet()) {
+ LoggerConfig logger = entry.getValue();
+ String name = entry.getKey();
+ if (!name.equals("")) {
+ int i = name.lastIndexOf(".");
+ if (i > 0) {
+ name = name.substring(0, i);
+ LoggerConfig parent = getLoggerConfig(name);
+ if (parent == null) {
+ parent = root;
+ }
+ logger.setParent(parent);
+ }
+ }
+ }
+ }
+
+ @Plugin(name="appenders", type="Core")
+ public static class AppendersPlugin {
+
+ @PluginFactory
+ public static ConcurrentMap<String, Appender> createAppenders(Node node) {
+ ConcurrentMap<String, Appender> map = new ConcurrentHashMap<String, Appender>();
+
+ for (Node child : node.getChildren()) {
+ Object obj = child.getObject();
+ if (obj != null && obj instanceof Appender) {
+ Appender appender = (Appender) obj;
+ map.put(appender.getName(), appender);
+ }
+ }
+
+ return map;
+ }
+ }
+
+
+ @Plugin(name="filters", type="Core")
+ public static class FiltersPlugin {
+
+ @PluginFactory
+ public static Filter[] createFilters(Node node) {
+ List<Filter> filters = new ArrayList<Filter>();
+
+ for (Node child : node.getChildren()) {
+ Object obj = child.getObject();
+ if (obj != null && obj instanceof Filter) {
+ filters.add((Filter) obj);
+ }
+ }
+
+ return filters.toArray(new Filter[filters.size()]);
+ }
+ }
+
+ @Plugin(name="loggers", type="Core")
+ public static class LoggersPlugin {
+
+ @PluginFactory
+ public static Loggers createLoggers(Node node) {
+ Loggers loggers = new Loggers();
+
+ for (Node child : node.getChildren()) {
+ Object obj = child.getObject();
+ if (obj != null && obj instanceof LoggerConfig) {
+ LoggerConfig logger = (LoggerConfig) obj;
+ if (logger != null) {
+ if (child.getName().equals("root")) {
+ loggers.root = logger;
+ }
+ loggers.map.put(logger.getName(), logger);
+ }
+ }
+ }
+
+ return loggers;
+ }
+ }
+
+ private static class Loggers {
+ ConcurrentMap<String, LoggerConfig> map = new ConcurrentHashMap<String, LoggerConfig>();
+ LoggerConfig root = null;
+ }
+}
\ No newline at end of file
Added: logging/log4j/branches/BRANCH_2_0_EXPERIMENTAL/rgoers/log4j2-core/src/main/java/org/apache/logging/log4j/core/config/Configuration.java
URL: http://svn.apache.org/viewvc/logging/log4j/branches/BRANCH_2_0_EXPERIMENTAL/rgoers/log4j2-core/src/main/java/org/apache/logging/log4j/core/config/Configuration.java?rev=943816&view=auto
==============================================================================
--- logging/log4j/branches/BRANCH_2_0_EXPERIMENTAL/rgoers/log4j2-core/src/main/java/org/apache/logging/log4j/core/config/Configuration.java (added)
+++ logging/log4j/branches/BRANCH_2_0_EXPERIMENTAL/rgoers/log4j2-core/src/main/java/org/apache/logging/log4j/core/config/Configuration.java Thu May 13 06:31:04 2010
@@ -0,0 +1,35 @@
+package org.apache.logging.log4j.core.config;
+
+import org.apache.logging.log4j.core.Appender;
+import org.apache.logging.log4j.core.Filter;
+
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+
+/**
+ *
+ */
+public interface Configuration {
+
+ LoggerConfig getLoggerConfig(String name);
+
+ Map<String, Appender> getAppenders();
+
+ Iterator<Filter> getFilters();
+
+ void addFilter(Filter filter);
+
+ void removeFilter(Filter filter);
+
+ boolean hasFilters();
+
+ Map<String, LoggerConfig> getLoggers();
+
+ void addLoggerAppender(String name, Appender appender);
+
+ void start();
+
+ void stop();
+
+}
Added: logging/log4j/branches/BRANCH_2_0_EXPERIMENTAL/rgoers/log4j2-core/src/main/java/org/apache/logging/log4j/core/config/ConfigurationException.java
URL: http://svn.apache.org/viewvc/logging/log4j/branches/BRANCH_2_0_EXPERIMENTAL/rgoers/log4j2-core/src/main/java/org/apache/logging/log4j/core/config/ConfigurationException.java?rev=943816&view=auto
==============================================================================
--- logging/log4j/branches/BRANCH_2_0_EXPERIMENTAL/rgoers/log4j2-core/src/main/java/org/apache/logging/log4j/core/config/ConfigurationException.java (added)
+++ logging/log4j/branches/BRANCH_2_0_EXPERIMENTAL/rgoers/log4j2-core/src/main/java/org/apache/logging/log4j/core/config/ConfigurationException.java Thu May 13 06:31:04 2010
@@ -0,0 +1,31 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache license, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the license for the specific language governing permissions and
+ * limitations under the license.
+ */
+package org.apache.logging.log4j.core.config;
+
+/**
+ *
+ */
+public class ConfigurationException extends RuntimeException {
+
+ public ConfigurationException(String msg) {
+ super(msg);
+ }
+
+ public ConfigurationException(String msg, Exception ex) {
+ super(msg, ex);
+ }
+}
Added: logging/log4j/branches/BRANCH_2_0_EXPERIMENTAL/rgoers/log4j2-core/src/main/java/org/apache/logging/log4j/core/config/ConfigurationFactory.java
URL: http://svn.apache.org/viewvc/logging/log4j/branches/BRANCH_2_0_EXPERIMENTAL/rgoers/log4j2-core/src/main/java/org/apache/logging/log4j/core/config/ConfigurationFactory.java?rev=943816&view=auto
==============================================================================
--- logging/log4j/branches/BRANCH_2_0_EXPERIMENTAL/rgoers/log4j2-core/src/main/java/org/apache/logging/log4j/core/config/ConfigurationFactory.java (added)
+++ logging/log4j/branches/BRANCH_2_0_EXPERIMENTAL/rgoers/log4j2-core/src/main/java/org/apache/logging/log4j/core/config/ConfigurationFactory.java Thu May 13 06:31:04 2010
@@ -0,0 +1,127 @@
+package org.apache.logging.log4j.core.config;
+
+import org.apache.logging.log4j.Logger;
+import org.apache.logging.log4j.core.config.plugins.PluginManager;
+import org.apache.logging.log4j.core.config.plugins.PluginType;
+import org.apache.logging.log4j.internal.StatusLogger;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.TreeSet;
+
+/**
+ * ConfigurationFactory allows the configuration implementation to be dynamically chosen in 1
+ * of 3 ways:
+ * 1. A system property named "log4j.configurationFactory" can be set with the name of the
+ * ConfigurationFactory to be used.
+ * 2. setConfigurationFactory can be called with the instance of the ConfigurationFactory to
+ * be used. This must be called before any other calls to Log4j.
+ * 3. A ConfigurationFactory implementation can be added to the classpath and configured as a
+ * plugin. The Order annotation should be used to configure the factory to be the first one
+ * inspected. See XMLConfigurationFactory for an example.
+ *
+ * If the ConfigurationFactory that was added returns null on a call to getConfiguration the
+ * any other ConfigurationFactories found as plugins will be called in their respective order.
+ * DefaultConfiguration is always called last if no configuration has been returned.
+ */
+public abstract class ConfigurationFactory {
+
+ public static final String CONFIGURATION_FACTORY_PROPERTY = "log4j.configurationFactory";
+
+ private static List<ConfigurationFactory> factories = new ArrayList<ConfigurationFactory>();
+
+ private static Logger logger = StatusLogger.getLogger();
+
+ public static ConfigurationFactory getInstance() {
+ String factoryClass = System.getProperty(CONFIGURATION_FACTORY_PROPERTY);
+ if (factoryClass != null) {
+ addFactory(factoryClass);
+ }
+ PluginManager manager = new PluginManager("ConfigurationFactory");
+ manager.collectPlugins();
+ Map<String, PluginType> plugins = manager.getPlugins();
+ Set<WeightedFactory> ordered = new TreeSet<WeightedFactory>();
+ for (PluginType type : plugins.values()) {
+ try {
+ Class<ConfigurationFactory> clazz = type.getPluginClass();
+ Order o = clazz.getAnnotation(Order.class);
+ Integer weight = o.value();
+ if (o != null) {
+ ordered.add(new WeightedFactory(weight, clazz));
+ }
+ } catch (Exception ex) {
+
+ }
+ }
+ for (WeightedFactory wf : ordered) {
+ addFactory(wf.factoryClass);
+ }
+ return new Factory();
+ }
+
+ private static void addFactory(String factoryClass) {
+ try {
+ Class clazz = Class.forName(factoryClass);
+ addFactory(clazz);
+ } catch (ClassNotFoundException ex) {
+ logger.error("Unable to load class " + factoryClass, ex);
+ } catch (Exception ex) {
+ logger.error("Unable to load class " + factoryClass, ex);
+ }
+ }
+
+ private static void addFactory(Class factoryClass) {
+ try {
+ factories.add((ConfigurationFactory) factoryClass.newInstance());
+ } catch (Exception ex) {
+ logger.error("Unable to create instance of " + factoryClass.getName(), ex);
+ }
+ }
+
+ public static void setConfigurationFactory(ConfigurationFactory factory) {
+ factories.add(0, factory);
+ }
+
+ public static void removeConfigurationFactory(ConfigurationFactory factory) {
+ factories.remove(factory);
+ }
+
+ public abstract Configuration getConfiguration();
+
+ private static class WeightedFactory implements Comparable<WeightedFactory> {
+ private int weight;
+ private Class<ConfigurationFactory> factoryClass;
+
+ public WeightedFactory(int weight, Class<ConfigurationFactory> clazz) {
+ this.weight = weight;
+ this.factoryClass = clazz;
+ }
+
+ public int compareTo(WeightedFactory wf) {
+ int w = wf.weight;
+ if (weight == w) {
+ return 0;
+ } else if (weight > w) {
+ return -1;
+ } else {
+ return 1;
+ }
+ }
+ }
+
+ private static class Factory extends ConfigurationFactory {
+
+ public Configuration getConfiguration() {
+
+ for (ConfigurationFactory factory : factories) {
+ Configuration c = factory.getConfiguration();
+ if (c != null) {
+ return c;
+ }
+ }
+ return new DefaultConfiguration();
+ }
+ }
+}
Added: logging/log4j/branches/BRANCH_2_0_EXPERIMENTAL/rgoers/log4j2-core/src/main/java/org/apache/logging/log4j/core/config/DefaultConfiguration.java
URL: http://svn.apache.org/viewvc/logging/log4j/branches/BRANCH_2_0_EXPERIMENTAL/rgoers/log4j2-core/src/main/java/org/apache/logging/log4j/core/config/DefaultConfiguration.java?rev=943816&view=auto
==============================================================================
--- logging/log4j/branches/BRANCH_2_0_EXPERIMENTAL/rgoers/log4j2-core/src/main/java/org/apache/logging/log4j/core/config/DefaultConfiguration.java (added)
+++ logging/log4j/branches/BRANCH_2_0_EXPERIMENTAL/rgoers/log4j2-core/src/main/java/org/apache/logging/log4j/core/config/DefaultConfiguration.java Thu May 13 06:31:04 2010
@@ -0,0 +1,59 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache license, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the license for the specific language governing permissions and
+ * limitations under the license.
+ */
+package org.apache.logging.log4j.core.config;
+
+import org.apache.logging.log4j.Level;
+import org.apache.logging.log4j.core.Appender;
+import org.apache.logging.log4j.core.Layout;
+import org.apache.logging.log4j.core.LogEvent;
+import org.apache.logging.log4j.core.appender.ConsoleAppender;
+
+/**
+ *
+ */
+public class DefaultConfiguration extends BaseConfiguration {
+
+ private static final String CONSOLE = "CONSOLE";;
+ private static final String DEFAULT_LEVEL = "org.apache.logging.log4j.level";
+ private static final String EMPTY_STRING = "";
+
+ public DefaultConfiguration() {
+
+ Appender appender = new ConsoleAppender("Console", new BasicLayout());
+ addAppender(appender);
+ LoggerConfig root = getRootLogger();
+ root.addAppender(appender);
+ String l = System.getProperty(DEFAULT_LEVEL);
+ Level level = (l != null && Level.valueOf(l) != null) ? Level.valueOf(l) : Level.ERROR;
+ root.setLevel(level);
+ }
+
+ public class BasicLayout implements Layout {
+ public byte[] format(LogEvent event) {
+ String result = event.getMessage().getFormattedMessage() + "\n";
+ return result.getBytes();
+ }
+
+ public byte[] getHeader() {
+ return EMPTY_STRING.getBytes();
+ }
+
+ public byte[] getFooter() {
+ return EMPTY_STRING.getBytes();
+ }
+ }
+}
Added: logging/log4j/branches/BRANCH_2_0_EXPERIMENTAL/rgoers/log4j2-core/src/main/java/org/apache/logging/log4j/core/config/LoggerConfig.java
URL: http://svn.apache.org/viewvc/logging/log4j/branches/BRANCH_2_0_EXPERIMENTAL/rgoers/log4j2-core/src/main/java/org/apache/logging/log4j/core/config/LoggerConfig.java?rev=943816&view=auto
==============================================================================
--- logging/log4j/branches/BRANCH_2_0_EXPERIMENTAL/rgoers/log4j2-core/src/main/java/org/apache/logging/log4j/core/config/LoggerConfig.java (added)
+++ logging/log4j/branches/BRANCH_2_0_EXPERIMENTAL/rgoers/log4j2-core/src/main/java/org/apache/logging/log4j/core/config/LoggerConfig.java Thu May 13 06:31:04 2010
@@ -0,0 +1,264 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache license, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the license for the specific language governing permissions and
+ * limitations under the license.
+ */
+package org.apache.logging.log4j.core.config;
+
+import org.apache.logging.log4j.Level;
+import org.apache.logging.log4j.Logger;
+import org.apache.logging.log4j.Marker;
+import org.apache.logging.log4j.core.Appender;
+import org.apache.logging.log4j.core.Filter;
+import org.apache.logging.log4j.core.Log4jLogEvent;
+import org.apache.logging.log4j.core.LogEvent;
+import org.apache.logging.log4j.core.LogEventFactory;
+import org.apache.logging.log4j.core.config.plugins.Plugin;
+import org.apache.logging.log4j.core.config.plugins.PluginFactory;
+import org.apache.logging.log4j.internal.StatusLogger;
+import org.apache.logging.log4j.message.Message;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.CopyOnWriteArrayList;
+
+/**
+ *
+ */
+@Plugin(name="logger",type="Core")
+public class LoggerConfig implements LogEventFactory {
+
+ private List<String> appenderRefs = new ArrayList<String>();
+ private Map<String, AppenderControl> appenders = new ConcurrentHashMap<String, AppenderControl>();
+
+ private List<Filter> filters = new CopyOnWriteArrayList<Filter>();
+ private boolean hasFilters = false;
+
+ private final String name;
+
+ private LogEventFactory logEventFactory;
+
+ private Level level;
+
+ private boolean additive = true;
+
+ private LoggerConfig parent;
+
+ private static Logger logger = StatusLogger.getLogger();
+
+ public LoggerConfig() {
+ this.logEventFactory = this;
+ this.level = Level.ERROR;
+ this.name = "";
+ }
+
+ public LoggerConfig(String name, Level level, boolean additive) {
+ this.logEventFactory = this;
+ this.name = name;
+ this.level = level;
+ this.additive = additive;
+ }
+
+ protected LoggerConfig(String name, List<String> appenders, Filter[] filters, Level level,
+ boolean additive) {
+ this.logEventFactory = this;
+ this.name = name;
+ this.appenderRefs = appenders;
+ if (filters != null && filters.length > 0) {
+ this.filters = new CopyOnWriteArrayList<Filter>(filters);
+ hasFilters = true;
+ }
+ this.level = level;
+ this.additive = additive;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setParent(LoggerConfig parent) {
+ this.parent = parent;
+ }
+
+ public void addAppender(Appender appender) {
+ appenders.put(appender.getName(), new AppenderControl(appender));
+ }
+
+ public void removeAppender(String name) {
+ appenders.remove(name);
+ }
+
+ public Map<String, Appender> getAppenders() {
+ Map<String, Appender> map = new HashMap<String, Appender>();
+ for (Map.Entry<String, AppenderControl> entry : appenders.entrySet()) {
+ map.put(entry.getKey(), entry.getValue().getAppender());
+ }
+ return map;
+ }
+
+ protected void clearAppenders() {
+ appenders.clear();
+ }
+
+ public List<String> getAppenderRefs() {
+ return appenderRefs;
+ }
+
+ public void setLevel(Level level) {
+ this.level = level;
+ }
+
+ public Level getLevel() {
+ return level;
+ }
+
+ public LogEventFactory getLogEventFactory() {
+ return logEventFactory;
+ }
+
+ public void setLogEventFactory(LogEventFactory logEventFactory) {
+ this.logEventFactory = logEventFactory;
+ }
+
+ public void addFilter(Filter filter) {
+ filters.add(filter);
+ hasFilters = filters.size() > 0;
+ }
+
+ public void removeFilter(Filter filter) {
+ filters.remove(filter);
+ hasFilters = filters.size() > 0;
+ }
+
+ public List<Filter> getFilters() {
+ return Collections.unmodifiableList(filters);
+ }
+
+ public boolean isAdditive() {
+ return additive;
+ }
+
+ public void log(String loggerName, Marker marker, String fqcn, Level level, Message data, Throwable t) {
+ LogEvent event = logEventFactory.createEvent(loggerName, marker, fqcn, level, data, t);
+ log(event);
+ }
+
+ private void log(LogEvent event) {
+ if (hasFilters) {
+ for (Filter filter : filters) {
+ if (filter.filter(event) == Filter.Result.DENY) {
+ return;
+ }
+ }
+ }
+
+ callAppenders(event);
+
+ if (additive && parent != null) {
+ parent.log(event);
+ }
+ }
+
+ private void callAppenders(LogEvent event) {
+ for (AppenderControl control: appenders.values()) {
+ control.callAppender(event);
+ }
+ }
+
+ public LogEvent createEvent(String loggerName, Marker marker, String fqcn, Level level, Message data,
+ Throwable t) {
+ return new Log4jLogEvent(loggerName, marker, fqcn, level, data, t);
+ }
+
+ @PluginFactory
+ public static LoggerConfig createLogger(Node node) {
+ Map<String, String> map = node.getAttributes();
+ List<String> appenderRefs = new ArrayList<String>();
+ Filter[] filters = null;
+ boolean additive = true;
+ Level level = Level.ERROR;
+ String name = null;
+
+ for (Map.Entry<String, String> entry : map.entrySet()) {
+ String key = entry.getKey();
+ if (key.equalsIgnoreCase("additivity")) {
+ additive = Boolean.parseBoolean(entry.getValue());
+ }
+ if (key.equalsIgnoreCase("level")) {
+ Level l = Level.valueOf(entry.getValue().toUpperCase());
+ if (l != null) {
+ level = l;
+ }
+ }
+ if (key.equalsIgnoreCase("name")) {
+ name = entry.getValue();
+ }
+ }
+
+ if (node.getName().equals("root")) {
+ name = "";
+ }
+
+ if (name == null) {
+ logger.error("Loggers cannot be configured without a name");
+ return null;
+ }
+
+ for (Node child : node.getChildren()) {
+ Object obj = child.getObject();
+ if (obj != null) {
+ if (obj instanceof String) {
+ appenderRefs.add((String) obj);
+ } else if (obj instanceof Filter[]) {
+ filters = (Filter[]) obj;
+ }
+ }
+ }
+
+ return new LoggerConfig(name, appenderRefs, filters, level, additive);
+ }
+ /*
+ @Plugin("appender-refs")
+ public static class AppenderRefs {
+
+ @PluginFactory
+ public static String[] createAppenderRefs(Node node) {
+ String[] refs = new String[node.getChildren().size()];
+ int i = 0;
+ for (Node child : node.getChildren()) {
+ refs[i++] = (String) child.getObject();
+ }
+ return refs;
+ }
+ } */
+
+ @Plugin(name="appender-ref",type="Core")
+ public static class AppenderRef {
+
+ @PluginFactory
+ public static String createAppenderRef(Node node) {
+ Map<String, String> attrs = node.getAttributes();
+ for (Map.Entry<String, String> attr : attrs.entrySet()) {
+ if (attr.getKey().equalsIgnoreCase("ref")) {
+ return attr.getValue();
+ }
+ }
+ return null;
+ }
+ }
+}
Added: logging/log4j/branches/BRANCH_2_0_EXPERIMENTAL/rgoers/log4j2-core/src/main/java/org/apache/logging/log4j/core/config/Node.java
URL: http://svn.apache.org/viewvc/logging/log4j/branches/BRANCH_2_0_EXPERIMENTAL/rgoers/log4j2-core/src/main/java/org/apache/logging/log4j/core/config/Node.java?rev=943816&view=auto
==============================================================================
--- logging/log4j/branches/BRANCH_2_0_EXPERIMENTAL/rgoers/log4j2-core/src/main/java/org/apache/logging/log4j/core/config/Node.java (added)
+++ logging/log4j/branches/BRANCH_2_0_EXPERIMENTAL/rgoers/log4j2-core/src/main/java/org/apache/logging/log4j/core/config/Node.java Thu May 13 06:31:04 2010
@@ -0,0 +1,100 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache license, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the license for the specific language governing permissions and
+ * limitations under the license.
+ */
+package org.apache.logging.log4j.core.config;
+
+import org.apache.logging.log4j.core.config.plugins.PluginType;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ *
+ */
+
+public class Node {
+
+ private Node parent;
+ private String name;
+ private String value;
+ private PluginType type;
+ private Map<String, String> attributes = new HashMap<String, String>();
+ private List<Node> children = new ArrayList<Node>();
+ private Object object;
+ private Configuration config;
+
+
+ /**
+ * Creates a new instance of <code>Node</code> and initializes it
+ * with a name and the corresponding XML element.
+ *
+ * @param parent the node's parent.
+ * @param name the node's name.
+ * @param type The Plugin Type associated with the node.
+ */
+ public Node(Node parent, String name, PluginType type) {
+ this.parent = parent;
+ this.name = name;
+ this.type = type;
+ this.config = parent.config;
+ }
+
+ public Node(Configuration config) {
+ this.config = config;
+ }
+
+ public Map<String, String> getAttributes() {
+ return attributes;
+ }
+
+ public List<Node> getChildren() {
+ return children;
+ }
+
+ public boolean hasChildren() {
+ return children.size() > 0;
+ }
+
+ public String getValue() {
+ return value;
+ }
+
+ public void setValue(String value) {
+ this.value = value;
+ }
+
+ public Node getParent() {
+ return parent;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public boolean isRoot() {
+ return parent == null;
+ }
+
+ public void setObject(Object obj) {
+ object = obj;
+ }
+
+ public Object getObject() {
+ return object;
+ }
+}
Added: logging/log4j/branches/BRANCH_2_0_EXPERIMENTAL/rgoers/log4j2-core/src/main/java/org/apache/logging/log4j/core/config/Order.java
URL: http://svn.apache.org/viewvc/logging/log4j/branches/BRANCH_2_0_EXPERIMENTAL/rgoers/log4j2-core/src/main/java/org/apache/logging/log4j/core/config/Order.java?rev=943816&view=auto
==============================================================================
--- logging/log4j/branches/BRANCH_2_0_EXPERIMENTAL/rgoers/log4j2-core/src/main/java/org/apache/logging/log4j/core/config/Order.java (added)
+++ logging/log4j/branches/BRANCH_2_0_EXPERIMENTAL/rgoers/log4j2-core/src/main/java/org/apache/logging/log4j/core/config/Order.java Thu May 13 06:31:04 2010
@@ -0,0 +1,15 @@
+package org.apache.logging.log4j.core.config;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+/**
+ *
+ */
+@Retention(RetentionPolicy.RUNTIME)
+@Target(ElementType.TYPE)
+public @interface Order {
+ public int value();
+}
Added: logging/log4j/branches/BRANCH_2_0_EXPERIMENTAL/rgoers/log4j2-core/src/main/java/org/apache/logging/log4j/core/config/XMLConfiguration.java
URL: http://svn.apache.org/viewvc/logging/log4j/branches/BRANCH_2_0_EXPERIMENTAL/rgoers/log4j2-core/src/main/java/org/apache/logging/log4j/core/config/XMLConfiguration.java?rev=943816&view=auto
==============================================================================
--- logging/log4j/branches/BRANCH_2_0_EXPERIMENTAL/rgoers/log4j2-core/src/main/java/org/apache/logging/log4j/core/config/XMLConfiguration.java (added)
+++ logging/log4j/branches/BRANCH_2_0_EXPERIMENTAL/rgoers/log4j2-core/src/main/java/org/apache/logging/log4j/core/config/XMLConfiguration.java Thu May 13 06:31:04 2010
@@ -0,0 +1,213 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache license, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the license for the specific language governing permissions and
+ * limitations under the license.
+ */
+package org.apache.logging.log4j.core.config;
+
+import org.apache.logging.log4j.Level;
+import org.apache.logging.log4j.core.Filter;
+import org.apache.logging.log4j.core.config.plugins.Plugin;
+import org.apache.logging.log4j.core.config.plugins.PluginFactory;
+import org.apache.logging.log4j.core.config.plugins.PluginManager;
+import org.apache.logging.log4j.core.config.plugins.PluginType;
+import org.apache.logging.log4j.core.config.plugins.ResolverUtil;
+import org.apache.logging.log4j.internal.StatusConsoleListener;
+import org.apache.logging.log4j.internal.StatusLogger;
+import org.w3c.dom.Attr;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.w3c.dom.NamedNodeMap;
+import org.w3c.dom.NodeList;
+import org.w3c.dom.Text;
+import org.xml.sax.InputSource;
+import org.xml.sax.SAXException;
+
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+import javax.xml.parsers.ParserConfigurationException;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Creates a Node hierarchy from an XML file.
+ */
+public class XMLConfiguration extends BaseConfiguration {
+
+ private List<Status> status = new ArrayList<Status>();
+
+ private Element rootElement = null;
+
+ private static final String[] verboseClasses = new String[] { ResolverUtil.class.getName() };
+
+ public XMLConfiguration(InputSource source) {
+ try {
+ DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
+ Document document = builder.parse(source);
+ rootElement = document.getDocumentElement();
+ Map<String, String> attrs = processAttributes(rootNode, rootElement);
+ boolean debug = false;
+ boolean verbose = false;
+
+ for (Map.Entry<String, String> entry : attrs.entrySet()) {
+ if ("debug".equalsIgnoreCase(entry.getKey())) {
+ debug = Boolean.parseBoolean(entry.getValue());
+ } else if ("verbose".equalsIgnoreCase(entry.getKey())) {
+ verbose = Boolean.parseBoolean(entry.getValue());
+ } else if ("packages".equalsIgnoreCase(entry.getKey())) {
+ String[] packages = entry.getValue().split(",");
+ for (String p : packages) {
+ PluginManager.addPackage(p);
+ }
+ } else if ("name".equalsIgnoreCase(entry.getKey())) {
+ setName(entry.getValue());
+ }
+ }
+ if (debug) {
+ StatusConsoleListener listener = new StatusConsoleListener(Level.DEBUG);
+ if (!verbose) {
+ listener.setFilters(verboseClasses);
+ }
+ ((StatusLogger) logger).registerListener(listener);
+ }
+
+ } catch (SAXException domEx) {
+ logger.error("Error parsing " + source.getSystemId(), domEx);
+ } catch (IOException ioe) {
+ logger.error("Error parsing " + source.getSystemId(), ioe);
+ } catch (ParserConfigurationException pex) {
+ logger.error("Error parsing " + source.getSystemId(), pex);
+ }
+ }
+
+ public void setup() {
+ constructHierarchy(rootNode, rootElement);
+ if (status.size() > 0) {
+ for (Status s : status) {
+ logger.error("Error processing element " + s.name + ": " + s.errorType);
+ }
+ return;
+ }
+ rootElement = null;
+ }
+
+ private void constructHierarchy(Node node, Element element) {
+ processAttributes(node, element);
+ StringBuffer buffer = new StringBuffer();
+ NodeList list = element.getChildNodes();
+ List<Node> children = node.getChildren();
+ for (int i = 0; i < list.getLength(); i++) {
+ org.w3c.dom.Node w3cNode = list.item(i);
+ if (w3cNode instanceof Element) {
+ Element child = (Element) w3cNode;
+ String name = child.getTagName();
+ PluginType type = getPluginManager().getPluginType(name);
+ Node childNode = new Node(node, name, type);
+ constructHierarchy(childNode, child);
+ if (type == null) {
+ String value = childNode.getValue();
+ if (!childNode.hasChildren() && value != null) {
+ node.getAttributes().put(name, value);
+ } else {
+ status.add(new Status(name, element, ErrorType.CLASS_NOT_FOUND));
+ }
+ } else {
+ children.add(childNode);
+ }
+ } else if (w3cNode instanceof Text) {
+ Text data = (Text) w3cNode;
+ buffer.append(data.getData());
+ }
+ }
+
+ String text = buffer.toString().trim();
+ if (text.length() > 0 || (!node.hasChildren() && !node.isRoot())) {
+ node.setValue(text);
+ }
+ }
+
+ private Map<String, String> processAttributes(Node node, Element element) {
+ NamedNodeMap attrs = element.getAttributes();
+ Map<String, String> attributes = node.getAttributes();
+
+ for (int i = 0; i < attrs.getLength(); ++i) {
+ org.w3c.dom.Node w3cNode = attrs.item(i);
+ if (w3cNode instanceof Attr) {
+ Attr attr = (Attr) w3cNode;
+ attributes.put(attr.getName(), attr.getValue());
+ }
+ }
+ return attributes;
+ }
+
+ private enum ErrorType {
+ CLASS_NOT_FOUND
+ }
+
+ private class Status {
+ Element element;
+ String name;
+ ErrorType errorType;
+
+ public Status(String name, Element element, ErrorType errorType) {
+ this.name = name;
+ this.element = element;
+ this.errorType = errorType;
+ }
+ }
+
+ @Plugin(name = "root", type = "Core")
+ public static class RootLogger extends LoggerConfig {
+
+ @PluginFactory
+ public static LoggerConfig createLogger(Node node) {
+ Map<String, String> map = node.getAttributes();
+ List<String> appenderRefs = new ArrayList<String>();
+ Filter[] filters = null;
+ boolean additive = false;
+ Level level = Level.ERROR;
+ String name = "";
+
+ for (Map.Entry<String, String> entry : map.entrySet()) {
+ String key = entry.getKey();
+ if (key.equalsIgnoreCase("level")) {
+ Level l = Level.valueOf(entry.getValue().toUpperCase());
+ if (l != null) {
+ level = l;
+ }
+ } else {
+ logger.warn("Unsupported key " + key + " ignored on root logger");
+ }
+
+ }
+
+ for (Node child : node.getChildren()) {
+ Object obj = child.getObject();
+ if (obj != null) {
+ if (obj instanceof String) {
+ appenderRefs.add((String) obj);
+ } else if (obj instanceof Filter[]) {
+ filters = (Filter[]) obj;
+ }
+ }
+ }
+
+ return new LoggerConfig(name, appenderRefs, filters, level, additive);
+ }
+ }
+
+
+}
Added: logging/log4j/branches/BRANCH_2_0_EXPERIMENTAL/rgoers/log4j2-core/src/main/java/org/apache/logging/log4j/core/config/XMLConfigurationFactory.java
URL: http://svn.apache.org/viewvc/logging/log4j/branches/BRANCH_2_0_EXPERIMENTAL/rgoers/log4j2-core/src/main/java/org/apache/logging/log4j/core/config/XMLConfigurationFactory.java?rev=943816&view=auto
==============================================================================
--- logging/log4j/branches/BRANCH_2_0_EXPERIMENTAL/rgoers/log4j2-core/src/main/java/org/apache/logging/log4j/core/config/XMLConfigurationFactory.java (added)
+++ logging/log4j/branches/BRANCH_2_0_EXPERIMENTAL/rgoers/log4j2-core/src/main/java/org/apache/logging/log4j/core/config/XMLConfigurationFactory.java Thu May 13 06:31:04 2010
@@ -0,0 +1,90 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache license, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the license for the specific language governing permissions and
+ * limitations under the license.
+ */
+package org.apache.logging.log4j.core.config;
+
+import org.apache.logging.log4j.core.config.plugins.Plugin;
+import org.xml.sax.InputSource;
+
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.InputStream;
+import java.net.URL;
+
+/**
+ *
+ */
+@Plugin(name="XMLConfigurationFactory", type="ConfigurationFactory")
+@Order(1)
+public class XMLConfigurationFactory extends ConfigurationFactory {
+
+ public static final String CONFIGURATION_FILE_PROPERTY = "log4j.configurationFile";
+
+ public static final String DEFAULT_CONFIG_FILE = "log4j2.xml";
+
+ public static final String TEST_CONFIG_FILE = "log4j2-test.xml";
+
+ public Configuration getConfiguration() {
+ ClassLoader loader = this.getClass().getClassLoader();
+ InputSource source = getInputFromSystemProperty(loader);
+ if (source == null) {
+ source = getInputFromResource(TEST_CONFIG_FILE, loader);
+ if (source == null) {
+ source = getInputFromResource(DEFAULT_CONFIG_FILE, loader);
+ }
+ if (source == null) {
+ return null;
+ }
+ }
+ return new XMLConfiguration(source);
+ }
+
+ private InputSource getInputFromSystemProperty(ClassLoader loader) {
+ String configFile = System.getProperty(CONFIGURATION_FILE_PROPERTY);
+ if (configFile == null) {
+ return null;
+ }
+ InputSource source;
+ try {
+ URL url = new URL(configFile);
+ source = new InputSource(url.openStream());
+ source.setSystemId(configFile);
+ return source;
+ } catch (Exception ex) {
+ source = getInputFromResource(configFile, loader);
+ if (source == null) {
+ try {
+ InputStream is = new FileInputStream(configFile);
+ source = new InputSource(is);
+ source.setSystemId(configFile);
+ } catch (FileNotFoundException fnfe) {
+ // Ignore the exception
+ }
+ }
+ }
+ return source;
+ }
+
+ private InputSource getInputFromResource(String resource, ClassLoader loader) {
+ InputStream is = loader.getResourceAsStream(resource);
+ if (is == null) {
+ return null;
+ }
+ InputSource source = new InputSource(is);
+ source.setSystemId(resource);
+ return source;
+ }
+}
Added: logging/log4j/branches/BRANCH_2_0_EXPERIMENTAL/rgoers/log4j2-core/src/main/java/org/apache/logging/log4j/core/config/plugins/Plugin.java
URL: http://svn.apache.org/viewvc/logging/log4j/branches/BRANCH_2_0_EXPERIMENTAL/rgoers/log4j2-core/src/main/java/org/apache/logging/log4j/core/config/plugins/Plugin.java?rev=943816&view=auto
==============================================================================
--- logging/log4j/branches/BRANCH_2_0_EXPERIMENTAL/rgoers/log4j2-core/src/main/java/org/apache/logging/log4j/core/config/plugins/Plugin.java (added)
+++ logging/log4j/branches/BRANCH_2_0_EXPERIMENTAL/rgoers/log4j2-core/src/main/java/org/apache/logging/log4j/core/config/plugins/Plugin.java Thu May 13 06:31:04 2010
@@ -0,0 +1,17 @@
+package org.apache.logging.log4j.core.config.plugins;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+/**
+ *
+ */
+@Retention(RetentionPolicy.RUNTIME)
+@Target(ElementType.TYPE)
+public @interface Plugin {
+
+ public String name();
+ public String type();
+}
Added: logging/log4j/branches/BRANCH_2_0_EXPERIMENTAL/rgoers/log4j2-core/src/main/java/org/apache/logging/log4j/core/config/plugins/PluginFactory.java
URL: http://svn.apache.org/viewvc/logging/log4j/branches/BRANCH_2_0_EXPERIMENTAL/rgoers/log4j2-core/src/main/java/org/apache/logging/log4j/core/config/plugins/PluginFactory.java?rev=943816&view=auto
==============================================================================
--- logging/log4j/branches/BRANCH_2_0_EXPERIMENTAL/rgoers/log4j2-core/src/main/java/org/apache/logging/log4j/core/config/plugins/PluginFactory.java (added)
+++ logging/log4j/branches/BRANCH_2_0_EXPERIMENTAL/rgoers/log4j2-core/src/main/java/org/apache/logging/log4j/core/config/plugins/PluginFactory.java Thu May 13 06:31:04 2010
@@ -0,0 +1,15 @@
+package org.apache.logging.log4j.core.config.plugins;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+/**
+ *
+ */
+@Retention(RetentionPolicy.RUNTIME)
+@Target(ElementType.METHOD)
+public @interface PluginFactory {
+
+}
Added: logging/log4j/branches/BRANCH_2_0_EXPERIMENTAL/rgoers/log4j2-core/src/main/java/org/apache/logging/log4j/core/config/plugins/PluginManager.java
URL: http://svn.apache.org/viewvc/logging/log4j/branches/BRANCH_2_0_EXPERIMENTAL/rgoers/log4j2-core/src/main/java/org/apache/logging/log4j/core/config/plugins/PluginManager.java?rev=943816&view=auto
==============================================================================
--- logging/log4j/branches/BRANCH_2_0_EXPERIMENTAL/rgoers/log4j2-core/src/main/java/org/apache/logging/log4j/core/config/plugins/PluginManager.java (added)
+++ logging/log4j/branches/BRANCH_2_0_EXPERIMENTAL/rgoers/log4j2-core/src/main/java/org/apache/logging/log4j/core/config/plugins/PluginManager.java Thu May 13 06:31:04 2010
@@ -0,0 +1,94 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache license, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the license for the specific language governing permissions and
+ * limitations under the license.
+ */
+package org.apache.logging.log4j.core.config.plugins;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.CopyOnWriteArrayList;
+
+/**
+ *
+ */
+public class PluginManager {
+
+
+ private Map<String, PluginType> plugins = new HashMap<String, PluginType>();
+
+ private static CopyOnWriteArrayList<String> packages = new CopyOnWriteArrayList<String>();
+
+ private final String type;
+
+ static {
+ packages.add("org.apache.logging.log4j");
+ }
+
+ public PluginManager(String type) {
+ this.type = type;
+ }
+
+ public static void addPackage(String p) {
+ packages.addIfAbsent(p);
+ }
+
+ public PluginType getPluginType(String name) {
+ return plugins.get(name);
+ }
+
+ public Map<String, PluginType> getPlugins() {
+ return plugins;
+ }
+
+
+ public void collectPlugins() {
+ ResolverUtil<?> r = new ResolverUtil();
+ ResolverUtil.Test test = new PluginTest(type);
+ for (String pkg : packages) {
+ r.findInPackage(test, pkg);
+ }
+ for (Class<?> item : r.getClasses())
+ {
+ Plugin p = item.getAnnotation(Plugin.class);
+ plugins.put(p.name(), new PluginType(item));
+ }
+ }
+
+
+ /**
+ * A Test that checks to see if each class is annotated with a specific annotation. If it
+ * is, then the test returns true, otherwise false.
+ */
+ public static class PluginTest extends ResolverUtil.ClassTest {
+ private String type;
+
+ /** Constructs an AnnotatedWith test for the specified annotation type. */
+ public PluginTest(String type) {
+ this.type = type;
+ }
+
+ /** Returns true if the type is annotated with the class provided to the constructor. */
+ public boolean matches(Class type) {
+ return type != null && type.isAnnotationPresent(Plugin.class) &&
+ this.type.equals(((Plugin)type.getAnnotation(Plugin.class)).type());
+ }
+
+ @Override public String toString() {
+ return "annotated with @" + Plugin.class.getSimpleName();
+ }
+ }
+}
Added: logging/log4j/branches/BRANCH_2_0_EXPERIMENTAL/rgoers/log4j2-core/src/main/java/org/apache/logging/log4j/core/config/plugins/PluginType.java
URL: http://svn.apache.org/viewvc/logging/log4j/branches/BRANCH_2_0_EXPERIMENTAL/rgoers/log4j2-core/src/main/java/org/apache/logging/log4j/core/config/plugins/PluginType.java?rev=943816&view=auto
==============================================================================
--- logging/log4j/branches/BRANCH_2_0_EXPERIMENTAL/rgoers/log4j2-core/src/main/java/org/apache/logging/log4j/core/config/plugins/PluginType.java (added)
+++ logging/log4j/branches/BRANCH_2_0_EXPERIMENTAL/rgoers/log4j2-core/src/main/java/org/apache/logging/log4j/core/config/plugins/PluginType.java Thu May 13 06:31:04 2010
@@ -0,0 +1,35 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache license, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the license for the specific language governing permissions and
+ * limitations under the license.
+ */
+package org.apache.logging.log4j.core.config.plugins;
+
+
+/**
+ *
+ */
+public class PluginType {
+
+ private Class pluginClass;
+
+ public PluginType(Class clazz) {
+ this.pluginClass = clazz;
+ }
+
+ public Class getPluginClass() {
+ return this.pluginClass;
+ }
+
+}
Added: logging/log4j/branches/BRANCH_2_0_EXPERIMENTAL/rgoers/log4j2-core/src/main/java/org/apache/logging/log4j/core/config/plugins/ResolverUtil.java
URL: http://svn.apache.org/viewvc/logging/log4j/branches/BRANCH_2_0_EXPERIMENTAL/rgoers/log4j2-core/src/main/java/org/apache/logging/log4j/core/config/plugins/ResolverUtil.java?rev=943816&view=auto
==============================================================================
--- logging/log4j/branches/BRANCH_2_0_EXPERIMENTAL/rgoers/log4j2-core/src/main/java/org/apache/logging/log4j/core/config/plugins/ResolverUtil.java (added)
+++ logging/log4j/branches/BRANCH_2_0_EXPERIMENTAL/rgoers/log4j2-core/src/main/java/org/apache/logging/log4j/core/config/plugins/ResolverUtil.java Thu May 13 06:31:04 2010
@@ -0,0 +1,458 @@
+/* Copyright 2005-2006 Tim Fennell
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.logging.log4j.core.config.plugins;
+
+import org.apache.logging.log4j.Logger;
+import org.apache.logging.log4j.internal.StatusLogger;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.lang.annotation.Annotation;
+import java.net.URL;
+import java.net.URLDecoder;
+import java.util.Enumeration;
+import java.util.HashSet;
+import java.util.Set;
+import java.util.jar.JarEntry;
+import java.util.jar.JarInputStream;
+
+/**
+ * <p>ResolverUtil is used to locate classes that are available in the/a class path and meet
+ * arbitrary conditions. The two most common conditions are that a class implements/extends
+ * another class, or that is it annotated with a specific annotation. However, through the use
+ * of the {@link Test} class it is possible to search using arbitrary conditions.</p>
+ *
+ * <p>A ClassLoader is used to locate all locations (directories and jar files) in the class
+ * path that contain classes within certain packages, and then to load those classes and
+ * check them. By default the ClassLoader returned by
+ * {@code Thread.currentThread().getContextClassLoader()} is used, but this can be overridden
+ * by calling {@link #setClassLoader(ClassLoader)} prior to invoking any of the {@code find()}
+ * methods.</p>
+ *
+ * <p>General searches are initiated by calling the
+ * {@link #find(org.apache.logging.log4j.core..util.ResolverUtil.Test, String...)} ()} method and supplying
+ * a package name and a Test instance. This will cause the named package <b>and all sub-packages</b>
+ * to be scanned for classes that meet the test. There are also utility methods for the common
+ * use cases of scanning multiple packages for extensions of particular classes, or classes
+ * annotated with a specific annotation.</p>
+ *
+ * <p>The standard usage pattern for the ResolverUtil class is as follows:</p>
+ *
+ *<pre>
+ *ResolverUtil<ActionBean> resolver = new ResolverUtil<ActionBean>();
+ *resolver.findImplementation(ActionBean.class, pkg1, pkg2);
+ *resolver.find(new CustomTest(), pkg1);
+ *resolver.find(new CustomTest(), pkg2);
+ *Collection<ActionBean> beans = resolver.getClasses();
+ *</pre>
+ *
+ * <p>This class was copied from Stripes - http://stripes.mc4j.org/confluence/display/stripes/Home
+ * </p>
+ *
+ * @author Tim Fennell
+ */
+public class ResolverUtil<T> {
+ /** An instance of Log to use for logging in this class. */
+ private static final Logger LOG = StatusLogger.getLogger();
+
+ /**
+ * A simple interface that specifies how to test classes to determine if they
+ * are to be included in the results produced by the ResolverUtil.
+ */
+ public static interface Test {
+ /**
+ * Will be called repeatedly with candidate classes. Must return True if a class
+ * is to be included in the results, false otherwise.
+ */
+ boolean matches(Class type);
+
+ boolean matches(URL resource);
+
+ boolean doesMatchClass();
+ boolean doesMatchResource();
+ }
+
+ public static abstract class ClassTest implements Test {
+ public boolean matches(URL resource) {
+ throw new UnsupportedOperationException();
+ }
+
+ public boolean doesMatchClass() {
+ return true;
+ }
+ public boolean doesMatchResource() {
+ return false;
+ }
+ }
+
+ public static abstract class ResourceTest implements Test {
+ public boolean matches(Class cls) {
+ throw new UnsupportedOperationException();
+ }
+
+ public boolean doesMatchClass() {
+ return false;
+ }
+ public boolean doesMatchResource() {
+ return true;
+ }
+ }
+
+ /**
+ * A Test that checks to see if each class is assignable to the provided class. Note
+ * that this test will match the parent type itself if it is presented for matching.
+ */
+ public static class IsA extends ClassTest {
+ private Class parent;
+
+ /** Constructs an IsA test using the supplied Class as the parent class/interface. */
+ public IsA(Class parentType) { this.parent = parentType; }
+
+ /** Returns true if type is assignable to the parent type supplied in the constructor. */
+ public boolean matches(Class type) {
+ return type != null && parent.isAssignableFrom(type);
+ }
+
+ @Override public String toString() {
+ return "is assignable to " + parent.getSimpleName();
+ }
+ }
+
+ /**
+ * A Test that checks to see if each class name ends with the provided suffix.
+ */
+ public static class NameEndsWith extends ClassTest {
+ private String suffix;
+
+ /** Constructs a NameEndsWith test using the supplied suffix. */
+ public NameEndsWith(String suffix) { this.suffix = suffix; }
+
+ /** Returns true if type name ends with the suffix supplied in the constructor. */
+ public boolean matches(Class type) {
+ return type != null && type.getName().endsWith(suffix);
+ }
+
+ @Override public String toString() {
+ return "ends with the suffix " + suffix;
+ }
+ }
+
+ /**
+ * A Test that checks to see if each class is annotated with a specific annotation. If it
+ * is, then the test returns true, otherwise false.
+ */
+ public static class AnnotatedWith extends ClassTest {
+ private Class<? extends Annotation> annotation;
+
+ /** Construts an AnnotatedWith test for the specified annotation type. */
+ public AnnotatedWith(Class<? extends Annotation> annotation) { this.annotation = annotation; }
+
+ /** Returns true if the type is annotated with the class provided to the constructor. */
+ public boolean matches(Class type) {
+ return type != null && type.isAnnotationPresent(annotation);
+ }
+
+ @Override public String toString() {
+ return "annotated with @" + annotation.getSimpleName();
+ }
+ }
+
+ public static class NameIs extends ResourceTest {
+ private String name;
+
+ public NameIs(String name) { this.name = "/" + name; }
+
+ public boolean matches(URL resource) {
+ return (resource.getPath().endsWith(name));
+ }
+
+ @Override public String toString() {
+ return "named " + name;
+ }
+ }
+
+ /** The set of matches being accumulated. */
+ private Set<Class<? extends T>> classMatches = new HashSet<Class<?extends T>>();
+
+ /** The set of matches being accumulated. */
+ private Set<URL> resourceMatches = new HashSet<URL>();
+
+ /**
+ * The ClassLoader to use when looking for classes. If null then the ClassLoader returned
+ * by Thread.currentThread().getContextClassLoader() will be used.
+ */
+ private ClassLoader classloader;
+
+ /**
+ * Provides access to the classes discovered so far. If no calls have been made to
+ * any of the {@code find()} methods, this set will be empty.
+ *
+ * @return the set of classes that have been discovered.
+ */
+ public Set<Class<? extends T>> getClasses() {
+ return classMatches;
+ }
+
+ public Set<URL> getResources() {
+ return resourceMatches;
+ }
+
+
+ /**
+ * Returns the classloader that will be used for scanning for classes. If no explicit
+ * ClassLoader has been set by the calling, the context class loader will be used.
+ *
+ * @return the ClassLoader that will be used to scan for classes
+ */
+ public ClassLoader getClassLoader() {
+ return classloader == null ? Thread.currentThread().getContextClassLoader() : classloader;
+ }
+
+ /**
+ * Sets an explicit ClassLoader that should be used when scanning for classes. If none
+ * is set then the context classloader will be used.
+ *
+ * @param classloader a ClassLoader to use when scanning for classes
+ */
+ public void setClassLoader(ClassLoader classloader) { this.classloader = classloader; }
+
+ /**
+ * Attempts to discover classes that are assignable to the type provided. In the case
+ * that an interface is provided this method will collect implementations. In the case
+ * of a non-interface class, subclasses will be collected. Accumulated classes can be
+ * accessed by calling {@link #getClasses()}.
+ *
+ * @param parent the class of interface to find subclasses or implementations of
+ * @param packageNames one or more package names to scan (including subpackages) for classes
+ */
+ public void findImplementations(Class parent, String... packageNames) {
+ if (packageNames == null) return;
+
+ Test test = new IsA(parent);
+ for (String pkg : packageNames) {
+ findInPackage(test, pkg);
+ }
+ }
+
+ /**
+ * Attempts to discover classes who's name ends with the provided suffix. Accumulated classes can be
+ * accessed by calling {@link #getClasses()}.
+ *
+ * @param suffix The class name suffix to match
+ * @param packageNames one or more package names to scan (including subpackages) for classes
+ */
+ public void findSuffix(String suffix, String... packageNames) {
+ if (packageNames == null) return;
+
+ Test test = new NameEndsWith(suffix);
+ for (String pkg : packageNames) {
+ findInPackage(test, pkg);
+ }
+ }
+
+ /**
+ * Attempts to discover classes that are annotated with to the annotation. Accumulated
+ * classes can be accessed by calling {@link #getClasses()}.
+ *
+ * @param annotation the annotation that should be present on matching classes
+ * @param packageNames one or more package names to scan (including subpackages) for classes
+ */
+ public void findAnnotated(Class<? extends Annotation> annotation, String... packageNames) {
+ if (packageNames == null) return;
+
+ Test test = new AnnotatedWith(annotation);
+ for (String pkg : packageNames) {
+ findInPackage(test, pkg);
+ }
+ }
+
+ public void findNamedResource(String name, String... pathNames) {
+ if (pathNames == null) return;
+
+ Test test = new NameIs(name);
+ for (String pkg : pathNames) {
+ findInPackage(test, pkg);
+ }
+ }
+
+ /**
+ * Attempts to discover classes that pass the test. Accumulated
+ * classes can be accessed by calling {@link #getClasses()}.
+ *
+ * @param test the test to determine matching classes
+ * @param packageNames one or more package names to scan (including subpackages) for classes
+ */
+ public void find(Test test, String... packageNames) {
+ if (packageNames == null) return;
+
+ for (String pkg : packageNames) {
+ findInPackage(test, pkg);
+ }
+ }
+
+ /**
+ * Scans for classes starting at the package provided and descending into subpackages.
+ * Each class is offered up to the Test as it is discovered, and if the Test returns
+ * true the class is retained. Accumulated classes can be fetched by calling
+ * {@link #getClasses()}.
+ *
+ * @param test an instance of {@link Test} that will be used to filter classes
+ * @param packageName the name of the package from which to start scanning for
+ * classes, e.g. {@code net.sourceforge.stripes}
+ */
+ public void findInPackage(Test test, String packageName) {
+ packageName = packageName.replace('.', '/');
+ ClassLoader loader = getClassLoader();
+ Enumeration<URL> urls;
+
+ try {
+ urls = loader.getResources(packageName);
+ }
+ catch (IOException ioe) {
+ LOG.warn("Could not read package: " + packageName, ioe);
+ return;
+ }
+
+ while (urls.hasMoreElements()) {
+ try {
+ String urlPath = urls.nextElement().getFile();
+ urlPath = URLDecoder.decode(urlPath, "UTF-8");
+
+ // If it's a file in a directory, trim the stupid file: spec
+ if ( urlPath.startsWith("file:") ) {
+ urlPath = urlPath.substring(5);
+ }
+
+ // Else it's in a JAR, grab the path to the jar
+ if (urlPath.indexOf('!') > 0) {
+ urlPath = urlPath.substring(0, urlPath.indexOf('!'));
+ }
+
+ LOG.info("Scanning for classes in [" + urlPath + "] matching criteria: " + test);
+ File file = new File(urlPath);
+ if ( file.isDirectory() ) {
+ loadImplementationsInDirectory(test, packageName, file);
+ }
+ else {
+ loadImplementationsInJar(test, packageName, file);
+ }
+ }
+ catch (IOException ioe) {
+ LOG.warn("could not read entries", ioe);
+ }
+ }
+ }
+
+
+ /**
+ * Finds matches in a physical directory on a filesystem. Examines all
+ * files within a directory - if the File object is not a directory, and ends with <i>.class</i>
+ * the file is loaded and tested to see if it is acceptable according to the Test. Operates
+ * recursively to find classes within a folder structure matching the package structure.
+ *
+ * @param test a Test used to filter the classes that are discovered
+ * @param parent the package name up to this directory in the package hierarchy. E.g. if
+ * /classes is in the classpath and we wish to examine files in /classes/org/apache then
+ * the values of <i>parent</i> would be <i>org/apache</i>
+ * @param location a File object representing a directory
+ */
+ private void loadImplementationsInDirectory(Test test, String parent, File location) {
+ File[] files = location.listFiles();
+ StringBuilder builder = null;
+
+ for (File file : files) {
+ builder = new StringBuilder(100);
+ builder.append(parent).append("/").append(file.getName());
+ String packageOrClass = ( parent == null ? file.getName() : builder.toString() );
+
+ if (file.isDirectory()) {
+ loadImplementationsInDirectory(test, packageOrClass, file);
+ }
+ else if (isTestApplicable(test, file.getName())) {
+ addIfMatching(test, packageOrClass);
+ }
+ }
+ }
+
+ private boolean isTestApplicable(Test test, String path) {
+ return test.doesMatchResource() || path.endsWith(".class") && test.doesMatchClass();
+ }
+
+ /**
+ * Finds matching classes within a jar files that contains a folder structure
+ * matching the package structure. If the File is not a JarFile or does not exist a warning
+ * will be logged, but no error will be raised.
+ *
+ * @param test a Test used to filter the classes that are discovered
+ * @param parent the parent package under which classes must be in order to be considered
+ * @param jarfile the jar file to be examined for classes
+ */
+ private void loadImplementationsInJar(Test test, String parent, File jarfile) {
+
+ try {
+ JarEntry entry;
+ JarInputStream jarStream = new JarInputStream(new FileInputStream(jarfile));
+
+ while ( (entry = jarStream.getNextJarEntry() ) != null) {
+ String name = entry.getName();
+ if (!entry.isDirectory() && name.startsWith(parent) && isTestApplicable(test, name)) {
+ addIfMatching(test, name);
+ }
+ }
+ }
+ catch (IOException ioe) {
+ LOG.error("Could not search jar file '" + jarfile + "' for classes matching criteria: " +
+ test + " due to an IOException", ioe);
+ }
+ }
+
+ /**
+ * Add the class designated by the fully qualified class name provided to the set of
+ * resolved classes if and only if it is approved by the Test supplied.
+ *
+ * @param test the test used to determine if the class matches
+ * @param fqn the fully qualified name of a class
+ */
+ protected void addIfMatching(Test test, String fqn) {
+ try {
+ ClassLoader loader = getClassLoader();
+ if (test.doesMatchClass()) {
+ String externalName = fqn.substring(0, fqn.indexOf('.')).replace('/', '.');
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("Checking to see if class " + externalName + " matches criteria [" + test + "]");
+ }
+
+ Class type = loader.loadClass(externalName);
+ if (test.matches(type) ) {
+ classMatches.add( (Class<T>) type);
+ }
+ }
+ if (test.doesMatchResource()) {
+ URL url = loader.getResource(fqn);
+ if (url == null) {
+ url = loader.getResource(fqn.substring(1));
+ }
+ if (url != null && test.matches(url)) {
+ resourceMatches.add(url);
+ }
+ }
+ }
+ catch (Throwable t) {
+ LOG.warn("Could not examine class '" + fqn + "' due to a " +
+ t.getClass().getName() + " with message: " + t.getMessage());
+ }
+ }
+}
\ No newline at end of file
Added: logging/log4j/branches/BRANCH_2_0_EXPERIMENTAL/rgoers/log4j2-core/src/main/java/org/apache/logging/log4j/core/filter/FilterBase.java
URL: http://svn.apache.org/viewvc/logging/log4j/branches/BRANCH_2_0_EXPERIMENTAL/rgoers/log4j2-core/src/main/java/org/apache/logging/log4j/core/filter/FilterBase.java?rev=943816&view=auto
==============================================================================
--- logging/log4j/branches/BRANCH_2_0_EXPERIMENTAL/rgoers/log4j2-core/src/main/java/org/apache/logging/log4j/core/filter/FilterBase.java (added)
+++ logging/log4j/branches/BRANCH_2_0_EXPERIMENTAL/rgoers/log4j2-core/src/main/java/org/apache/logging/log4j/core/filter/FilterBase.java Thu May 13 06:31:04 2010
@@ -0,0 +1,122 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache license, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the license for the specific language governing permissions and
+ * limitations under the license.
+ */
+package org.apache.logging.log4j.core.filter;
+
+import org.apache.logging.log4j.Level;
+import org.apache.logging.log4j.Marker;
+import org.apache.logging.log4j.core.Filter;
+import org.apache.logging.log4j.core.LogEvent;
+import org.apache.logging.log4j.core.Logger;
+import org.apache.logging.log4j.core.config.Node;
+import org.apache.logging.log4j.internal.StatusLogger;
+import org.apache.logging.log4j.message.Message;
+
+/**
+ * Users should extend this class to implement filters. Filters can be either context wide or attached to
+ * an appender. A filter may choose to support being called only from the context or only from an appender in
+ * which case it will only implement the required method(s). The rest will default to return NEUTRAL.
+ */
+public abstract class FilterBase implements Filter {
+
+ protected boolean started;
+
+ protected final Result onMatch;
+
+ protected final Result onMismatch;
+
+ protected static final org.apache.logging.log4j.Logger LOGGER = StatusLogger.getLogger();
+
+ protected static final String ON_MATCH = "onmatch";
+ protected static final String ON_MISMATCH = "onmismatch";
+
+ protected FilterBase() {
+ this(null, null);
+ }
+
+ protected FilterBase(Result onMatch, Result onMismatch) {
+ this.onMatch = onMatch == null ? Result.ACCEPT : onMatch;
+ this.onMismatch = onMismatch == null ? Result.NEUTRAL : onMismatch;
+ }
+
+ public void start() {
+ started = true;
+ }
+
+ public boolean isStarted() {
+ return started;
+ }
+
+ public void stop() {
+ started = false;
+ }
+
+ public final Result getOnMismatch() {
+ return onMismatch;
+ }
+
+ public final Result getOnMatch() {
+ return onMatch;
+ }
+
+ /**
+ * Appender Filter method. The default returns NEUTRAL.
+ * @param logger the logger
+ * @param level
+ * @param marker
+ * @param msg
+ * @param params
+ * @return
+ */
+ public Result filter(Logger logger, Level level, Marker marker, String msg, Object[] params) {
+ return Result.NEUTRAL;
+ }
+
+ /**
+ * Appender Filter method. The default returns NEUTRAL.
+ * @param logger
+ * @param level
+ * @param marker
+ * @param msg
+ * @param t
+ * @return
+ */
+ public Result filter(Logger logger, Level level, Marker marker, Object msg, Throwable t) {
+ return Result.NEUTRAL;
+ }
+
+ /**
+ * Appender Filter method. The default returns NEUTRAL.
+ * @param logger
+ * @param level
+ * @param marker
+ * @param msg
+ * @param t
+ * @return
+ */
+ public Result filter(Logger logger, Level level, Marker marker, Message msg, Throwable t) {
+ return Result.NEUTRAL;
+ }
+
+ /**
+ * Context Filter method. The default returns NEUTRAL.
+ * @param event
+ * @return
+ */
+ public Result filter(LogEvent event) {
+ return Result.NEUTRAL;
+ }
+}
Added: logging/log4j/branches/BRANCH_2_0_EXPERIMENTAL/rgoers/log4j2-core/src/main/java/org/apache/logging/log4j/core/filter/MDCFilter.java
URL: http://svn.apache.org/viewvc/logging/log4j/branches/BRANCH_2_0_EXPERIMENTAL/rgoers/log4j2-core/src/main/java/org/apache/logging/log4j/core/filter/MDCFilter.java?rev=943816&view=auto
==============================================================================
--- logging/log4j/branches/BRANCH_2_0_EXPERIMENTAL/rgoers/log4j2-core/src/main/java/org/apache/logging/log4j/core/filter/MDCFilter.java (added)
+++ logging/log4j/branches/BRANCH_2_0_EXPERIMENTAL/rgoers/log4j2-core/src/main/java/org/apache/logging/log4j/core/filter/MDCFilter.java Thu May 13 06:31:04 2010
@@ -0,0 +1,102 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache license, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the license for the specific language governing permissions and
+ * limitations under the license.
+ */
+package org.apache.logging.log4j.core.filter;
+
+import org.apache.logging.log4j.Level;
+import org.apache.logging.log4j.MDC;
+import org.apache.logging.log4j.Marker;
+import org.apache.logging.log4j.core.LogEvent;
+import org.apache.logging.log4j.core.Logger;
+import org.apache.logging.log4j.core.config.Node;
+import org.apache.logging.log4j.core.config.plugins.Plugin;
+import org.apache.logging.log4j.core.config.plugins.PluginFactory;
+import org.apache.logging.log4j.message.Message;
+
+import java.util.Map;
+
+/**
+ *
+ */
+@Plugin(name="MDC", type="Core")
+public class MDCFilter extends FilterBase {
+ private final String key;
+ private final String value;
+
+ private static final String KEY = "key";
+ private static final String VALUE = "value";
+
+ public MDCFilter(String key, String value, Result onMatch, Result onMismatch) {
+ super(onMatch, onMismatch);
+ if (key == null) {
+ throw new NullPointerException("key cannot be null");
+ }
+ if (value == null) {
+ throw new NullPointerException("value cannot be null");
+ }
+ this.key = key;
+ this.value = value;
+ }
+
+ public String getKey() {
+ return this.key;
+ }
+
+ public String getValue() {
+ return this.value;
+ }
+ public Result filter(Logger logger, Level level, Marker marker, String msg, Object[] params) {
+ return filter(MDC.get(key));
+ }
+
+ public Result filter(Logger logger, Level level, Marker marker, Object msg, Throwable t) {
+ return filter(MDC.get(key));
+ }
+
+ public Result filter(Logger logger, Level level, Marker marker, Message msg, Throwable t) {
+ return filter(MDC.get(key));
+ }
+
+ @Override
+ public Result filter(LogEvent event) {
+ return filter(event.getContextMap().get(key));
+ }
+
+ private Result filter(Object val) {
+ return this.value.equals(val) ? onMatch : onMismatch;
+ }
+
+ @PluginFactory
+ public static MDCFilter createFilter(Node node) {
+ String key = null;
+ String value = null;
+ Result onMatch = null;
+ Result onMismatch = null;
+ for (Map.Entry<String, String> entry : node.getAttributes().entrySet()) {
+ String name = entry.getKey().toLowerCase();
+ if (name.equals(KEY)) {
+ key = entry.getValue();
+ } else if (name.equals(VALUE)) {
+ value = entry.getValue();
+ } else if (name.equals(ON_MATCH)) {
+ onMatch = Result.valueOf(entry.getValue());
+ } else if (name.equals(ON_MISMATCH)) {
+ onMismatch = Result.valueOf(entry.getValue());
+ }
+ }
+ return new MDCFilter(key, value, onMatch, onMismatch);
+ }
+}
---------------------------------------------------------------------
To unsubscribe, e-mail: log4j-dev-unsubscribe@logging.apache.org
For additional commands, e-mail: log4j-dev-help@logging.apache.org