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;
028
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.SimpleElementVisitor6;
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        try {
071            final Set<? extends Element> elements = roundEnv.getElementsAnnotatedWith(Plugin.class);
072            if (elements.isEmpty()) {
073                return false;
074            }
075            collectPlugins(elements);
076            writeCacheFile(elements.toArray(new Element[elements.size()]));
077            return true;
078        } catch (final IOException e) {
079            error(e.getMessage());
080            return false;
081        }
082    }
083
084    private void error(final CharSequence message) {
085        processingEnv.getMessager().printMessage(Kind.ERROR, message);
086    }
087
088    private void collectPlugins(final Iterable<? extends Element> elements) {
089        final Elements elementUtils = processingEnv.getElementUtils();
090        final ElementVisitor<PluginEntry, Plugin> pluginVisitor = new PluginElementVisitor(elementUtils);
091        final ElementVisitor<Collection<PluginEntry>, Plugin> pluginAliasesVisitor = new PluginAliasesElementVisitor(
092                elementUtils);
093        for (final Element element : elements) {
094            final Plugin plugin = element.getAnnotation(Plugin.class);
095            final PluginEntry entry = element.accept(pluginVisitor, plugin);
096            final Map<String, PluginEntry> category = pluginCache.getCategory(entry.getCategory());
097            category.put(entry.getKey(), entry);
098            final Collection<PluginEntry> entries = element.accept(pluginAliasesVisitor, plugin);
099            for (final PluginEntry pluginEntry : entries) {
100                category.put(pluginEntry.getKey(), pluginEntry);
101            }
102        }
103    }
104
105    private void writeCacheFile(final Element... elements) throws IOException {
106        final FileObject fo = processingEnv.getFiler().createResource(StandardLocation.CLASS_OUTPUT, Strings.EMPTY,
107                PLUGIN_CACHE_FILE, elements);
108        try (final OutputStream out = fo.openOutputStream()) {
109            pluginCache.writeCache(out);
110        }
111    }
112
113    /**
114     * ElementVisitor to scan the Plugin annotation.
115     */
116    private static class PluginElementVisitor extends SimpleElementVisitor6<PluginEntry, Plugin> {
117
118        private final Elements elements;
119
120        private PluginElementVisitor(final Elements elements) {
121            this.elements = elements;
122        }
123
124        @Override
125        public PluginEntry visitType(final TypeElement e, final Plugin plugin) {
126            Objects.requireNonNull(plugin, "Plugin annotation is null.");
127            final PluginEntry entry = new PluginEntry();
128            entry.setKey(plugin.name().toLowerCase());
129            entry.setClassName(elements.getBinaryName(e).toString());
130            entry.setName(Plugin.EMPTY.equals(plugin.elementType()) ? plugin.name() : plugin.elementType());
131            entry.setPrintable(plugin.printObject());
132            entry.setDefer(plugin.deferChildren());
133            entry.setCategory(plugin.category());
134            return entry;
135        }
136    }
137
138    /**
139     * ElementVisitor to scan the PluginAliases annotation.
140     */
141    private static class PluginAliasesElementVisitor extends SimpleElementVisitor6<Collection<PluginEntry>, Plugin> {
142
143        private final Elements elements;
144
145        private PluginAliasesElementVisitor(final Elements elements) {
146            super(Collections.<PluginEntry> emptyList());
147            this.elements = elements;
148        }
149
150        @Override
151        public Collection<PluginEntry> visitType(final TypeElement e, final Plugin plugin) {
152            final PluginAliases aliases = e.getAnnotation(PluginAliases.class);
153            if (aliases == null) {
154                return DEFAULT_VALUE;
155            }
156            final Collection<PluginEntry> entries = new ArrayList<>(aliases.value().length);
157            for (final String alias : aliases.value()) {
158                final PluginEntry entry = new PluginEntry();
159                entry.setKey(alias.toLowerCase());
160                entry.setClassName(elements.getBinaryName(e).toString());
161                entry.setName(Plugin.EMPTY.equals(plugin.elementType()) ? alias : plugin.elementType());
162                entry.setPrintable(plugin.printObject());
163                entry.setDefer(plugin.deferChildren());
164                entry.setCategory(plugin.category());
165                entries.add(entry);
166            }
167            return entries;
168        }
169    }
170}