View Javadoc

1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements. See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache license, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License. You may obtain a copy of the License at
8    *
9    *      http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the license for the specific language governing permissions and
15   * limitations under the license.
16   */
17  package org.apache.logging.log4j.core.lookup;
18  
19  import java.util.HashMap;
20  import java.util.Map;
21  
22  import org.apache.logging.log4j.Logger;
23  import org.apache.logging.log4j.core.LogEvent;
24  import org.apache.logging.log4j.core.config.plugins.PluginManager;
25  import org.apache.logging.log4j.core.config.plugins.PluginType;
26  import org.apache.logging.log4j.status.StatusLogger;
27  
28  /**
29   * The Interpolator is a StrLookup that acts as a proxy for all the other StrLookups.
30   */
31  public class Interpolator implements StrLookup {
32  
33      private static final Logger LOGGER = StatusLogger.getLogger();
34  
35      /** Constant for the prefix separator. */
36      private static final char PREFIX_SEPARATOR = ':';
37  
38      private final Map<String, StrLookup> lookups = new HashMap<String, StrLookup>();
39  
40      private final StrLookup defaultLookup;
41  
42      public Interpolator(final StrLookup defaultLookup) {
43          this.defaultLookup = defaultLookup == null ? new MapLookup(new HashMap<String, String>()) : defaultLookup;
44          final PluginManager manager = new PluginManager("Lookup");
45          manager.collectPlugins();
46          final Map<String, PluginType<?>> plugins = manager.getPlugins();
47  
48          for (final Map.Entry<String, PluginType<?>> entry : plugins.entrySet()) {
49              @SuppressWarnings("unchecked")
50              final Class<? extends StrLookup> clazz = (Class<? extends StrLookup>) entry.getValue().getPluginClass();
51              try {
52                  lookups.put(entry.getKey(), clazz.newInstance());
53              } catch (final Exception ex) {
54                  LOGGER.error("Unable to create Lookup for " + entry.getKey(), ex);
55              }
56          }
57      }
58  
59      /**
60       * Create the default Interpolator using only Lookups that work without an event.
61       */
62      public Interpolator() {
63          this((Map<String, String>) null);
64      }
65  
66      /**
67       * Create the dInterpolator using only Lookups that work without an event and initial properties.
68       */
69      public Interpolator(Map<String, String> properties) {
70          this.defaultLookup = new MapLookup(properties == null ? new HashMap<String, String>() : properties);
71          lookups.put("sys", new SystemPropertiesLookup());
72          lookups.put("env", new EnvironmentLookup());
73          lookups.put("jndi", new JndiLookup());
74          try {
75              if (Class.forName("javax.servlet.ServletContext") != null) {
76                  lookups.put("web", new WebLookup());
77              }
78          } catch (ClassNotFoundException ex) {
79              LOGGER.debug("ServletContext not present - WebLookup not added");
80          } catch (Exception ex) {
81              LOGGER.error("Unable to locate ServletContext", ex);
82          }
83      }
84  
85       /**
86       * Resolves the specified variable. This implementation will try to extract
87       * a variable prefix from the given variable name (the first colon (':') is
88       * used as prefix separator). It then passes the name of the variable with
89       * the prefix stripped to the lookup object registered for this prefix. If
90       * no prefix can be found or if the associated lookup object cannot resolve
91       * this variable, the default lookup object will be used.
92       *
93       * @param var the name of the variable whose value is to be looked up
94       * @return the value of this variable or <b>null</b> if it cannot be
95       * resolved
96       */
97      @Override
98      public String lookup(final String var) {
99          return lookup(null, var);
100     }
101 
102     /**
103      * Resolves the specified variable. This implementation will try to extract
104      * a variable prefix from the given variable name (the first colon (':') is
105      * used as prefix separator). It then passes the name of the variable with
106      * the prefix stripped to the lookup object registered for this prefix. If
107      * no prefix can be found or if the associated lookup object cannot resolve
108      * this variable, the default lookup object will be used.
109      *
110      * @param event The current LogEvent or null.
111      * @param var the name of the variable whose value is to be looked up
112      * @return the value of this variable or <b>null</b> if it cannot be
113      * resolved
114      */
115     @Override
116     public String lookup(final LogEvent event, String var) {
117         if (var == null) {
118             return null;
119         }
120 
121         final int prefixPos = var.indexOf(PREFIX_SEPARATOR);
122         if (prefixPos >= 0) {
123             final String prefix = var.substring(0, prefixPos);
124             final String name = var.substring(prefixPos + 1);
125             final StrLookup lookup = lookups.get(prefix);
126             String value = null;
127             if (lookup != null) {
128                 value = event == null ? lookup.lookup(name) : lookup.lookup(event, name);
129             }
130 
131             if (value != null) {
132                 return value;
133             }
134             var = var.substring(prefixPos + 1);
135         }
136         if (defaultLookup != null) {
137             return event == null ? defaultLookup.lookup(var) : defaultLookup.lookup(event, var);
138         }
139         return null;
140     }
141 
142     @Override
143     public String toString() {
144         final StringBuilder sb = new StringBuilder();
145         for (final String name : lookups.keySet()) {
146             if (sb.length() == 0) {
147                 sb.append("{");
148             } else {
149                 sb.append(", ");
150             }
151 
152             sb.append(name);
153         }
154         if (sb.length() > 0) {
155             sb.append("}");
156         }
157         return sb.toString();
158     }
159 }