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.Collection;
027import java.util.List;
028import java.util.Map;
029import java.util.Objects;
030
031import org.apache.logging.log4j.Logger;
032import org.apache.logging.log4j.core.LogEvent;
033import org.apache.logging.log4j.core.config.Configuration;
034import org.apache.logging.log4j.core.config.ConfigurationException;
035import org.apache.logging.log4j.core.config.Node;
036import org.apache.logging.log4j.core.config.plugins.PluginAliases;
037import org.apache.logging.log4j.core.config.plugins.PluginBuilderFactory;
038import org.apache.logging.log4j.core.config.plugins.PluginFactory;
039import org.apache.logging.log4j.core.config.plugins.validation.ConstraintValidator;
040import org.apache.logging.log4j.core.config.plugins.validation.ConstraintValidators;
041import org.apache.logging.log4j.core.config.plugins.visitors.PluginVisitor;
042import org.apache.logging.log4j.core.config.plugins.visitors.PluginVisitors;
043import org.apache.logging.log4j.core.util.Builder;
044import org.apache.logging.log4j.core.util.ReflectionUtil;
045import org.apache.logging.log4j.core.util.TypeUtil;
046import org.apache.logging.log4j.status.StatusLogger;
047import org.apache.logging.log4j.util.StringBuilders;
048
049/**
050 * Builder class to instantiate and configure a Plugin object using a PluginFactory method or PluginBuilderFactory
051 * builder class.
052 */
053public class PluginBuilder implements Builder<Object> {
054
055    private static final Logger LOGGER = StatusLogger.getLogger();
056
057    private final PluginType<?> pluginType;
058    private final Class<?> clazz;
059
060    private Configuration configuration;
061    private Node node;
062    private LogEvent event;
063
064    /**
065     * Constructs a PluginBuilder for a given PluginType.
066     *
067     * @param pluginType type of plugin to configure
068     */
069    public PluginBuilder(final PluginType<?> pluginType) {
070        this.pluginType = pluginType;
071        this.clazz = pluginType.getPluginClass();
072    }
073
074    /**
075     * Specifies the Configuration to use for constructing the plugin instance.
076     *
077     * @param configuration the configuration to use.
078     * @return {@code this}
079     */
080    public PluginBuilder withConfiguration(final Configuration configuration) {
081        this.configuration = configuration;
082        return this;
083    }
084
085    /**
086     * Specifies the Node corresponding to the plugin object that will be created.
087     *
088     * @param node the plugin configuration node to use.
089     * @return {@code this}
090     */
091    public PluginBuilder withConfigurationNode(final Node node) {
092        this.node = node;
093        return this;
094    }
095
096    /**
097     * Specifies the LogEvent that may be used to provide extra context for string substitutions.
098     *
099     * @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}