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