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.lookup;
018
019import java.util.HashMap;
020import java.util.Map;
021
022import org.apache.logging.log4j.Logger;
023import org.apache.logging.log4j.core.LogEvent;
024import org.apache.logging.log4j.core.config.plugins.util.PluginManager;
025import org.apache.logging.log4j.core.config.plugins.util.PluginType;
026import org.apache.logging.log4j.core.util.Loader;
027import org.apache.logging.log4j.status.StatusLogger;
028
029/**
030 * Proxies all the other StrLookups.
031 */
032public class Interpolator implements StrLookup {
033
034    private static final Logger LOGGER = StatusLogger.getLogger();
035
036    /** Constant for the prefix separator. */
037    private static final char PREFIX_SEPARATOR = ':';
038
039    private final Map<String, StrLookup> lookups = new HashMap<String, StrLookup>();
040
041    private final StrLookup defaultLookup;
042
043    public Interpolator(final StrLookup defaultLookup) {
044        this.defaultLookup = defaultLookup == null ? new MapLookup(new HashMap<String, String>()) : defaultLookup;
045        final PluginManager manager = new PluginManager("Lookup");
046        manager.collectPlugins();
047        final Map<String, PluginType<?>> plugins = manager.getPlugins();
048
049        for (final Map.Entry<String, PluginType<?>> entry : plugins.entrySet()) {
050            @SuppressWarnings("unchecked")
051            final Class<? extends StrLookup> clazz = (Class<? extends StrLookup>) entry.getValue().getPluginClass();
052            try {
053                lookups.put(entry.getKey(), clazz.getConstructor().newInstance());
054            } catch (final Exception ex) {
055                LOGGER.error("Unable to create Lookup for {}", entry.getKey(), ex);
056            }
057        }
058    }
059
060    /**
061     * Create the default Interpolator using only Lookups that work without an event.
062     */
063    public Interpolator() {
064        this((Map<String, String>) null);
065    }
066
067    /**
068     * Create the dInterpolator using only Lookups that work without an event and initial properties.
069     */
070    public Interpolator(final Map<String, String> properties) {
071        this.defaultLookup = new MapLookup(properties == null ? new HashMap<String, String>() : properties);
072        // TODO: this ought to use the PluginManager
073        lookups.put("sys", new SystemPropertiesLookup());
074        lookups.put("env", new EnvironmentLookup());
075        try {
076            // [LOG4J2-703] We might be on Android
077            lookups.put("jndi",
078                Loader.newCheckedInstanceOf("org.apache.logging.log4j.core.lookup.JndiLookup", StrLookup.class));
079        } catch (Throwable e) {
080            // java.lang.VerifyError: org/apache/logging/log4j/core/lookup/JndiLookup
081            LOGGER.warn(
082                    "JNDI lookup class is not available because this JRE does not support JNDI. JNDI string lookups will not be available, continuing configuration.",
083                    e);
084        }
085        lookups.put("date", new DateLookup());
086        lookups.put("ctx", new ContextMapLookup());
087        if (Loader.isClassAvailable("javax.servlet.ServletContext")) {
088            try {
089                lookups.put("web",
090                    Loader.newCheckedInstanceOf("org.apache.logging.log4j.web.WebLookup", StrLookup.class));
091            } catch (final Exception ignored) {
092                LOGGER.info("Log4j appears to be running in a Servlet environment, but there's no log4j-web module " +
093                    "available. If you want better web container support, please add the log4j-web JAR to your " +
094                    "web archive or server lib directory.");
095            }
096        } else {
097            LOGGER.debug("Not in a ServletContext environment, thus not loading WebLookup plugin.");
098        }
099    }
100
101     /**
102     * Resolves the specified variable. This implementation will try to extract
103     * a variable prefix from the given variable name (the first colon (':') is
104     * used as prefix separator). It then passes the name of the variable with
105     * the prefix stripped to the lookup object registered for this prefix. If
106     * no prefix can be found or if the associated lookup object cannot resolve
107     * this variable, the default lookup object will be used.
108     *
109     * @param var the name of the variable whose value is to be looked up
110     * @return the value of this variable or <b>null</b> if it cannot be
111     * resolved
112     */
113    @Override
114    public String lookup(final String var) {
115        return lookup(null, var);
116    }
117
118    /**
119     * Resolves the specified variable. This implementation will try to extract
120     * a variable prefix from the given variable name (the first colon (':') is
121     * used as prefix separator). It then passes the name of the variable with
122     * the prefix stripped to the lookup object registered for this prefix. If
123     * no prefix can be found or if the associated lookup object cannot resolve
124     * this variable, the default lookup object will be used.
125     *
126     * @param event The current LogEvent or null.
127     * @param var the name of the variable whose value is to be looked up
128     * @return the value of this variable or <b>null</b> if it cannot be
129     * resolved
130     */
131    @Override
132    public String lookup(final LogEvent event, String var) {
133        if (var == null) {
134            return null;
135        }
136
137        final int prefixPos = var.indexOf(PREFIX_SEPARATOR);
138        if (prefixPos >= 0) {
139            final String prefix = var.substring(0, prefixPos);
140            final String name = var.substring(prefixPos + 1);
141            final StrLookup lookup = lookups.get(prefix);
142            String value = null;
143            if (lookup != null) {
144                value = event == null ? lookup.lookup(name) : lookup.lookup(event, name);
145            }
146
147            if (value != null) {
148                return value;
149            }
150            var = var.substring(prefixPos + 1);
151        }
152        if (defaultLookup != null) {
153            return event == null ? defaultLookup.lookup(var) : defaultLookup.lookup(event, var);
154        }
155        return null;
156    }
157
158    @Override
159    public String toString() {
160        final StringBuilder sb = new StringBuilder();
161        for (final String name : lookups.keySet()) {
162            if (sb.length() == 0) {
163                sb.append('{');
164            } else {
165                sb.append(", ");
166            }
167
168            sb.append(name);
169        }
170        if (sb.length() > 0) {
171            sb.append('}');
172        }
173        return sb.toString();
174    }
175}