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                 final Object result = builder.build();
123                 return result;
124             }
125         } catch (final Exception e) {
126             LOGGER.error("Unable to inject fields into builder class for plugin type {}, element {}.", this.clazz,
127                 node.getName(), e);
128         }
129         // or fall back to factory method if no builder class is available
130         try {
131             final Method factory = findFactoryMethod(this.clazz);
132             final Object[] params = generateParameters(factory);
133             final Object plugin = factory.invoke(null, params);
134             return plugin;
135         } catch (final Exception e) {
136             LOGGER.error("Unable to invoke factory method in class {} for element {}.", this.clazz, this.node.getName(),
137                 e);
138             return null;
139         }
140     }
141 
142     private void verify() {
143         Objects.requireNonNull(this.configuration, "No Configuration object was set.");
144         Objects.requireNonNull(this.node, "No Node object was set.");
145     }
146 
147     private static Builder<?> createBuilder(final Class<?> clazz)
148         throws InvocationTargetException, IllegalAccessException {
149         for (final Method method : clazz.getDeclaredMethods()) {
150             if (method.isAnnotationPresent(PluginBuilderFactory.class) &&
151                 Modifier.isStatic(method.getModifiers()) &&
152                 TypeUtil.isAssignable(Builder.class, method.getGenericReturnType())) {
153                 ReflectionUtil.makeAccessible(method);
154                 final Builder<?> builder = (Builder<?>) method.invoke(null);
155                 return builder;
156             }
157         }
158         return null;
159     }
160 
161     private void injectFields(final Builder<?> builder) throws IllegalAccessException {
162         final Field[] fields = builder.getClass().getDeclaredFields();
163         AccessibleObject.setAccessible(fields, true);
164         final StringBuilder log = new StringBuilder();
165         boolean invalid = false;
166         for (final Field field : fields) {
167             log.append(log.length() == 0 ? simpleName(builder) + "(" : ", ");
168             final Annotation[] annotations = field.getDeclaredAnnotations();
169             final String[] aliases = extractPluginAliases(annotations);
170             for (final Annotation a : annotations) {
171                 if (a instanceof PluginAliases) {
172                     continue; // already processed
173                 }
174                 final PluginVisitor<? extends Annotation> visitor =
175                     PluginVisitors.findVisitor(a.annotationType());
176                 if (visitor != null) {
177                     final Object value = visitor.setAliases(aliases)
178                         .setAnnotation(a)
179                         .setConversionType(field.getType())
180                         .setStrSubstitutor(configuration.getStrSubstitutor())
181                         .setMember(field)
182                         .visit(configuration, node, event, log);
183                     // don't overwrite default values if the visitor gives us no value to inject
184                     if (value != null) {
185                         field.set(builder, value);
186                     }
187                 }
188             }
189             final Collection<ConstraintValidator<?>> validators =
190                 ConstraintValidators.findValidators(annotations);
191             final Object value = field.get(builder);
192             for (final ConstraintValidator<?> validator : validators) {
193                 if (!validator.isValid(field.getName(), value)) {
194                     invalid = true;
195                 }
196             }
197         }
198         log.append(log.length() == 0 ? builder.getClass().getSimpleName() + "()" : ")");
199         LOGGER.debug(log.toString());
200         if (invalid) {
201             throw new ConfigurationException("Arguments given for element " + node.getName() + " are invalid");
202         }
203         checkForRemainingAttributes();
204         verifyNodeChildrenUsed();
205     }
206 
207     /**
208      * {@code object.getClass().getSimpleName()} returns {@code Builder}, when we want {@code PatternLayout$Builder}.
209      */
210     private String simpleName(final Object object) {
211         if (object == null) {
212             return "null";
213         }
214         final String cls = object.getClass().getName();
215         final int index = cls.lastIndexOf('.');
216         return index < 0 ? cls : cls.substring(index + 1);
217     }
218 
219     private static Method findFactoryMethod(final Class<?> clazz) {
220         for (final Method method : clazz.getDeclaredMethods()) {
221             if (method.isAnnotationPresent(PluginFactory.class) &&
222                 Modifier.isStatic(method.getModifiers())) {
223                 ReflectionUtil.makeAccessible(method);
224                 return method;
225             }
226         }
227         throw new IllegalStateException("No factory method found for class " + clazz.getName());
228     }
229 
230     private Object[] generateParameters(final Method factory) {
231         final StringBuilder log = new StringBuilder();
232         final Class<?>[] types = factory.getParameterTypes();
233         final Annotation[][] annotations = factory.getParameterAnnotations();
234         final Object[] args = new Object[annotations.length];
235         boolean invalid = false;
236         for (int i = 0; i < annotations.length; i++) {
237             log.append(log.length() == 0 ? factory.getName() + "(" : ", ");
238             final String[] aliases = extractPluginAliases(annotations[i]);
239             for (final Annotation a : annotations[i]) {
240                 if (a instanceof PluginAliases) {
241                     continue; // already processed
242                 }
243                 final PluginVisitor<? extends Annotation> visitor = PluginVisitors.findVisitor(
244                     a.annotationType());
245                 if (visitor != null) {
246                     final Object value = visitor.setAliases(aliases)
247                         .setAnnotation(a)
248                         .setConversionType(types[i])
249                         .setStrSubstitutor(configuration.getStrSubstitutor())
250                         .setMember(factory)
251                         .visit(configuration, node, event, log);
252                     // don't overwrite existing values if the visitor gives us no value to inject
253                     if (value != null) {
254                         args[i] = value;
255                     }
256                 }
257             }
258             final Collection<ConstraintValidator<?>> validators =
259                 ConstraintValidators.findValidators(annotations[i]);
260             final Object value = args[i];
261             final String argName = "arg[" + i + "](" + simpleName(value) + ")";
262             for (final ConstraintValidator<?> validator : validators) {
263                 if (!validator.isValid(argName, value)) {
264                     invalid = true;
265                 }
266             }
267         }
268         log.append(log.length() == 0 ? factory.getName() + "()" : ")");
269         checkForRemainingAttributes();
270         verifyNodeChildrenUsed();
271         LOGGER.debug(log.toString());
272         if (invalid) {
273             throw new ConfigurationException("Arguments given for element " + node.getName() + " are invalid");
274         }
275         return args;
276     }
277 
278     private static String[] extractPluginAliases(final Annotation... parmTypes) {
279         String[] aliases = null;
280         for (final Annotation a : parmTypes) {
281             if (a instanceof PluginAliases) {
282                 aliases = ((PluginAliases) a).value();
283             }
284         }
285         return aliases;
286     }
287 
288     private void checkForRemainingAttributes() {
289         final Map<String, String> attrs = node.getAttributes();
290         if (!attrs.isEmpty()) {
291             final StringBuilder sb = new StringBuilder();
292             for (final String key : attrs.keySet()) {
293                 if (sb.length() == 0) {
294                     sb.append(node.getName());
295                     sb.append(" contains ");
296                     if (attrs.size() == 1) {
297                         sb.append("an invalid element or attribute ");
298                     } else {
299                         sb.append("invalid attributes ");
300                     }
301                 } else {
302                     sb.append(", ");
303                 }
304                 StringBuilders.appendDqValue(sb, key);
305             }
306             LOGGER.error(sb.toString());
307         }
308     }
309 
310     private void verifyNodeChildrenUsed() {
311         final List<Node> children = node.getChildren();
312         if (!(pluginType.isDeferChildren() || children.isEmpty())) {
313             for (final Node child : children) {
314                 final String nodeType = node.getType().getElementName();
315                 final String start = nodeType.equals(node.getName()) ? node.getName() : nodeType + ' ' + node.getName();
316                 LOGGER.error("{} has no parameter that matches element {}", start, child.getName());
317             }
318         }
319     }
320 }