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.net.URI;
029    import java.util.ArrayList;
030    import java.util.Collections;
031    import java.util.List;
032    import java.util.Map;
033    import java.util.concurrent.ConcurrentHashMap;
034    import java.util.concurrent.ConcurrentMap;
035    
036    /**
037     * This class can be used to define a
038     * custom logger repository.  It makes use of the fact that in J2EE
039     * environments, each web-application is guaranteed to have its own JNDI
040     * context relative to the <code>java:comp/env</code> context. In EJBs, each
041     * enterprise bean (albeit not each application) has its own context relative
042     * to the <code>java:comp/env</code> context.  An <code>env-entry</code> in a
043     * deployment descriptor provides the information to the JNDI context.  Once the
044     * <code>env-entry</code> is set, a repository selector can query the JNDI
045     * application context to look up the value of the entry. The logging context of
046     * the web-application will depend on the value the env-entry.  The JNDI context
047     *  which is looked up by this class is
048     * <code>java:comp/env/log4j/context-name</code>.
049     *
050     * <p>Here is an example of an <code>env-entry<code>:
051     * <blockquote>
052     * <pre>
053     * &lt;env-entry&gt;
054     *   &lt;description&gt;JNDI logging context name for this app&lt;/description&gt;
055     *   &lt;env-entry-name&gt;log4j/context-name&lt;/env-entry-name&gt;
056     *   &lt;env-entry-value&gt;aDistinctiveLoggingContextName&lt;/env-entry-value&gt;
057     *   &lt;env-entry-type&gt;java.lang.String&lt;/env-entry-type&gt;
058     * &lt;/env-entry&gt;
059     * </pre>
060     * </blockquote>
061     * </p>
062     *
063     * <p><em>If multiple applications use the same logging context name, then they
064     * will share the same logging context.</em>
065     * </p>
066     *
067     *<p>You can also specify the URL for this context's configuration resource.
068     * This repository selector (ContextJNDISelector) will use this resource
069     * to automatically configure the log4j repository.
070     *</p>
071     ** <blockquote>
072     * <pre>
073     * &lt;env-entry&gt;
074     *   &lt;description&gt;URL for configuring log4j context&lt;/description&gt;
075     *   &lt;env-entry-name&gt;log4j/configuration-resource&lt;/env-entry-name&gt;
076     *   &lt;env-entry-value&gt;urlOfConfigrationResource&lt;/env-entry-value&gt;
077     *   &lt;env-entry-type&gt;java.lang.String&lt;/env-entry-type&gt;
078     * &lt;/env-entry&gt;
079     * </pre>
080     * </blockquote>
081     *
082     * <p>It usually good practice for configuration resources of distinct
083     * applications to have distinct names. However, if this is not possible
084     * Naming
085     * </p>
086     *
087     */
088    public class JNDIContextSelector implements NamedContextSelector {
089    
090        private static final LoggerContext CONTEXT = new LoggerContext("Default");
091    
092        private static final ConcurrentMap<String, LoggerContext> CONTEXT_MAP =
093            new ConcurrentHashMap<String, LoggerContext>();
094    
095        private static final StatusLogger LOGGER = StatusLogger.getLogger();
096    
097        public LoggerContext getContext(final String fqcn, final ClassLoader loader, final boolean currentContext) {
098            return getContext(fqcn, loader, currentContext, null);
099        }
100    
101        public LoggerContext getContext(final String fqcn, final ClassLoader loader, final boolean currentContext,
102                                        URI configLocation) {
103    
104            final LoggerContext lc = ContextAnchor.THREAD_CONTEXT.get();
105            if (lc != null) {
106                return lc;
107            }
108    
109            String loggingContextName = null;
110    
111            try {
112                final Context ctx = new InitialContext();
113                loggingContextName = (String) lookup(ctx, Constants.JNDI_CONTEXT_NAME);
114            } catch (final NamingException ne) {
115                LOGGER.error("Unable to lookup " + Constants.JNDI_CONTEXT_NAME, ne);
116            }
117    
118            return loggingContextName == null ? CONTEXT : locateContext(loggingContextName, configLocation);
119        }
120    
121        public LoggerContext locateContext(final String name, final URI configLocation) {
122            if (name == null) {
123                LOGGER.error("A context name is required to locate a LoggerContext");
124                return null;
125            }
126            if (!CONTEXT_MAP.containsKey(name)) {
127                final LoggerContext ctx = new LoggerContext(name, null, configLocation);
128                CONTEXT_MAP.putIfAbsent(name, ctx);
129            }
130            return CONTEXT_MAP.get(name);
131        }
132    
133        public void removeContext(final LoggerContext context) {
134    
135            for (final Map.Entry<String, LoggerContext> entry : CONTEXT_MAP.entrySet()) {
136                if (entry.getValue().equals(context)) {
137                    CONTEXT_MAP.remove(entry.getKey());
138                }
139            }
140        }
141    
142        public LoggerContext removeContext(final String name) {
143            return CONTEXT_MAP.remove(name);
144        }
145    
146        public List<LoggerContext> getLoggerContexts() {
147            final List<LoggerContext> list = new ArrayList<LoggerContext>(CONTEXT_MAP.values());
148            return Collections.unmodifiableList(list);
149        }
150    
151    
152        protected static Object lookup(final Context ctx, final String name) throws NamingException {
153            if (ctx == null) {
154                return null;
155            }
156            try {
157                return ctx.lookup(name);
158            } catch (final NameNotFoundException e) {
159                LOGGER.error("Could not find name [" + name + "].");
160                throw e;
161            }
162        }
163    }