    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.NamingException;
    027
    028    import org.apache.logging.log4j.core.LoggerContext;
    029    import org.apache.logging.log4j.core.impl.ContextAnchor;
    030    import org.apache.logging.log4j.core.net.JndiManager;
    031    import org.apache.logging.log4j.core.util.Constants;
    032    import 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     */
    086    public 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<String, LoggerContext>();
    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            final JndiManager jndiManager = JndiManager.getDefaultManager();
    112            try {
    113                loggingContextName = jndiManager.lookup(Constants.JNDI_CONTEXT_NAME);
    114            } catch (final NamingException ne) {
    115                LOGGER.error("Unable to lookup {}", Constants.JNDI_CONTEXT_NAME, ne);
    116            } finally {
    117                jndiManager.release();
    118            }
    119
    120            return loggingContextName == null ? CONTEXT : locateContext(loggingContextName, null, configLocation);
    121        }
    122
    123        @Override
    124        public LoggerContext locateContext(final String name, final Object externalContext, final URI configLocation) {
    125            if (name == null) {
    126                LOGGER.error("A context name is required to locate a LoggerContext");
    127                return null;
    128            }
    129            if (!CONTEXT_MAP.containsKey(name)) {
    130                final LoggerContext ctx = new LoggerContext(name, externalContext, configLocation);
    131                CONTEXT_MAP.putIfAbsent(name, ctx);
    132            }
    133            return CONTEXT_MAP.get(name);
    134        }
    135
    136        @Override
    137        public void removeContext(final LoggerContext context) {
    138
    139            for (final Map.Entry<String, LoggerContext> entry : CONTEXT_MAP.entrySet()) {
    140                if (entry.getValue().equals(context)) {
    141                    CONTEXT_MAP.remove(entry.getKey());
    142                }
    143            }
    144        }
    145
    146        @Override
    147        public LoggerContext removeContext(final String name) {
    148            return CONTEXT_MAP.remove(name);
    149        }
    150
    151        @Override
    152        public List<LoggerContext> getLoggerContexts() {
    153            final List<LoggerContext> list = new ArrayList<LoggerContext>(CONTEXT_MAP.values());
    154            return Collections.unmodifiableList(list);
    155        }
    156
    157    }