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