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 */
017
018package org.apache.logging.log4j.core.config.plugins.util;
019
020import java.lang.annotation.Annotation;
021import java.lang.reflect.AccessibleObject;
022import java.lang.reflect.Field;
023import java.lang.reflect.InvocationTargetException;
024import java.lang.reflect.Method;
025import java.lang.reflect.Modifier;
026import java.util.ArrayList;
027import java.util.Collection;
028import java.util.List;
029import java.util.Map;
030import java.util.Objects;
031
032import org.apache.logging.log4j.Logger;
033import org.apache.logging.log4j.core.LogEvent;
034import org.apache.logging.log4j.core.config.Configuration;
035import org.apache.logging.log4j.core.config.ConfigurationException;
036import org.apache.logging.log4j.core.config.Node;
037import org.apache.logging.log4j.core.config.plugins.PluginAliases;
038import org.apache.logging.log4j.core.config.plugins.PluginBuilderFactory;
039import org.apache.logging.log4j.core.config.plugins.PluginFactory;
040import org.apache.logging.log4j.core.config.plugins.validation.ConstraintValidator;
041import org.apache.logging.log4j.core.config.plugins.validation.ConstraintValidators;
042import org.apache.logging.log4j.core.config.plugins.visitors.PluginVisitor;
043import org.apache.logging.log4j.core.config.plugins.visitors.PluginVisitors;
044import org.apache.logging.log4j.core.util.Builder;
045import org.apache.logging.log4j.core.util.ReflectionUtil;
046import org.apache.logging.log4j.core.util.TypeUtil;
047import org.apache.logging.log4j.status.StatusLogger;
048import org.apache.logging.log4j.util.StringBuilders;
049
050/**
051 * Builder class to instantiate and configure a Plugin object using a PluginFactory method or PluginBuilderFactory
052 * builder class.
053 */
054public class PluginBuilder implements Builder<Object> {
055
056    private static final Logger LOGGER = StatusLogger.getLogger();
057
058    private final PluginType<?> pluginType;
059    private final Class<?> clazz;
060
061    private Configuration configuration;
062    private Node node;
063    private LogEvent event;
064
065    /**
066     * Constructs a PluginBuilder for a given PluginType.
067     *
068     * @param pluginType type of plugin to configure
069     */
070    public PluginBuilder(final PluginType<?> pluginType) {
071        this.pluginType = pluginType;
072        this.clazz = pluginType.getPluginClass();
073    }
074
075    /**
076     * Specifies the Configuration to use for constructing the plugin instance.
077     *
078     * @param configuration the configuration to use.
079     * @return {@code this}
080     */
081    public PluginBuilder withConfiguration(final Configuration configuration) {
082        this.configuration = configuration;
083        return this;
084    }
085
086    /**
087     * Specifies the Node corresponding to the plugin object that will be created.
088     *
089     * @param node the plugin configuration node to use.
090     * @return {@code this}
091     */
092    public PluginBuilder withConfigurationNode(final Node node) {
093        this.node = node;
094        return this;
095    }
096
097    /**
098     * Specifies the LogEvent that may be used to provide extra context for string substitutions.
099     *
100     * @param event the event to use for extra information.
101     * @return {@code this}
102     */
103    public PluginBuilder forLogEvent(final LogEvent event) {
104        this.event = event;
105        return this;
106    }
107
108    /**
109     * Builds the plugin object.
110     *
111     * @return the plugin object or {@code null} if there was a problem creating it.
112     */
113    @Override
114    public Object build() {
115        verify();
116        // first try to use a builder class if one is available
117        try {
118            LOGGER.debug("Building Plugin[name={}, class={}].", pluginType.getElementName(),
119                    pluginType.getPluginClass().getName());
120            final Builder<?> builder = createBuilder(this.clazz);
121            if (builder != null) {
122                injectFields(builder);
123                return builder.build();
124            }
125        } catch (final ConfigurationException e) { // LOG4J2-1908
126            LOGGER.error("Could not create plugin of type {} for element {}", this.clazz, node.getName(), e);
127            return null; // no point in trying the factory method
128        } catch (final Exception e) {
129            LOGGER.error("Could not create plugin of type {} for element {}: {}",
130                    this.clazz, node.getName(),
131                    (e instanceof InvocationTargetException ? ((InvocationTargetException) e).getCause() : e).toString(), e);
132        }
133        // or fall back to factory method if no builder class is available
134        try {
135            final Method factory = findFactoryMethod(this.clazz);
136            final Object[] params = generateParameters(factory);
137            return factory.invoke(null, params);
138        } catch (final Exception e) {
139            LOGGER.error("Unable to invoke factory method in {} for element {}: {}",
140                    this.clazz, this.node.getName(),
141                    (e instanceof InvocationTargetException ? ((InvocationTargetException) e).getCause() : e).toString(), e);
142            return null;
143        }
144    }
145
146    private void verify() {
147        Objects.requireNonNull(this.configuration, "No Configuration object was set.");
148        Objects.requireNonNull(this.node, "No Node object was set.");
149    }
150
151    private static Builder<?> createBuilder(final Class<?> clazz)
152        throws InvocationTargetException, IllegalAccessException {
153        for (final Method method : clazz.getDeclaredMethods()) {
154            if (method.isAnnotationPresent(PluginBuilderFactory.class) &&
155                Modifier.isStatic(method.getModifiers()) &&
156                TypeUtil.isAssignable(Builder.class, method.getReturnType())) {
157                ReflectionUtil.makeAccessible(method);
158                return (Builder<?>) method.invoke(null);
159            }
160        }
161        return null;
162    }
163
164    private void injectFields(final Builder<?> builder) throws IllegalAccessException {
165        final List<Field> fields = TypeUtil.getAllDeclaredFields(builder.getClass());
166        AccessibleObject.setAccessible(fields.toArray(new Field[] {}), true);
167        final StringBuilder log = new StringBuilder();
168        boolean invalid = false;
169        String reason = "";
170        for (final Field field : fields) {
171            log.append(log.length() == 0 ? simpleName(builder) + "(" : ", ");
172            final Annotation[] annotations = field.getDeclaredAnnotations();
173            final String[] aliases = extractPluginAliases(annotations);
174            for (final Annotation a : annotations) {
175                if (a instanceof PluginAliases) {
176                    continue; // already processed
177                }
178                final PluginVisitor<? extends Annotation> visitor =
179                    PluginVisitors.findVisitor(a.annotationType());
180                if (visitor != null) {
181                    final Object value = visitor.setAliases(aliases)
182                        .setAnnotation(a)
183                        .setConversionType(field.getType())
184                        .setStrSubstitutor(configuration.getStrSubstitutor())
185                        .setMember(field)
186                        .visit(configuration, node, event, log);
187                    // don't overwrite default values if the visitor gives us no value to inject
188                    if (value != null) {
189                        field.set(builder, value);
190                    }
191                }
192            }
193            final Collection<ConstraintValidator<?>> validators =
194                ConstraintValidators.findValidators(annotations);
195            final Object value = field.get(builder);
196            for (final ConstraintValidator<?> validator : validators) {
197                if (!validator.isValid(field.getName(), value)) {
198                    invalid = true;
199                    if (!reason.isEmpty()) {
200                        reason += ", ";
201                    }
202                    reason += "field '" + field.getName() + "' has invalid value '" + value + "'";
203                }
204            }
205        }
206        log.append(log.length() == 0 ? builder.getClass().getSimpleName() + "()" : ")");
207        LOGGER.debug(log.toString());
208        if (invalid) {
209            throw new ConfigurationException("Arguments given for element " + node.getName() + " are invalid: " + reason);
210        }
211        checkForRemainingAttributes();
212        verifyNodeChildrenUsed();
213    }
214
215    /**
216     * {@code object.getClass().getSimpleName()} returns {@code Builder}, when we want {@code PatternLayout$Builder}.
217     */
218    private static String simpleName(final Object object) {
219        if (object == null) {
220            return "null";
221        }
222        final String cls = object.getClass().getName();
223        final int index = cls.lastIndexOf('.');
224        return index < 0 ? cls : cls.substring(index + 1);
225    }
226
227    private static Method findFactoryMethod(final Class<?> clazz) {
228        for (final Method method : clazz.getDeclaredMethods()) {
229            if (method.isAnnotationPresent(PluginFactory.class) &&
230                Modifier.isStatic(method.getModifiers())) {
231                ReflectionUtil.makeAccessible(method);
232                return method;
233            }
234        }
235        throw new IllegalStateException("No factory method found for class " + clazz.getName());
236    }
237
238    private Object[] generateParameters(final Method factory) {
239        final StringBuilder log = new StringBuilder();
240        final Class<?>[] types = factory.getParameterTypes();
241        final Annotation[][] annotations = factory.getParameterAnnotations();
242        final Object[] args = new Object[annotations.length];
243        boolean invalid = false;
244        for (int i = 0; i < annotations.length; i++) {
245            log.append(log.length() == 0 ? factory.getName() + "(" : ", ");
246            final String[] aliases = extractPluginAliases(annotations[i]);
247            for (final Annotation a : annotations[i]) {
248                if (a instanceof PluginAliases) {
249                    continue; // already processed
250                }
251                final PluginVisitor<? extends Annotation> visitor = PluginVisitors.findVisitor(
252                    a.annotationType());
253                if (visitor != null) {
254                    final Object value = visitor.setAliases(aliases)
255                        .setAnnotation(a)
256                        .setConversionType(types[i])
257                        .setStrSubstitutor(configuration.getStrSubstitutor())
258                        .setMember(factory)
259                        .visit(configuration, node, event, log);
260                    // don't overwrite existing values if the visitor gives us no value to inject
261                    if (value != null) {
262                        args[i] = value;
263                    }
264                }
265            }
266            final Collection<ConstraintValidator<?>> validators =
267                ConstraintValidators.findValidators(annotations[i]);
268            final Object value = args[i];
269            final String argName = "arg[" + i + "](" + simpleName(value) + ")";
270            for (final ConstraintValidator<?> validator : validators) {
271                if (!validator.isValid(argName, value)) {
272                    invalid = true;
273                }
274            }
275        }
276        log.append(log.length() == 0 ? factory.getName() + "()" : ")");
277        checkForRemainingAttributes();
278        verifyNodeChildrenUsed();
279        LOGGER.debug(log.toString());
280        if (invalid) {
281            throw new ConfigurationException("Arguments given for element " + node.getName() + " are invalid");
282        }
283        return args;
284    }
285
286    private static String[] extractPluginAliases(final Annotation... parmTypes) {
287        String[] aliases = null;
288        for (final Annotation a : parmTypes) {
289            if (a instanceof PluginAliases) {
290                aliases = ((PluginAliases) a).value();
291            }
292        }
293        return aliases;
294    }
295
296    private void checkForRemainingAttributes() {
297        final Map<String, String> attrs = node.getAttributes();
298        if (!attrs.isEmpty()) {
299            final StringBuilder sb = new StringBuilder();
300            for (final String key : attrs.keySet()) {
301                if (sb.length() == 0) {
302                    sb.append(node.getName());
303                    sb.append(" contains ");
304                    if (attrs.size() == 1) {
305                        sb.append("an invalid element or attribute ");
306                    } else {
307                        sb.append("invalid attributes ");
308                    }
309                } else {
310                    sb.append(", ");
311                }
312                StringBuilders.appendDqValue(sb, key);
313            }
314            LOGGER.error(sb.toString());
315        }
316    }
317
318    private void verifyNodeChildrenUsed() {
319        final List<Node> children = node.getChildren();
320        if (!(pluginType.isDeferChildren() || children.isEmpty())) {
321            for (final Node child : children) {
322                final String nodeType = node.getType().getElementName();
323                final String start = nodeType.equals(node.getName()) ? node.getName() : nodeType + ' ' + node.getName();
324                LOGGER.error("{} has no parameter that matches element {}", start, child.getName());
325            }
326        }
327    }
328}