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.impl;
18  
19  import java.lang.reflect.Constructor;
20  import java.util.Map;
21  import java.util.Map.Entry;
22  
23  import org.apache.logging.log4j.core.ContextDataInjector;
24  import org.apache.logging.log4j.core.LogEvent;
25  import org.apache.logging.log4j.core.util.Loader;
26  import org.apache.logging.log4j.util.IndexedStringMap;
27  import org.apache.logging.log4j.util.PropertiesUtil;
28  import org.apache.logging.log4j.util.ReadOnlyStringMap;
29  import org.apache.logging.log4j.util.SortedArrayStringMap;
30  import org.apache.logging.log4j.util.StringMap;
31  
32  /**
33   * Factory for creating the StringMap instances used to initialize LogEvents' {@linkplain LogEvent#getContextData()
34   * context data}. When context data is {@linkplain ContextDataInjector injected} into the log event, these StringMap
35   * instances may be either populated with key-value pairs from the context, or completely replaced altogether.
36   * <p>
37   * By default returns {@code SortedArrayStringMap} objects. Can be configured by setting system property
38   * {@code "log4j2.ContextData"} to the fully qualified class name of a class implementing the {@code StringMap}
39   * interface. The class must have a public default constructor, and if possible should also have a public constructor
40   * that takes a single {@code int} argument for the initial capacity.
41   * </p>
42   *
43   * @see LogEvent#getContextData()
44   * @see ContextDataInjector
45   * @see SortedArrayStringMap
46   * @since 2.7
47   */
48  public class ContextDataFactory {
49      private static final String CLASS_NAME = PropertiesUtil.getProperties().getStringProperty("log4j2.ContextData");
50      private static final Class<? extends StringMap> CACHED_CLASS = createCachedClass(CLASS_NAME);
51  
52      /**
53       * In LOG4J2-2649 (https://issues.apache.org/jira/browse/LOG4J2-2649),
54       * the reporter said some reason about using graalvm to static compile.
55       * In graalvm doc (https://github.com/oracle/graal/blob/master/substratevm/LIMITATIONS.md),
56       * graalvm is not support MethodHandle now, so the Constructor need not to return MethodHandle.
57       */
58      private static final Constructor<?> DEFAULT_CONSTRUCTOR = createDefaultConstructor(CACHED_CLASS);
59      private static final Constructor<?> INITIAL_CAPACITY_CONSTRUCTOR = createInitialCapacityConstructor(CACHED_CLASS);
60  
61      private static final StringMap EMPTY_STRING_MAP = createContextData(0);
62  
63      static {
64          EMPTY_STRING_MAP.freeze();
65      }
66  
67      private static Class<? extends StringMap> createCachedClass(final String className) {
68          if (className == null) {
69              return null;
70          }
71          try {
72              return Loader.loadClass(className).asSubclass(IndexedStringMap.class);
73          } catch (final Exception any) {
74              return null;
75          }
76      }
77  
78      private static Constructor<?> createDefaultConstructor(final Class<? extends StringMap> cachedClass){
79          if (cachedClass == null) {
80              return null;
81          }
82          try {
83              return cachedClass.getConstructor();
84          } catch (final NoSuchMethodException | IllegalAccessError ignored) {
85              return null;
86          }
87      }
88  
89      private static Constructor<?> createInitialCapacityConstructor(final Class<? extends StringMap> cachedClass){
90          if (cachedClass == null) {
91              return null;
92          }
93          try {
94              return cachedClass.getConstructor(int.class);
95          } catch (final NoSuchMethodException | IllegalAccessError ignored) {
96              return null;
97          }
98      }
99  
100     public static StringMap createContextData() {
101         if (DEFAULT_CONSTRUCTOR == null) {
102             return new SortedArrayStringMap();
103         }
104         try {
105             return (IndexedStringMap) DEFAULT_CONSTRUCTOR.newInstance();
106         } catch (final Throwable ignored) {
107             return new SortedArrayStringMap();
108         }
109     }
110 
111     public static StringMap createContextData(final int initialCapacity) {
112         if (INITIAL_CAPACITY_CONSTRUCTOR == null) {
113             return new SortedArrayStringMap(initialCapacity);
114         }
115         try {
116             return (IndexedStringMap) INITIAL_CAPACITY_CONSTRUCTOR.newInstance(initialCapacity);
117         } catch (final Throwable ignored) {
118             return new SortedArrayStringMap(initialCapacity);
119         }
120     }
121 
122     public static StringMap createContextData(final Map<String, String> context) {
123         final StringMap contextData = createContextData(context.size());
124         for (final Entry<String, String> entry : context.entrySet()) {
125             contextData.putValue(entry.getKey(), entry.getValue());
126         }
127         return contextData;
128     }
129 
130     public static StringMap createContextData(final ReadOnlyStringMap readOnlyStringMap) {
131         final StringMap contextData = createContextData(readOnlyStringMap.size());
132         contextData.putAll(readOnlyStringMap);
133         return contextData;
134     }
135 
136     /**
137      * An empty pre-frozen IndexedStringMap. The returned object may be shared.
138      *
139      * @return an empty pre-frozen IndexedStringMap
140      */
141     public static StringMap emptyFrozenContextData() {
142         return EMPTY_STRING_MAP;
143     }
144 
145 }