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 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}