1/*
2 * Copyright (c) 2006, 2015, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 */
23
24/*
25 * @test
26 * @bug 6397298 6400986 6425592 6449798 6453386 6508401 6498938 6911854 8030049 8038080 8032230
27 * @summary Tests that getElementsAnnotatedWith works properly.
28 * @author  Joseph D. Darcy
29 * @library /tools/javac/lib
30 * @modules java.compiler
31 *          jdk.compiler
32 * @build   JavacTestingAbstractProcessor
33 * @compile TestElementsAnnotatedWith.java
34 * @compile InheritedAnnotation.java
35 * @compile TpAnno.java
36 * @compile Anno.java
37 * @compile -processor TestElementsAnnotatedWith -proc:only SurfaceAnnotations.java
38 * @compile -processor TestElementsAnnotatedWith -proc:only BuriedAnnotations.java
39 * @compile -processor TestElementsAnnotatedWith -proc:only Part1.java Part2.java
40 * @compile -processor TestElementsAnnotatedWith -proc:only C2.java
41 * @compile -processor TestElementsAnnotatedWith -proc:only Foo.java
42 * @compile -processor TestElementsAnnotatedWith -proc:only TypeParameterAnnotations.java
43 * @compile -processor TestElementsAnnotatedWith -proc:only ParameterAnnotations.java
44 * @compile/fail/ref=ErroneousAnnotations.out -processor TestElementsAnnotatedWith -proc:only -XDrawDiagnostics ErroneousAnnotations.java
45 * @compile Foo.java
46 * @compile/process -processor TestElementsAnnotatedWith -proc:only Foo
47 */
48
49import java.lang.annotation.Annotation;
50import java.util.Collections;
51import java.util.Set;
52import java.util.HashSet;
53import java.util.Arrays;
54import java.util.Objects;
55import javax.annotation.processing.*;
56import javax.lang.model.element.*;
57import static javax.lang.model.util.ElementFilter.*;
58
59/**
60 * This processor verifies that the information returned by
61 * getElementsAnnotatedWith and getElementsAnnotatedWithAny is
62 * consistent with the expected results stored in an
63 * AnnotatedElementInfo annotation.
64 */
65@AnnotatedElementInfo(annotationName="java.lang.SuppressWarnings", expectedSize=0, names={})
66public class TestElementsAnnotatedWith extends JavacTestingAbstractProcessor {
67
68    public boolean process(Set<? extends TypeElement> annotations,
69                           RoundEnvironment roundEnv) {
70        // First check sets of annotated elements using the round
71        // environment from the annotation processing tool framework.
72        checkSetOfAnnotatedElements(roundEnv);
73
74        // Next check sets of annotated elements using a round
75        // environment which uses the default implementations of the
76        // getElementsAnnotatedWithAny methods from the interface.
77        checkSetOfAnnotatedElements(new TestingRoundEnvironment(roundEnv));
78        return true;
79    }
80
81    /**
82     * To allow testing of the executable code of the default methods
83     * for the two overloaded getElementsAnnotatedWithAny methods
84     * defined in the RoundEnvironment interface, this class delegates
85     * the non-default methods of RoundEnvironment to a given
86     * RoundEnvironment object and then explicitly calls the default
87     * methods of the interface instead of relying on the object's
88     * implementation of those methods.
89     */
90    private class TestingRoundEnvironment implements RoundEnvironment {
91        private RoundEnvironment re;
92
93        public TestingRoundEnvironment(RoundEnvironment re) {
94            this.re = re;
95        }
96
97        @Override
98        public boolean errorRaised() {
99            return re.errorRaised();
100        }
101
102        @Override
103        public Set<? extends Element> getElementsAnnotatedWith(Class<? extends Annotation> a) {
104            return re.getElementsAnnotatedWith(a);
105        }
106
107        @Override
108        public Set<? extends Element> getElementsAnnotatedWithAny(Set<Class<? extends Annotation>> a) {
109            // Default method defined in the interface
110            return RoundEnvironment.super.getElementsAnnotatedWithAny(a);
111        }
112
113        @Override
114        public Set<? extends Element> getElementsAnnotatedWith(TypeElement a) {
115            return re.getElementsAnnotatedWith(a);
116        }
117
118        @Override
119        public Set<? extends Element> getElementsAnnotatedWithAny(TypeElement... a) {
120            // Default method defined in the interface
121            return RoundEnvironment.super.getElementsAnnotatedWithAny(a);
122        }
123
124        @Override
125        public Set<? extends Element> getRootElements() {
126            return re.getRootElements();
127        }
128
129        @Override
130        public boolean processingOver() {
131            return re.processingOver();
132        }
133
134    }
135
136    /**
137     * The method checks the following conditions:
138     *
139     * 1) The sets of elements found are equal for the TypeElement and
140     * Class<? extends Annotation> methods on logically equivalent
141     * arguments.
142     *
143     * 2) getElementsAnnotatedWithAny(X) is equal to
144     * getElementsAnnotatedWith(X') where X is a set/var-args array
145     * with one element and X' is the element.
146     *
147     * 3) Verify the result of getElementsAnnotatedWithAny({X, Y}) is equal to
148     * getElementsAnnotatedWith(X) UNION getElementsAnnotatedWith(Y).
149     */
150    void checkSetOfAnnotatedElements(RoundEnvironment re) {
151        TypeElement annotatedElemInfoElem =  elements.getTypeElement("AnnotatedElementInfo");
152
153        // For the "Any" methods, search for both the expected
154        // annotation and AnnotatedElementInfo and verify the return
155        // set is the union of searching for AnnotatedElementInfo and
156        // the other annotation
157        Set<? extends Element> resultsMeta         = Collections.emptySet();
158        Set<? extends Element> resultsMetaAny      = Collections.emptySet();
159        Set<Element>           resultsMetaMulti    = new HashSet<>();
160        Set<? extends Element> resultsMetaAnyMulti = Collections.emptySet();
161        Set<? extends Element> resultsBase         = Collections.emptySet();
162        Set<? extends Element> resultsBaseAny      = Collections.emptySet();
163        Set<? extends Element> resultsBaseAnyMulti = Collections.emptySet();
164
165        if (!re.processingOver()) {
166            testNonAnnotations(re);
167
168            // Verify AnnotatedElementInfo is present on the first
169            // specified type.
170
171            TypeElement firstType = typesIn(re.getRootElements()).iterator().next();
172
173            AnnotatedElementInfo annotatedElemInfo =
174                firstType.getAnnotation(AnnotatedElementInfo.class);
175
176            boolean failed = false;
177
178            Objects.requireNonNull(annotatedElemInfo,
179                                   "Missing AnnotatedElementInfo annotation on " + firstType);
180
181            // Verify that the annotation information is as expected.
182            Set<String> expectedNames =
183                new HashSet<>(Arrays.asList(annotatedElemInfo.names()));
184
185            String annotationName = annotatedElemInfo.annotationName();
186            TypeElement annotationTypeElem = elements.getTypeElement(annotationName);
187
188            resultsMeta         = re.getElementsAnnotatedWith(annotationTypeElem);
189            resultsMetaAny      = re.getElementsAnnotatedWithAny(annotationTypeElem);
190            resultsMetaMulti.addAll(resultsMeta);
191            resultsMetaMulti.addAll(re.getElementsAnnotatedWith(annotatedElemInfoElem));
192            resultsMetaAnyMulti = re.getElementsAnnotatedWithAny(annotationTypeElem, annotatedElemInfoElem);
193
194            if (!resultsMeta.isEmpty())
195                System.err.println("Results: " + resultsMeta);
196
197            if (!resultsMeta.equals(resultsMetaAny)) {
198                failed = true;
199                System.err.printf("Inconsistent Meta with vs withAny results");
200            }
201
202            if (resultsMeta.size() != annotatedElemInfo.expectedSize()) {
203                failed = true;
204                System.err.printf("Bad number of elements; expected %d, got %d%n",
205                                  annotatedElemInfo.expectedSize(), resultsMeta.size());
206            } else {
207                for(Element element : resultsMeta) {
208                    String simpleName = element.getSimpleName().toString();
209                    if (!expectedNames.contains(simpleName) ) {
210                        failed = true;
211                        System.err.println("Name ``" + simpleName + "'' not expected.");
212                    }
213                }
214            }
215
216            resultsBase    = computeResultsBase(re, annotationName);
217            resultsBaseAny = computeResultsBaseAny(re, annotationName);
218            try {
219                Set<Class<? extends Annotation>> tmp = new HashSet<>();
220                tmp.add(AnnotatedElementInfo.class);
221                tmp.add(Class.forName(annotationName).asSubclass(Annotation.class));
222                resultsBaseAnyMulti = re.getElementsAnnotatedWithAny(tmp);
223            } catch (ClassNotFoundException e) {
224                throw new RuntimeException(e);
225            }
226
227            if (!resultsBase.equals(resultsBaseAny)) {
228                failed = true;
229                System.err.printf("Inconsistent Base with vs withAny results");
230            }
231
232            if (!resultsMeta.equals(resultsBase)) {
233                failed = true;
234                System.err.println("Base and Meta sets unequal;\n meta: " + resultsMeta +
235                                   "\nbase: " + resultsBase);
236            }
237
238            if (!resultsMetaAnyMulti.equals(resultsMetaMulti)) {
239                failed = true;
240                System.err.println("MetaMultAny and MetaMulti sets unequal;\n meta: " + resultsMeta +
241                                   "\nbase: " + resultsBase);
242            }
243
244            if (!resultsBaseAnyMulti.equals(resultsMetaAnyMulti)) {
245                failed = true;
246                System.err.println("BaseMulti and MetaMulti sets unequal;\n meta: " + resultsMeta +
247                                   "\nbase: " + resultsBase);
248            }
249
250            if (failed) {
251                System.err.println("AnnotatedElementInfo: " + annotatedElemInfo);
252                throw new RuntimeException();
253            }
254        } else {
255            // If processing is over without an error, the specified
256            // elements should be empty so an empty set should be
257            // returned.
258            throwOnNonEmpty(re.getElementsAnnotatedWith(annotatedElemInfoElem), "resultsMeta");
259            throwOnNonEmpty(re.getElementsAnnotatedWithAny(annotatedElemInfoElem), "resultsMetaAny");
260            throwOnNonEmpty(re.getElementsAnnotatedWith(AnnotatedElementInfo.class),    "resultsBase");
261            throwOnNonEmpty(re.getElementsAnnotatedWithAny(Set.of(AnnotatedElementInfo.class)), "resultsBaseAny");
262        }
263    }
264
265    private void throwOnNonEmpty(Set<? extends Element> results, String message) {
266        if (!results.isEmpty()) {
267                throw new RuntimeException("Nonempty " + message +  "\t"  + results);
268        }
269    }
270
271    private Set<? extends Element> computeResultsBase(RoundEnvironment roundEnv, String name) {
272        try {
273            return roundEnv.
274                getElementsAnnotatedWith(Class.forName(name).asSubclass(Annotation.class));
275        } catch (ClassNotFoundException cnfe) {
276            throw new RuntimeException(cnfe);
277        }
278    }
279
280    private Set<? extends Element> computeResultsBaseAny(RoundEnvironment roundEnv, String name) {
281        try {
282            return roundEnv.
283                getElementsAnnotatedWithAny(Set.of(Class.forName(name).asSubclass(Annotation.class)));
284        } catch (ClassNotFoundException cnfe) {
285            throw new RuntimeException(cnfe);
286        }
287    }
288
289    /**
290     * Verify non-annotation types result in
291     * IllegalArgumentExceptions.
292     */
293    private void testNonAnnotations(RoundEnvironment roundEnv) {
294        Class objectClass = (Class)Object.class;
295        Set<? extends Element> elements;
296        try {
297            elements = roundEnv.getElementsAnnotatedWith(objectClass);
298            throw new RuntimeException("Illegal argument exception not thrown");
299        } catch (IllegalArgumentException iae) {}
300
301        try {
302            elements = roundEnv.getElementsAnnotatedWithAny(Set.of(objectClass));
303            throw new RuntimeException("Illegal argument exception not thrown");
304        } catch (IllegalArgumentException iae) {}
305
306        TypeElement objectElement = processingEnv.getElementUtils().getTypeElement("java.lang.Object");
307        try {
308            elements = roundEnv.getElementsAnnotatedWith(objectElement);
309            throw new RuntimeException("Illegal argument exception not thrown");
310        } catch (IllegalArgumentException iae) {}
311
312        try {
313            elements = roundEnv.getElementsAnnotatedWithAny(objectElement);
314            throw new RuntimeException("Illegal argument exception not thrown");
315        } catch (IllegalArgumentException iae) {}
316    }
317}
318