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.visitors; 19 20 import java.lang.annotation.Annotation; 21 22 import org.apache.logging.log4j.Logger; 23 import org.apache.logging.log4j.core.config.plugins.PluginVisitorStrategy; 24 import org.apache.logging.log4j.status.StatusLogger; 25 26 /** 27 * Utility class to locate an appropriate PluginVisitor implementation for an annotation. 28 */ 29 public final class PluginVisitors { 30 31 private static final Logger LOGGER = StatusLogger.getLogger(); 32 33 private PluginVisitors() { 34 } 35 36 /** 37 * Creates a PluginVisitor instance for the given annotation class using metadata provided by the annotation's 38 * {@link PluginVisitorStrategy} annotation. This instance must be further populated with 39 * data to be useful. Such data is passed through both the setters and the visit method. 40 * 41 * @param annotation the Plugin annotation class to find a PluginVisitor for. 42 * @param <A> the Plugin annotation type. 43 * @return a PluginVisitor instance if one could be created, or {@code null} otherwise. 44 */ 45 @SuppressWarnings("unchecked") // we're keeping track of types, thanks 46 public static <A extends Annotation> PluginVisitor<A> findVisitor(final Class<A> annotation) { 47 final PluginVisitorStrategy strategy = annotation.getAnnotation(PluginVisitorStrategy.class); 48 if (strategy == null) { 49 LOGGER.debug("No PluginVisitorStrategy found on annotation [{}]. Ignoring.", annotation); 50 return null; 51 } 52 final Class<? extends PluginVisitor<A>> visitorClass = (Class<? extends PluginVisitor<A>>) strategy.value(); 53 try { 54 return visitorClass.newInstance(); 55 } catch (final Exception e) { 56 LOGGER.error("Error loading PluginVisitor [{}] for annotation [{}].", visitorClass, annotation, e); 57 return null; 58 } 59 } 60 }