001    /*
002     * Licensed to the Apache Software Foundation (ASF) under one or more
003     * contributor license agreements. See the NOTICE file distributed with
004     * this work for additional information regarding copyright ownership.
005     * The ASF licenses this file to You under the Apache license, Version 2.0
006     * (the "License"); you may not use this file except in compliance with
007     * the License. You may obtain a copy of the License at
008     *
009     *      http://www.apache.org/licenses/LICENSE-2.0
010     *
011     * Unless required by applicable law or agreed to in writing, software
012     * distributed under the License is distributed on an "AS IS" BASIS,
013     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014     * See the license for the specific language governing permissions and
015     * limitations under the license.
016     */
017    package org.apache.logging.log4j.core.selector;
018    
019    import org.apache.logging.log4j.core.LoggerContext;
020    import org.apache.logging.log4j.core.helpers.Constants;
021    import org.apache.logging.log4j.core.impl.ContextAnchor;
022    import org.apache.logging.log4j.status.StatusLogger;
023    
024    import javax.naming.Context;
025    import javax.naming.InitialContext;
026    import javax.naming.NameNotFoundException;
027    import javax.naming.NamingException;
028    import java.util.ArrayList;
029    import java.util.Collections;
030    import java.util.List;
031    import java.util.Map;
032    import java.util.concurrent.ConcurrentHashMap;
033    import java.util.concurrent.ConcurrentMap;
034    
035    /**
036     * This class can be used to define a
037     * custom logger repository.  It makes use of the fact that in J2EE
038     * environments, each web-application is guaranteed to have its own JNDI
039     * context relative to the <code>java:comp/env</code> context. In EJBs, each
040     * enterprise bean (albeit not each application) has its own context relative
041     * to the <code>java:comp/env</code> context.  An <code>env-entry</code> in a
042     * deployment descriptor provides the information to the JNDI context.  Once the
043     * <code>env-entry</code> is set, a repository selector can query the JNDI
044     * application context to look up the value of the entry. The logging context of
045     * the web-application will depend on the value the env-entry.  The JNDI context
046     *  which is looked up by this class is
047     * <code>java:comp/env/log4j/context-name</code>.
048     *
049     * <p>Here is an example of an <code>env-entry<code>:
050     * <blockquote>
051     * <pre>
052     * &lt;env-entry&gt;
053     *   &lt;description&gt;JNDI logging context name for this app&lt;/description&gt;
054     *   &lt;env-entry-name&gt;log4j/context-name&lt;/env-entry-name&gt;
055     *   &lt;env-entry-value&gt;aDistinctiveLoggingContextName&lt;/env-entry-value&gt;
056     *   &lt;env-entry-type&gt;java.lang.String&lt;/env-entry-type&gt;
057     * &lt;/env-entry&gt;
058     * </pre>
059     * </blockquote>
060     * </p>
061     *
062     * <p><em>If multiple applications use the same logging context name, then they
063     * will share the same logging context.</em>
064     * </p>
065     *
066     *<p>You can also specify the URL for this context's configuration resource.
067     * This repository selector (ContextJNDISelector) will use this resource
068     * to automatically configure the log4j repository.
069     *</p>
070     ** <blockquote>
071     * <pre>
072     * &lt;env-entry&gt;
073     *   &lt;description&gt;URL for configuring log4j context&lt;/description&gt;
074     *   &lt;env-entry-name&gt;log4j/configuration-resource&lt;/env-entry-name&gt;
075     *   &lt;env-entry-value&gt;urlOfConfigrationResource&lt;/env-entry-value&gt;
076     *   &lt;env-entry-type&gt;java.lang.String&lt;/env-entry-type&gt;
077     * &lt;/env-entry&gt;
078     * </pre>
079     * </blockquote>
080     *
081     * <p>It usually good practice for configuration resources of distinct
082     * applications to have distinct names. However, if this is not possible
083     * Naming
084     * </p>
085     *
086     */
087    public class JNDIContextSelector implements NamedContextSelector {
088    
089        private static final LoggerContext CONTEXT = new LoggerContext("Default");
090    
091        private static final ConcurrentMap<String, LoggerContext> CONTEXT_MAP =
092            new ConcurrentHashMap<String, LoggerContext>();
093    
094        private static final StatusLogger LOGGER = StatusLogger.getLogger();
095    
096        public LoggerContext getContext(final String fqcn, final ClassLoader loader, final boolean currentContext) {
097    
098            final LoggerContext lc = ContextAnchor.THREAD_CONTEXT.get();
099            if (lc != null) {
100                return lc;
101            }
102    
103            String loggingContextName = null;
104    
105            try {
106                final Context ctx = new InitialContext();
107                loggingContextName = (String) lookup(ctx, Constants.JNDI_CONTEXT_NAME);
108            } catch (final NamingException ne) {
109                LOGGER.error("Unable to lookup " + Constants.JNDI_CONTEXT_NAME, ne);
110            }
111    
112            return loggingContextName == null ? CONTEXT : locateContext(loggingContextName, null);
113        }
114    
115        public LoggerContext locateContext(final String name, final String configLocation) {
116            if (name == null) {
117                LOGGER.error("A context name is required to locate a LoggerContext");
118                return null;
119            }
120            if (!CONTEXT_MAP.containsKey(name)) {
121                final LoggerContext ctx = new LoggerContext(name, null, configLocation);
122                CONTEXT_MAP.putIfAbsent(name, ctx);
123            }
124            return CONTEXT_MAP.get(name);
125        }
126    
127        public void removeContext(final LoggerContext context) {
128    
129            for (final Map.Entry<String, LoggerContext> entry : CONTEXT_MAP.entrySet()) {
130                if (entry.getValue().equals(context)) {
131                    CONTEXT_MAP.remove(entry.getKey());
132                }
133            }
134        }
135    
136        public LoggerContext removeContext(final String name) {
137            return CONTEXT_MAP.remove(name);
138        }
139    
140        public List<LoggerContext> getLoggerContexts() {
141            final List<LoggerContext> list = new ArrayList<LoggerContext>(CONTEXT_MAP.values());
142            return Collections.unmodifiableList(list);
143        }
144    
145    
146        protected static Object lookup(final Context ctx, final String name) throws NamingException {
147            if (ctx == null) {
148                return null;
149            }
150            try {
151                return ctx.lookup(name);
152            } catch (final NameNotFoundException e) {
153                LOGGER.error("Could not find name [" + name + "].");
154                throw e;
155            }
156        }
157    }