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