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