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.visitors;
019
020import java.lang.annotation.Annotation;
021
022import org.apache.logging.log4j.Logger;
023import org.apache.logging.log4j.core.config.plugins.PluginVisitorStrategy;
024import org.apache.logging.log4j.status.StatusLogger;
025
026/**
027 * Utility class to locate an appropriate {@link PluginVisitor} implementation for an annotation.
028 */
029public 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     * @return a PluginVisitor instance if one could be created, or {@code null} otherwise.
043     */
044    public static PluginVisitor<? extends Annotation> findVisitor(final Class<? extends Annotation> annotation) {
045        final PluginVisitorStrategy strategy = annotation.getAnnotation(PluginVisitorStrategy.class);
046        if (strategy == null) {
047            LOGGER.debug("No PluginVisitorStrategy found on annotation [{}]. Ignoring.", annotation);
048            return null;
049        }
050        try {
051            return strategy.value().newInstance();
052        } catch (final Exception e) {
053            LOGGER.error("Error loading PluginVisitor [{}] for annotation [{}].", strategy.value(), annotation, e);
054            return null;
055        }
056    }
057}