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