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