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 018 package org.apache.logging.log4j.core.config.plugins.visitors; 019 020 import java.lang.annotation.Annotation; 021 022 import org.apache.logging.log4j.Logger; 023 import org.apache.logging.log4j.core.config.plugins.PluginVisitorStrategy; 024 import org.apache.logging.log4j.status.StatusLogger; 025 026 /** 027 * Utility class to locate an appropriate PluginVisitor implementation for an annotation. 028 */ 029 public final class PluginVisitors { 030 031 private static final Logger LOGGER = StatusLogger.getLogger(); 032 033 private PluginVisitors() { 034 } 035 036 /** 037 * Creates a PluginVisitor instance for the given annotation class using metadata provided by the annotation's 038 * {@link PluginVisitorStrategy} annotation. This instance must be further populated with 039 * data to be useful. Such data is passed through both the setters and the visit method. 040 * 041 * @param annotation the Plugin annotation class to find a PluginVisitor for. 042 * @param <A> the Plugin annotation type. 043 * @return a PluginVisitor instance if one could be created, or {@code null} otherwise. 044 */ 045 @SuppressWarnings("unchecked") // we're keeping track of types, thanks 046 public static <A extends Annotation> PluginVisitor<A> findVisitor(final Class<A> annotation) { 047 final PluginVisitorStrategy strategy = annotation.getAnnotation(PluginVisitorStrategy.class); 048 if (strategy == null) { 049 LOGGER.debug("No PluginVisitorStrategy found on annotation [{}]. Ignoring.", annotation); 050 return null; 051 } 052 final Class<? extends PluginVisitor<A>> visitorClass = (Class<? extends PluginVisitor<A>>) strategy.value(); 053 try { 054 return visitorClass.newInstance(); 055 } catch (final Exception e) { 056 LOGGER.error("Error loading PluginVisitor [{}] for annotation [{}].", visitorClass, annotation, e); 057 return null; 058 } 059 } 060 }