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