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  
18  package org.apache.logging.log4j.core.config.plugins.util;
19  
20  import java.lang.annotation.Annotation;
21  import java.lang.reflect.AccessibleObject;
22  import java.lang.reflect.Field;
23  import java.lang.reflect.InvocationTargetException;
24  import java.lang.reflect.Method;
25  import java.lang.reflect.Modifier;
26  import java.util.Collection;
27  import java.util.List;
28  import java.util.Map;
29  import java.util.Objects;
30  
31  import org.apache.logging.log4j.Logger;
32  import org.apache.logging.log4j.core.LogEvent;
33  import org.apache.logging.log4j.core.config.Configuration;
34  import org.apache.logging.log4j.core.config.ConfigurationException;
35  import org.apache.logging.log4j.core.config.Node;
36  import org.apache.logging.log4j.core.config.plugins.PluginAliases;
37  import org.apache.logging.log4j.core.config.plugins.PluginBuilderFactory;
38  import org.apache.logging.log4j.core.config.plugins.PluginFactory;
39  import org.apache.logging.log4j.core.config.plugins.validation.ConstraintValidator;
40  import org.apache.logging.log4j.core.config.plugins.validation.ConstraintValidators;
41  import org.apache.logging.log4j.core.config.plugins.visitors.PluginVisitor;
42  import org.apache.logging.log4j.core.config.plugins.visitors.PluginVisitors;
43  import org.apache.logging.log4j.core.util.Builder;
44  import org.apache.logging.log4j.core.util.ReflectionUtil;
45  import org.apache.logging.log4j.core.util.TypeUtil;
46  import org.apache.logging.log4j.status.StatusLogger;
47  import org.apache.logging.log4j.util.StringBuilders;
48  
49  /**
50   * Builder class to instantiate and configure a Plugin object using a PluginFactory method or PluginBuilderFactory
51   * builder class.
52   */
53  public class PluginBuilder implements Builder<Object> {
54  
55      private static final Logger LOGGER = StatusLogger.getLogger();
56  
57      private final PluginType<?> pluginType;
58      private final Class<?> clazz;
59  
60      private Configuration configuration;
61      private Node node;
62      private LogEvent event;
63  
64      /**
65       * Constructs a PluginBuilder for a given PluginType.
66       *
67       * @param pluginType type of plugin to configure
68       */
69      public PluginBuilder(final PluginType<?> pluginType) {
70          this.pluginType = pluginType;
71          this.clazz = pluginType.getPluginClass();
72      }
73  
74      /**
75       * Specifies the Configuration to use for constructing the plugin instance.
76       *
77       * @param configuration the configuration to use.
78       * @return {@code this}
79       */
80      public PluginBuilder withConfiguration(final Configuration configuration) {
81          this.configuration = configuration;
82          return this;
83      }
84  
85      /**
86       * Specifies the Node corresponding to the plugin object that will be created.
87       *
88       * @param node the plugin configuration node to use.
89       * @return {@code this}
90       */
91      public PluginBuilder withConfigurationNode(final Node node) {
92          this.node = node;
93          return this;
94      }
95  
96      /**
97       * Specifies the LogEvent that may be used to provide extra context for string substitutions.
98       *
99       * @param event the event to use for extra information.
100      * @return {@code this}
101      */
102     public PluginBuilder forLogEvent(final LogEvent event) {
103         this.event = event;
104         return this;
105     }
106 
107     /**
108      * Builds the plugin object.
109      *
110      * @return the plugin object or {@code null} if there was a problem creating it.
111      */
112     @Override
113     public Object build() {
114         verify();
115         // first try to use a builder class if one is available
116         try {
117             LOGGER.debug("Building Plugin[name={}, class={}].", pluginType.getElementName(),
118                     pluginType.getPluginClass().getName());
119             final Builder<?> builder = createBuilder(this.clazz);
120             if (builder != null) {
121                 injectFields(builder);
122                 return builder.build();
123             }
124         } catch (final ConfigurationException e) { // LOG4J2-1908
125             LOGGER.error("Could not create plugin of type {} for element {}", this.clazz, node.getName(), e);
126             return null; // no point in trying the factory method
127         } catch (final Exception e) {
128             LOGGER.error("Could not create plugin of type {} for element {}: {}",
129                     this.clazz, node.getName(),
130                     (e instanceof InvocationTargetException ? ((InvocationTargetException) e).getCause() : e).toString(), e);
131         }
132         // or fall back to factory method if no builder class is available
133         try {
134             final Method factory = findFactoryMethod(this.clazz);
135             final Object[] params = generateParameters(factory);
136             return factory.invoke(null, params);
137         } catch (final Exception e) {
138             LOGGER.error("Unable to invoke factory method in {} for element {}: {}",
139                     this.clazz, this.node.getName(),
140                     (e instanceof InvocationTargetException ? ((InvocationTargetException) e).getCause() : e).toString(), e);
141             return null;
142         }
143     }
144 
145     private void verify() {
146         Objects.requireNonNull(this.configuration, "No Configuration object was set.");
147         Objects.requireNonNull(this.node, "No Node object was set.");
148     }
149 
150     private static Builder<?> createBuilder(final Class<?> clazz)
151         throws InvocationTargetException, IllegalAccessException {
152         for (final Method method : clazz.getDeclaredMethods()) {
153             if (method.isAnnotationPresent(PluginBuilderFactory.class) &&
154                 Modifier.isStatic(method.getModifiers()) &&
155                 TypeUtil.isAssignable(Builder.class, method.getReturnType())) {
156                 ReflectionUtil.makeAccessible(method);
157                 return (Builder<?>) method.invoke(null);
158             }
159         }
160         return null;
161     }
162 
163     private void injectFields(final Builder<?> builder) throws IllegalAccessException {
164         final List<Field> fields = TypeUtil.getAllDeclaredFields(builder.getClass());
165         AccessibleObject.setAccessible(fields.toArray(new Field[] {}), true);
166         final StringBuilder log = new StringBuilder();
167         boolean invalid = false;
168         for (final Field field : fields) {
169             log.append(log.length() == 0 ? simpleName(builder) + "(" : ", ");
170             final Annotation[] annotations = field.getDeclaredAnnotations();
171             final String[] aliases = extractPluginAliases(annotations);
172             for (final Annotation a : annotations) {
173                 if (a instanceof PluginAliases) {
174                     continue; // already processed
175                 }
176                 final PluginVisitor<? extends Annotation> visitor =
177                     PluginVisitors.findVisitor(a.annotationType());
178                 if (visitor != null) {
179                     final Object value = visitor.setAliases(aliases)
180                         .setAnnotation(a)
181                         .setConversionType(field.getType())
182                         .setStrSubstitutor(configuration.getStrSubstitutor())
183                         .setMember(field)
184                         .visit(configuration, node, event, log);
185                     // don't overwrite default values if the visitor gives us no value to inject
186                     if (value != null) {
187                         field.set(builder, value);
188                     }
189                 }
190             }
191             final Collection<ConstraintValidator<?>> validators =
192                 ConstraintValidators.findValidators(annotations);
193             final Object value = field.get(builder);
194             for (final ConstraintValidator<?> validator : validators) {
195                 if (!validator.isValid(field.getName(), value)) {
196                     invalid = true;
197                 }
198             }
199         }
200         log.append(log.length() == 0 ? builder.getClass().getSimpleName() + "()" : ")");
201         LOGGER.debug(log.toString());
202         if (invalid) {
203             throw new ConfigurationException("Arguments given for element " + node.getName() + " are invalid");
204         }
205         checkForRemainingAttributes();
206         verifyNodeChildrenUsed();
207     }
208 
209     /**
210      * {@code object.getClass().getSimpleName()} returns {@code Builder}, when we want {@code PatternLayout$Builder}.
211      */
212     private static String simpleName(final Object object) {
213         if (object == null) {
214             return "null";
215         }
216         final String cls = object.getClass().getName();
217         final int index = cls.lastIndexOf('.');
218         return index < 0 ? cls : cls.substring(index + 1);
219     }
220 
221     private static Method findFactoryMethod(final Class<?> clazz) {
222         for (final Method method : clazz.getDeclaredMethods()) {
223             if (method.isAnnotationPresent(PluginFactory.class) &&
224                 Modifier.isStatic(method.getModifiers())) {
225                 ReflectionUtil.makeAccessible(method);
226                 return method;
227             }
228         }
229         throw new IllegalStateException("No factory method found for class " + clazz.getName());
230     }
231 
232     private Object[] generateParameters(final Method factory) {
233         final StringBuilder log = new StringBuilder();
234         final Class<?>[] types = factory.getParameterTypes();
235         final Annotation[][] annotations = factory.getParameterAnnotations();
236         final Object[] args = new Object[annotations.length];
237         boolean invalid = false;
238         for (int i = 0; i < annotations.length; i++) {
239             log.append(log.length() == 0 ? factory.getName() + "(" : ", ");
240             final String[] aliases = extractPluginAliases(annotations[i]);
241             for (final Annotation a : annotations[i]) {
242                 if (a instanceof PluginAliases) {
243                     continue; // already processed
244                 }
245                 final PluginVisitor<? extends Annotation> visitor = PluginVisitors.findVisitor(
246                     a.annotationType());
247                 if (visitor != null) {
248                     final Object value = visitor.setAliases(aliases)
249                         .setAnnotation(a)
250                         .setConversionType(types[i])
251                         .setStrSubstitutor(configuration.getStrSubstitutor())
252                         .setMember(factory)
253                         .visit(configuration, node, event, log);
254                     // don't overwrite existing values if the visitor gives us no value to inject
255                     if (value != null) {
256                         args[i] = value;
257                     }
258                 }
259             }
260             final Collection<ConstraintValidator<?>> validators =
261                 ConstraintValidators.findValidators(annotations[i]);
262             final Object value = args[i];
263             final String argName = "arg[" + i + "](" + simpleName(value) + ")";
264             for (final ConstraintValidator<?> validator : validators) {
265                 if (!validator.isValid(argName, value)) {
266                     invalid = true;
267                 }
268             }
269         }
270         log.append(log.length() == 0 ? factory.getName() + "()" : ")");
271         checkForRemainingAttributes();
272         verifyNodeChildrenUsed();
273         LOGGER.debug(log.toString());
274         if (invalid) {
275             throw new ConfigurationException("Arguments given for element " + node.getName() + " are invalid");
276         }
277         return args;
278     }
279 
280     private static String[] extractPluginAliases(final Annotation... parmTypes) {
281         String[] aliases = null;
282         for (final Annotation a : parmTypes) {
283             if (a instanceof PluginAliases) {
284                 aliases = ((PluginAliases) a).value();
285             }
286         }
287         return aliases;
288     }
289 
290     private void checkForRemainingAttributes() {
291         final Map<String, String> attrs = node.getAttributes();
292         if (!attrs.isEmpty()) {
293             final StringBuilder sb = new StringBuilder();
294             for (final String key : attrs.keySet()) {
295                 if (sb.length() == 0) {
296                     sb.append(node.getName());
297                     sb.append(" contains ");
298                     if (attrs.size() == 1) {
299                         sb.append("an invalid element or attribute ");
300                     } else {
301                         sb.append("invalid attributes ");
302                     }
303                 } else {
304                     sb.append(", ");
305                 }
306                 StringBuilders.appendDqValue(sb, key);
307             }
308             LOGGER.error(sb.toString());
309         }
310     }
311 
312     private void verifyNodeChildrenUsed() {
313         final List<Node> children = node.getChildren();
314         if (!(pluginType.isDeferChildren() || children.isEmpty())) {
315             for (final Node child : children) {
316                 final String nodeType = node.getType().getElementName();
317                 final String start = nodeType.equals(node.getName()) ? node.getName() : nodeType + ' ' + node.getName();
318                 LOGGER.error("{} has no parameter that matches element {}", start, child.getName());
319             }
320         }
321     }
322 }