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.processor;
019
020import java.io.IOException;
021import java.io.OutputStream;
022import java.util.ArrayList;
023import java.util.Collection;
024import java.util.Collections;
025import java.util.Locale;
026import java.util.Map;
027import java.util.Objects;
028import java.util.Set;
029import javax.annotation.processing.AbstractProcessor;
030import javax.annotation.processing.Messager;
031import javax.annotation.processing.RoundEnvironment;
032import javax.annotation.processing.SupportedAnnotationTypes;
033import javax.lang.model.SourceVersion;
034import javax.lang.model.element.Element;
035import javax.lang.model.element.ElementVisitor;
036import javax.lang.model.element.TypeElement;
037import javax.lang.model.util.Elements;
038import javax.lang.model.util.SimpleElementVisitor7;
039import javax.tools.Diagnostic.Kind;
040import javax.tools.FileObject;
041import javax.tools.StandardLocation;
042
043import org.apache.logging.log4j.core.config.plugins.Plugin;
044import org.apache.logging.log4j.core.config.plugins.PluginAliases;
045import org.apache.logging.log4j.util.Strings;
046
047/**
048 * Annotation processor for pre-scanning Log4j 2 plugins.
049 */
050@SupportedAnnotationTypes("org.apache.logging.log4j.core.config.plugins.*")
051public class PluginProcessor extends AbstractProcessor {
052
053    // TODO: this could be made more abstract to allow for compile-time and run-time plugin processing
054
055    /**
056     * The location of the plugin cache data file. This file is written to by this processor, and read from by
057     * {@link org.apache.logging.log4j.core.config.plugins.util.PluginManager}.
058     */
059    public static final String PLUGIN_CACHE_FILE =
060            "META-INF/org/apache/logging/log4j/core/config/plugins/Log4j2Plugins.dat";
061
062    private final PluginCache pluginCache = new PluginCache();
063
064    @Override
065    public SourceVersion getSupportedSourceVersion() {
066        return SourceVersion.latest();
067    }
068
069    @Override
070    public boolean process(final Set<? extends TypeElement> annotations, final RoundEnvironment roundEnv) {
071        Messager messager = processingEnv.getMessager();
072        messager.printMessage(Kind.NOTE, "Processing Log4j annotations");
073        try {
074            final Set<? extends Element> elements = roundEnv.getElementsAnnotatedWith(Plugin.class);
075            if (elements.isEmpty()) {
076                messager.printMessage(Kind.NOTE, "No elements to process");
077                return false;
078            }
079            collectPlugins(elements);
080            writeCacheFile(elements.toArray(new Element[elements.size()]));
081            messager.printMessage(Kind.NOTE, "Annotations processed");
082            return true;
083        } catch (final Exception ex) {
084            ex.printStackTrace();
085            error(ex.getMessage());
086            return false;
087        }
088    }
089
090    private void error(final CharSequence message) {
091        processingEnv.getMessager().printMessage(Kind.ERROR, message);
092    }
093
094    private void collectPlugins(final Iterable<? extends Element> elements) {
095        final Elements elementUtils = processingEnv.getElementUtils();
096        final ElementVisitor<PluginEntry, Plugin> pluginVisitor = new PluginElementVisitor(elementUtils);
097        final ElementVisitor<Collection<PluginEntry>, Plugin> pluginAliasesVisitor = new PluginAliasesElementVisitor(
098                elementUtils);
099        for (final Element element : elements) {
100            final Plugin plugin = element.getAnnotation(Plugin.class);
101            if (plugin == null) {
102                continue;
103            }
104            final PluginEntry entry = element.accept(pluginVisitor, plugin);
105            final Map<String, PluginEntry> category = pluginCache.getCategory(entry.getCategory());
106            category.put(entry.getKey(), entry);
107            final Collection<PluginEntry> entries = element.accept(pluginAliasesVisitor, plugin);
108            for (final PluginEntry pluginEntry : entries) {
109                category.put(pluginEntry.getKey(), pluginEntry);
110            }
111        }
112    }
113
114    private void writeCacheFile(final Element... elements) throws IOException {
115        final FileObject fileObject = processingEnv.getFiler().createResource(StandardLocation.CLASS_OUTPUT, Strings.EMPTY,
116                PLUGIN_CACHE_FILE, elements);
117        try (final OutputStream out = fileObject.openOutputStream()) {
118            pluginCache.writeCache(out);
119        }
120    }
121
122    /**
123     * ElementVisitor to scan the Plugin annotation.
124     */
125    private static class PluginElementVisitor extends SimpleElementVisitor7<PluginEntry, Plugin> {
126
127        private final Elements elements;
128
129        private PluginElementVisitor(final Elements elements) {
130            this.elements = elements;
131        }
132
133        @Override
134        public PluginEntry visitType(final TypeElement e, final Plugin plugin) {
135            Objects.requireNonNull(plugin, "Plugin annotation is null.");
136            final PluginEntry entry = new PluginEntry();
137            entry.setKey(plugin.name().toLowerCase(Locale.US));
138            entry.setClassName(elements.getBinaryName(e).toString());
139            entry.setName(Plugin.EMPTY.equals(plugin.elementType()) ? plugin.name() : plugin.elementType());
140            entry.setPrintable(plugin.printObject());
141            entry.setDefer(plugin.deferChildren());
142            entry.setCategory(plugin.category());
143            return entry;
144        }
145    }
146
147    /**
148     * ElementVisitor to scan the PluginAliases annotation.
149     */
150    private static class PluginAliasesElementVisitor extends SimpleElementVisitor7<Collection<PluginEntry>, Plugin> {
151
152        private final Elements elements;
153
154        private PluginAliasesElementVisitor(final Elements elements) {
155            super(Collections.<PluginEntry> emptyList());
156            this.elements = elements;
157        }
158
159        @Override
160        public Collection<PluginEntry> visitType(final TypeElement e, final Plugin plugin) {
161            final PluginAliases aliases = e.getAnnotation(PluginAliases.class);
162            if (aliases == null) {
163                return DEFAULT_VALUE;
164            }
165            final Collection<PluginEntry> entries = new ArrayList<>(aliases.value().length);
166            for (final String alias : aliases.value()) {
167                final PluginEntry entry = new PluginEntry();
168                entry.setKey(alias.toLowerCase(Locale.US));
169                entry.setClassName(elements.getBinaryName(e).toString());
170                entry.setName(Plugin.EMPTY.equals(plugin.elementType()) ? alias : plugin.elementType());
171                entry.setPrintable(plugin.printObject());
172                entry.setDefer(plugin.deferChildren());
173                entry.setCategory(plugin.category());
174                entries.add(entry);
175            }
176            return entries;
177        }
178    }
179}