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