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