1 /*
   2  * Copyright (c) 2010, 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 6449781
  27  * @summary Test that reported names of anonymous classes are non-null.
  28  * @author  Joseph D. Darcy
  29  * @build TestAnonSourceNames
  30  * @compile -processor TestAnonSourceNames TestAnonClassNames.java
  31  * @run main TestAnonClassNames
  32  */
  33 
  34 /*
  35  * This test operates in phases to test retrieving the qualified name
  36  * of anonymous classes from type elements modeling the anonymous
  37  * class.  The type elements are generated using both source files and
  38  * class files as the basis of constructing the elements.
  39  *
  40  * Source files will be tested by the @compile line which runs
  41  * TestAnonSourceNames as an annotation processor over this file.
  42  *
  43  * Class files are tested by the @run command on this type.  This
  44  * class gets the names of classes with different nesting kinds,
  45  * including anonymous classes, and then invokes the compiler with an
  46  * annotation processor having the class files names as inputs.  The
  47  * compiler is invoked via the javax.tools mechanism.
  48  */
  49 
  50 import java.lang.annotation.*;
  51 import javax.lang.model.element.*;
  52 import javax.annotation.processing.*;
  53 import javax.lang.model.SourceVersion;
  54 import javax.lang.model.element.*;
  55 import javax.lang.model.util.*;
  56 import javax.tools.*;
  57 import java.util.*;
  58 
  59 import static java.lang.annotation.RetentionPolicy.*;
  60 import static javax.lang.model.element.NestingKind.*;
  61 import static javax.lang.model.util.ElementFilter.*;
  62 import static javax.tools.Diagnostic.Kind.*;
  63 import static javax.tools.StandardLocation.*;
  64 
  65 @Nesting(TOP_LEVEL)
  66 public class TestAnonClassNames {
  67     @Nesting(MEMBER)
  68     static class MemberClass1{}
  69 
  70     @Nesting(MEMBER)
  71     class MemberClass2{}
  72 
  73     @Nesting(MEMBER)
  74     class Win$$AtVegas { } // Class with funny name.
  75 
  76     public static void main(String... argv) {
  77         @Nesting(LOCAL)
  78         class LocalClass{};
  79 
  80         Object o =  new @Nesting(ANONYMOUS) Object() { // An anonymous annotated class
  81                 public String toString() {
  82                     return "I have no name!";
  83                 }
  84             };
  85 
  86         Class<?>[] classes = {
  87             MemberClass1.class,
  88             MemberClass2.class,
  89             LocalClass.class,
  90             Win$$AtVegas.class,
  91             o.getClass(),
  92             TestAnonClassNames.class,
  93         };
  94 
  95         for(Class<?> clazz : classes) {
  96             String name = clazz.getName();
  97             System.out.format("%s is %s%n",
  98                               clazz.getName(),
  99                               clazz.getAnnotation(Nesting.class).value());
 100             testClassName(name);
 101         }
 102     }
 103 
 104     /**
 105      * Perform annotation processing on the class file name and verify
 106      * the existence of different flavors of class names when the
 107      * input classes are modeled as elements.
 108      */
 109     static void testClassName(String className) {
 110         JavaCompiler javaCompiler = ToolProvider.getSystemJavaCompiler();
 111         List<String> classNames = new ArrayList<String>();
 112         classNames.add(className);
 113 
 114         List<String> options = new ArrayList<String>();
 115         options.add("-proc:only");
 116         options.add("-classpath");
 117         options.add(System.getProperty("test.classes"));
 118 
 119         JavaCompiler.CompilationTask compileTask =
 120             javaCompiler.getTask(null, // Output
 121                                  null, // File manager
 122                                  null, // Diagnostics
 123                                  options,
 124                                  classNames,
 125                                  null); // Sources
 126         List<Processor> processors = new ArrayList<Processor>();
 127         processors.add(new ClassNameProber());
 128         compileTask.setProcessors(processors);
 129         Boolean goodResult = compileTask.call();
 130         if (!goodResult) {
 131             throw new RuntimeException("Errors found during compile.");
 132         }
 133     }
 134 }
 135 
 136 @Retention(RUNTIME)
 137 @interface Nesting {
 138     NestingKind value();
 139 }
 140 
 141 /**
 142  * Probe at the various kinds of names of a type element.
 143  */
 144 @SupportedAnnotationTypes("*")
 145 class ClassNameProber extends AbstractProcessor {
 146     public ClassNameProber(){super();}
 147 
 148     private boolean classesFound=false;
 149 
 150     public boolean process(Set<? extends TypeElement> annotations,
 151                            RoundEnvironment roundEnv) {
 152         if (!roundEnv.processingOver()) {
 153             for(TypeElement typeElt : typesIn(roundEnv.getRootElements())) {
 154                 classesFound = true;
 155 
 156                 // Verify different names are non-null; an NPE will
 157                 // result in failed compile status being reported.
 158                 NestingKind nestingKind = typeElt.getNestingKind();
 159                 System.out.printf("\tSimple name: ''%s''\tQualified Name: ''%s''\tKind ''%s''\tNesting ''%s''%n",
 160                                   typeElt.getSimpleName().toString(),
 161                                   typeElt.getQualifiedName().toString(),
 162                                   typeElt.getKind().toString(),
 163                                   nestingKind.toString());
 164 
 165                 if (typeElt.getAnnotation(Nesting.class).value() != nestingKind) {
 166                     throw new RuntimeException("Mismatch of expected and reported nesting kind.");
 167                 }
 168             }
 169 
 170         }
 171 
 172         if (!classesFound) {
 173             throw new RuntimeException("Error: no classes processed.");
 174         }
 175         return true;
 176     }
 177 
 178     public SourceVersion getSupportedSourceVersion() {
 179         return SourceVersion.latest();
 180     }
 181 }