KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > modules > java > source > usages > SymbolDumperTest


1 /*
2  * The contents of this file are subject to the terms of the Common Development
3  * and Distribution License (the License). You may not use this file except in
4  * compliance with the License.
5  *
6  * You can obtain a copy of the License at http://www.netbeans.org/cddl.html
7  * or http://www.netbeans.org/cddl.txt.
8  *
9  * When distributing Covered Code, include this CDDL Header Notice in each file
10  * and include the License file at http://www.netbeans.org/cddl.txt.
11  * If applicable, add the following below the CDDL Header, with the fields
12  * enclosed by brackets [] replaced by your own identifying information:
13  * "Portions Copyrighted [year] [name of copyright owner]"
14  *
15  * The Original Software is NetBeans. The Initial Developer of the Original
16  * Software is Sun Microsystems, Inc. Portions Copyright 1997-2007 Sun
17  * Microsystems, Inc. All Rights Reserved.
18  */

19 package org.netbeans.modules.java.source.usages;
20
21 import com.sun.source.tree.CompilationUnitTree;
22 import com.sun.source.tree.Tree;
23 import com.sun.source.util.TreePath;
24 import com.sun.tools.javac.api.JavacTaskImpl;
25 import com.sun.tools.javac.code.Symbol;
26 import com.sun.tools.javac.code.Symbol.ClassSymbol;
27 import com.sun.tools.javac.code.Symbol.PackageSymbol;
28 import com.sun.tools.javac.code.Types;
29 import com.sun.tools.javac.jvm.ClassReader;
30 import com.sun.tools.javac.model.JavacElements;
31 import com.sun.tools.javac.util.Context;
32 import com.sun.tools.javac.util.CouplingAbort;
33 import com.sun.tools.javac.util.Name;
34 import com.sun.tools.javac.util.Name.Table;
35 import java.io.File JavaDoc;
36 import java.io.OutputStream JavaDoc;
37 import java.io.PrintWriter JavaDoc;
38 import java.io.StringWriter JavaDoc;
39 import java.util.ArrayList JavaDoc;
40 import java.util.Arrays JavaDoc;
41 import java.util.Collection JavaDoc;
42 import java.util.HashMap JavaDoc;
43 import java.util.List JavaDoc;
44 import java.util.Map JavaDoc;
45 import java.util.Map.Entry;
46 import java.util.Set JavaDoc;
47 import java.util.TreeMap JavaDoc;
48 import java.util.concurrent.CountDownLatch JavaDoc;
49 import javax.lang.model.element.AnnotationMirror;
50 import javax.lang.model.element.AnnotationValue;
51 import javax.lang.model.element.Element;
52 import javax.lang.model.element.ElementKind;
53 import javax.lang.model.element.ExecutableElement;
54 import javax.lang.model.element.TypeElement;
55 import javax.lang.model.element.VariableElement;
56 import javax.lang.model.type.DeclaredType;
57 import javax.lang.model.util.ElementFilter;
58 import junit.framework.TestSuite;
59 import org.netbeans.api.java.source.CancellableTask;
60 import org.netbeans.api.java.source.ClasspathInfo;
61 import org.netbeans.api.java.source.CompilationController;
62 import org.netbeans.api.java.source.CompilationInfo;
63 import org.netbeans.api.java.source.JavaSource;
64 import org.netbeans.api.java.source.JavaSource.Phase;
65 import org.netbeans.api.java.source.SourceUtilsTestUtil;
66 import org.netbeans.junit.NbTestCase;
67 import org.netbeans.junit.NbTestSuite;
68 import org.netbeans.modules.java.source.TestUtil;
69 import org.netbeans.modules.java.source.parsing.FileObjects;
70 import org.netbeans.modules.java.source.usages.ClassIndexImpl.UsageType;
71 import org.openide.filesystems.FileLock;
72 import org.openide.filesystems.FileObject;
73 import org.openide.filesystems.FileSystem;
74 import org.openide.filesystems.FileUtil;
75
76 /**
77  *
78  * @author Jan Lahoda
79  */

80 public class SymbolDumperTest extends NbTestCase {
81     
82     public SymbolDumperTest(String JavaDoc testName) {
83         super(testName);
84     }
85     
86 // public static TestSuite suite() {
87
// NbTestSuite result = new NbTestSuite();
88
//
89
// result.addTest(new SymbolDumperTest("testCyclicTypeArgumentDependency"));
90
//
91
// return result;
92
// }
93

94     protected void setUp() throws Exception JavaDoc {
95         SourceUtilsTestUtil.prepareTest(new String JavaDoc[0], new Object JavaDoc[0]);
96         
97         File JavaDoc work = TestUtil.createWorkFolder();
98         FileObject workFO = FileUtil.toFileObject(work);
99         
100         assertNotNull(workFO);
101         
102         FileObject sourceRoot = workFO.createFolder("src");
103         FileObject buildRoot = workFO.createFolder("build");
104         FileObject cache = workFO.createFolder("cache");
105         FileObject packageRoot = sourceRoot.createFolder("sourceutils");
106         
107         //FIXME:
108
File JavaDoc jarWithAnnotations = new File JavaDoc(getDataDir(), "Annotations.jar");
109         FileObject jarWithAnnotationsFO = FileUtil.toFileObject(jarWithAnnotations);
110         
111         assertNotNull(jarWithAnnotationsFO);
112         
113         SourceUtilsTestUtil.prepareTest(sourceRoot, buildRoot, cache, new FileObject[] {FileUtil. getArchiveRoot(jarWithAnnotationsFO)});
114     }
115     
116     private void writeIntoFile(FileObject file, String JavaDoc what) throws Exception JavaDoc {
117         FileLock lock = file.lock();
118         OutputStream JavaDoc out = file.getOutputStream(lock);
119         
120         try {
121             out.write(what.getBytes());
122         } finally {
123             out.close();
124             lock.releaseLock();
125         }
126     }
127     
128 // public void testDumpMethod() throws Exception {
129
// perform("package test;\npublic class test {\npublic <T> T test(T t) {return null;}\n}\n",
130
// "E<TT;>Ntest;(TT;Nt;)TT;",
131
// new Finder() {
132
// public Element findElement(CompilationInfo info, CompilationUnitTree unit) {
133
// Tree main = unit.getTypeDecls().iterator().next();
134
// TypeElement el = (TypeElement) info.getTrees().getElement(new TreePath(new TreePath(unit), main));
135
//
136
// return ElementFilter.methodsIn(el.getEnclosedElements()).get(0);
137
// }
138
// });
139
// }
140
//
141
// public void testDumpClassSimple() throws Exception {
142
// perform("package test;\npublic class test {\n}\n",
143
// "GNtest.test;Ljava.lang.Object;",
144
// new Finder() {
145
// public Element findElement(CompilationInfo info, CompilationUnitTree unit) {
146
// Tree main = unit.getTypeDecls().iterator().next();
147
// return (TypeElement) info.getTrees().getElement(new TreePath(new TreePath(unit), main));
148
// }
149
// });
150
// }
151
//
152
// public void testDumpClassComplex1() throws Exception {
153
// perform("package test;\npublic class test<T> {\n}\n",
154
// "G<T:Ljava.lang.Object;;>Ntest.test;Ljava.lang.Object;",
155
// new Finder() {
156
// public Element findElement(CompilationInfo info, CompilationUnitTree unit) {
157
// Tree main = unit.getTypeDecls().iterator().next();
158
// return (TypeElement) info.getTrees().getElement(new TreePath(new TreePath(unit), main));
159
// }
160
// });
161
// }
162
//
163
// public void testDumpClassComplex2() throws Exception {
164
// perform("package test;\npublic abstract class test<T> extends java.util.AbstractList<String> {\n}\n",
165
// "G<TT;>Ntest.test;Ljava.util.AbstractList<Ljava.lang.String;>;",
166
// new Finder() {
167
// public Element findElement(CompilationInfo info, CompilationUnitTree unit) {
168
// Tree main = unit.getTypeDecls().iterator().next();
169
// return (TypeElement) info.getTrees().getElement(new TreePath(new TreePath(unit), main));
170
// }
171
// });
172
// }
173
//
174
// public void testDumpClassComplex3() throws Exception {
175
// perform("package test;\npublic abstract class test<T> implements java.util.List<String>, java.util.Set<String> {\n}\n",
176
// "G<TT;>Ntest.test;Ljava.lang.Object;Ljava.util.List<Ljava.lang.String;>;Ljava.util.Map<Ljava.lang.String;TT;>;",
177
// new Finder() {
178
// public Element findElement(CompilationInfo info, CompilationUnitTree unit) {
179
// Tree main = unit.getTypeDecls().iterator().next();
180
// return (TypeElement) info.getTrees().getElement(new TreePath(new TreePath(unit), main));
181
// }
182
// });
183
// }
184
//
185
// public void testDumpClassComplex4() throws Exception {
186
// perform("package test;\npublic abstract class test<T extends java.util.List> {\n}\n",
187
// "G<T:Ljava.util.List;;>Ntest.test;Ljava.lang.Object;",
188
// new Finder() {
189
// public Element findElement(CompilationInfo info, CompilationUnitTree unit) {
190
// Tree main = unit.getTypeDecls().iterator().next();
191
// return (TypeElement) info.getTrees().getElement(new TreePath(new TreePath(unit), main));
192
// }
193
// });
194
// }
195
//
196
// public void testDumpClassComplex5() throws Exception {
197
// perform("package test;\npublic abstract class test<T extends java.util.List&java.util.Set> {\n}\n",
198
// "G<T:Ljava.lang.Object;Ljava.util.List;Ljava.util.Set;;>Ntest.test;Ljava.lang.Object;",
199
// new Finder() {
200
// public Element findElement(CompilationInfo info, CompilationUnitTree unit) {
201
// Tree main = unit.getTypeDecls().iterator().next();
202
//
203
// return (TypeElement) info.getTrees().getElement(new TreePath(new TreePath(unit), main));
204
// }
205
// });
206
// }
207
//
208
//
209
// public void testDumpMethodComplex1() throws Exception {
210
// perform("package test;\npublic class test<T> {\npublic T test(T t) {return null;}\n}\n",
211
// "ENtest;(TT;Nt;)TT;",
212
// new Finder() {
213
// public Element findElement(CompilationInfo info, CompilationUnitTree unit) {
214
// Tree main = unit.getTypeDecls().iterator().next();
215
// TypeElement el = (TypeElement) info.getTrees().getElement(new TreePath(new TreePath(unit), main));
216
//
217
// return ElementFilter.methodsIn(el.getEnclosedElements()).get(0);
218
// }
219
// });
220
// }
221

222     private static interface Finder {
223         
224         public Element findElement(CompilationInfo info, CompilationUnitTree unit);
225         
226     }
227     
228     protected void perform(String JavaDoc source, String JavaDoc signature, Finder finder) throws Exception JavaDoc {
229         FileSystem fs = FileUtil.createMemoryFileSystem();
230         FileObject file = fs.getRoot().createData("test.java");
231         
232         writeIntoFile(file, source);
233         
234         JavaSource js = JavaSource.forFileObject(file);
235         CompilationInfo info = SourceUtilsTestUtil.getCompilationInfo(js, Phase.RESOLVED);
236         CompilationUnitTree unit = info.getCompilationUnit();
237         assertTrue(info.getDiagnostics().toString(), info.getDiagnostics().isEmpty());
238         Element el = finder.findElement(info, unit);
239         
240         StringWriter JavaDoc w = new StringWriter JavaDoc();
241         PrintWriter JavaDoc pw = new PrintWriter JavaDoc(w);
242         
243         JavacTaskImpl jt = (JavacTaskImpl)SourceUtilsTestUtil.getJavacTaskFor(info);
244         SymbolDumper.dump(pw, Types.instance(jt.getContext()), (TypeElement) el, null);
245         
246         pw.close();
247         
248 // System.err.println(w.toString());
249
assertEquals(signature, w.toString());
250     }
251     
252     public void testReadWriteSimple1() throws Exception JavaDoc {
253         performReadWrite("package test;\npublic class test {\n}\n");
254     }
255     
256     public void testReadWriteSimple2() throws Exception JavaDoc {
257         performReadWrite("package test;\npublic class test {\npublic void testMethod(int a) {}\n}\n");
258     }
259     
260     public void testReadWriteSimple3() throws Exception JavaDoc {
261         performReadWrite("package test;\npublic class test {\npublic test(int y){} public void testMethod(int a) {}\n}\n");
262     }
263     
264     public void testReadWriteSimple4() throws Exception JavaDoc {
265         performReadWrite("package test;\npublic class test {\npublic void testMethod(String x) {}\n}\n");
266     }
267     
268     public void testReadWriteSimple5() throws Exception JavaDoc {
269         performReadWrite("package test;\npublic class test {\nprivate int x;\n}\n");
270     }
271     
272     public void testReadWriteSimple6() throws Exception JavaDoc {
273         performReadWrite("package test;\npublic class test {\nprivate int x;java.util.Map y;\n}\n");
274     }
275     
276     public void testReadWriteSimple7() throws Exception JavaDoc {
277         performReadWrite("package test;\npublic class test {\nprivate int x;java.util.Map y;\npublic void testMethod(String x) {}\n}\n");
278     }
279     
280     public void testReadWriteSimple8() throws Exception JavaDoc {
281         performReadWrite("package test;\npublic class test {\njava.util.Map y;\n}\n");
282     }
283     
284     public void testReadWriteSimple9() throws Exception JavaDoc {
285         performReadWrite("package test;\npublic class test {\njava.util.Map<String, String> y;\n}\n");
286     }
287     
288     public void testReadWriteSimple10() throws Exception JavaDoc {
289         performReadWrite("package test;\npublic class test {\njava.util.Map<String, String> y;\npublic java.util.Map<String, Integer> testMethod(java.util.Set<Long> set){return null;}\n}\n");
290     }
291     
292     public void testReadWriteSimple11() throws Exception JavaDoc {
293         performReadWrite("package test;\npublic abstract class test extends java.util.AbstractList {}\n");
294     }
295     
296     public void testReadWriteSimple12() throws Exception JavaDoc {
297         performReadWrite("package test;\npublic abstract class test extends java.util.AbstractList implements java.util.Set, java.util.List {}\n");
298     }
299     
300     public void testReadWriteArray1() throws Exception JavaDoc {
301         performReadWrite("package test;\npublic class test {\nprivate String[] f;}\n");
302     }
303     
304     public void testReadWriteArray2() throws Exception JavaDoc {
305         performReadWrite("package test;\npublic class test {\nprivate int[] f;}\n");
306     }
307     
308     public void testReadWriteThrows1() throws Exception JavaDoc {
309         performReadWrite("package test;\npublic class test {\nprivate void testMethod() throws Exception {}\n}\n");
310     }
311     
312     
313     public void testCyclicTypeArgumentDependency() throws Exception JavaDoc {
314         performReadWrite("package test;\npublic class test<T extends java.util.List<T>> {\npublic T test(T t) {return null;}\n}\n");
315     }
316     
317     
318     //TODO: test error type
319

320     public void testReadWriteGenerics1() throws Exception JavaDoc {
321         performReadWrite("package test;\npublic class test<T> {\npublic T test(T t) {return null;}\n}\n");
322     }
323     
324     public void testReadWriteGenerics2() throws Exception JavaDoc {
325         performReadWrite("package test;\npublic class test<T extends java.util.List> {\npublic T test(T t) {return null;}\n}\n");
326     }
327     
328     public void testReadWriteGenerics3() throws Exception JavaDoc {
329         performReadWrite("package test;\npublic class test<T extends java.util.List&java.util.Set> {\npublic T test(T t) {return null;}\n}\n");
330     }
331     
332     public void testReadWriteGenerics4() throws Exception JavaDoc {
333         performReadWrite("package test;\npublic class test {\npublic <T> T test(T t) {return null;}\n}\n");
334     }
335     
336     public void testReadWriteGenerics5() throws Exception JavaDoc {
337         performReadWrite("package test;\npublic class test {\npublic <T extends java.util.List> T test(T t) {return null;}\n}\n");
338     }
339     
340     public void testReadWriteGenerics6() throws Exception JavaDoc {
341         performReadWrite("package test;\npublic class test {\npublic <T extends java.util.List&Comparable> T test(T t) {return null;}\n}\n");
342     }
343     
344     public void testReadWriteGenerics7() throws Exception JavaDoc {
345         performReadWrite("package test;\npublic class test {\npublic <T extends java.util.Map<? extends Number, ? super Comparable>> T test(T t) {return null;}\n}\n");
346     }
347     
348     public void testReadWriteGenerics8() throws Exception JavaDoc {
349         performReadWrite("package test;\npublic class test <T extends java.util.Map<? extends Number, ? super Comparable>> {\npublic T test(T t) {return null;}\n}\n");
350     }
351     
352     public void testReadWriteGenerics9() throws Exception JavaDoc {
353         performReadWrite("package test; public class test {\npublic void testMethod() {\njava.util.Map<String, java.io.PrintWriter> m = new java.util.HashMap<String, java.io.PrintWriter>();}\n}");
354     }
355     
356     public void testReadWriteGenerics10() throws Exception JavaDoc {
357         performReadWrite("package test; public class test {\njava.util.Map<String, java.io.PrintWriter> m = new java.util.HashMap<String, java.io.PrintWriter>();\n}");
358     }
359     
360     public void testReadWriteGenerics11() throws Exception JavaDoc {
361         performReadWrite("package test; public class test<T> {\njava.util.Map<String, java.io.PrintWriter> m = new java.util.HashMap<String, java.io.PrintWriter>();\n}");
362     }
363     
364     private static class ConstantValidator implements Validator {
365         private Object JavaDoc value;
366         public ConstantValidator(Object JavaDoc value) {
367             this.value = value;
368         }
369         public void validate(CompilationInfo info, Element t) {
370             assertEquals(ElementKind.CLASS, t.getKind());
371             
372             VariableElement constant = ElementFilter.fieldsIn(t.getEnclosedElements()).get(0);
373             Object JavaDoc constantValue = constant.getConstantValue();
374             
375             assertEquals(value, constantValue);
376         }
377     }
378     
379     public void testReadWriteConstantInt() throws Exception JavaDoc {
380         performReadWrite("package test;\npublic class test {\npublic static final int X = 13;\n}\n", new ConstantValidator(Integer.valueOf(13)));
381     }
382     
383     //does not work:
384
// public void testReadWriteConstantBooleanTRUE() throws Exception {
385
// performReadWrite("package test;\npublic class test {\npublic static final boolean X = Boolean.TRUE;\n}\n", new ConstantValidator(Boolean.TRUE));
386
// }
387
//
388
// public void testReadWriteConstantBooleanFALSE() throws Exception {
389
// performReadWrite("package test;\npublic class test {\npublic static final boolean X = Boolean.FALSE;\n}\n", new ConstantValidator(Boolean.FALSE));
390
// }
391

392     public void testReadWriteConstantByte() throws Exception JavaDoc {
393         performReadWrite("package test;\npublic class test {\npublic static final byte X = 13;\n}\n", new ConstantValidator(Byte.valueOf("13")));
394     }
395     
396     public void testReadWriteConstantShort() throws Exception JavaDoc {
397         performReadWrite("package test;\npublic class test {\npublic static final short X = 13;\n}\n", new ConstantValidator(Short.valueOf("13")));
398     }
399     
400     public void testReadWriteConstantLong() throws Exception JavaDoc {
401         performReadWrite("package test;\npublic class test {\npublic static final long X = 13;\n}\n", new ConstantValidator(Long.valueOf(13)));
402     }
403     
404     public void testReadWriteConstantFloat() throws Exception JavaDoc {
405         performReadWrite("package test;\npublic class test {\npublic static final float X = 13.98F;\n}\n", new ConstantValidator(Float.valueOf("13.98")));
406     }
407     
408     public void testReadWriteConstantDouble() throws Exception JavaDoc {
409         performReadWrite("package test;\npublic class test {\npublic static final double X = 13.98;\n}\n", new ConstantValidator(Double.valueOf(13.98)));
410     }
411     
412     public void testReadWriteConstantChar() throws Exception JavaDoc {
413         performReadWrite("package test;\npublic class test {\npublic static final char X = 'a';\n}\n", new ConstantValidator(Character.valueOf('a')));
414     }
415     
416     public void testReadWriteConstantCharEscape1() throws Exception JavaDoc {
417         performReadWrite("package test;\npublic class test {\npublic static final char X = '@';\n}\n", new ConstantValidator(Character.valueOf('@')));
418     }
419     
420     public void testReadWriteConstantCharEscape2() throws Exception JavaDoc {
421         performReadWrite("package test;\npublic class test {\npublic static final char X = ';';\n}\n", new ConstantValidator(Character.valueOf(';')));
422     }
423     
424     public void testReadWriteConstantCharEscape3() throws Exception JavaDoc {
425         performReadWrite("package test;\npublic class test {\npublic static final char X = '\\\\';\n}\n", new ConstantValidator(Character.valueOf('\\')));
426     }
427     
428     public void testReadWriteConstantCharEscape4() throws Exception JavaDoc {
429         performReadWrite("package test;\npublic class test {\npublic static final char X = '\\n';\n}\n", new ConstantValidator(Character.valueOf('\n')));
430     }
431     
432     public void testReadWriteConstantString() throws Exception JavaDoc {
433         performReadWrite("package test;\npublic class test {\npublic static final String X = \"test@\\\\sd@;@\\n@''';\";\n}\n", new ConstantValidator("test@\\sd@;@\n@''';"));
434     }
435     
436     public void testReadWriteConstantString2() throws Exception JavaDoc {
437         performReadWrite("package test;\npublic class test {\npublic static final String X = \"d\\1x\";\n}\n", new ConstantValidator("d\1x"));
438     }
439     
440     public void testReadWriteConstantString3() throws Exception JavaDoc {
441         performReadWrite("package test;\npublic class test {\npublic static final String X = \"d\\\\1x\";\n}\n", new ConstantValidator("d\\1x"));
442     }
443     
444     public void testReadWriteConstantString4() throws Exception JavaDoc {
445         performReadWrite("package test;\npublic class test {\npublic static final String X = \"d\\\\\\1x\";\n}\n", new ConstantValidator("d\\\1x"));
446     }
447     
448     public void testReadWriteConstantString5() throws Exception JavaDoc {
449         performReadWrite("package test;\npublic class test {\npublic static final String X = \"d\\\\\\\\1x\";\n}\n", new ConstantValidator("d\\\\1x"));
450     }
451     
452     public void testReadWriteConstantString6() throws Exception JavaDoc {
453         performReadWrite("package test;\npublic class test {\npublic static final String X = \"d\\\\\";\n}\n", new ConstantValidator("d\\"));
454     }
455     
456     public void testReadWriteConstructors() throws Exception JavaDoc {
457         performReadWrite("package test; public class test {\npublic test(Class clazz){}\n}");
458     }
459     
460     public void testReadWriteNoArgAnnotation() throws Exception JavaDoc {
461         performReadWrite("package test; import annotations.NoArgAnnotation; @NoArgAnnotation public class test {\npublic test(Class clazz){}\n}", new Validator() {
462             public void validate(CompilationInfo info, Element t) {
463                 List JavaDoc<? extends AnnotationMirror> annotations = t.getAnnotationMirrors();
464                 
465                 boolean found = false;
466                 
467                 for (AnnotationMirror m : annotations) {
468                     if ("annotations.NoArgAnnotation".equals(((TypeElement) m.getAnnotationType().asElement()).getQualifiedName().toString())) {
469                         found = true;
470                         break;
471                     }
472                 }
473                 
474                 assertTrue(found);
475             }
476         });
477     }
478     
479     //we intentionaly store also the annotations with retention source:
480
public void testReadWriteNoArgAnnotationSource() throws Exception JavaDoc {
481         performReadWrite("package test; import annotations.NoArgAnnotationSource; @NoArgAnnotationSource public class test {\npublic test(Class clazz){}\n}", new Validator() {
482             public void validate(CompilationInfo info, Element t) {
483                 List JavaDoc<? extends AnnotationMirror> annotations = t.getAnnotationMirrors();
484                 
485                 boolean found = false;
486                 
487                 for (AnnotationMirror m : annotations) {
488                     if ("annotations.NoArgAnnotationSource".equals(((TypeElement) m.getAnnotationType().asElement()).getQualifiedName().toString())) {
489                         found = true;
490                         break;
491                     }
492                 }
493                 
494                 assertTrue(found);
495             }
496         });
497     }
498     
499     public void testReadWriteNoArgAnnotationOnMethod() throws Exception JavaDoc {
500         performReadWrite("package test; import annotations.NoArgAnnotation; public class test {\npublic @NoArgAnnotation test(Class clazz){}\n}", new Validator() {
501             public void validate(CompilationInfo info, Element t) {
502                 ExecutableElement ee = ElementFilter.constructorsIn(t.getEnclosedElements()).get(0);
503                 List JavaDoc<? extends AnnotationMirror> annotations = ee.getAnnotationMirrors();
504                 boolean found = false;
505                 
506                 for (AnnotationMirror m : annotations) {
507                     if ("annotations.NoArgAnnotation".equals(((TypeElement) m.getAnnotationType().asElement()).getQualifiedName().toString())) {
508                         found = true;
509                         break;
510                     }
511                 }
512                 
513                 assertTrue(found);
514             }
515         });
516     }
517     
518     public void testReadWriteNoArgAnnotationOnField() throws Exception JavaDoc {
519         performReadWrite("package test; import annotations.NoArgAnnotation; public class test {\npublic @NoArgAnnotation int test = 1;\n}", new Validator() {
520             public void validate(CompilationInfo info, Element t) {
521                 VariableElement ve = ElementFilter.fieldsIn(t.getEnclosedElements()).get(0);
522                 List JavaDoc<? extends AnnotationMirror> annotations = ve.getAnnotationMirrors();
523                 boolean found = false;
524                 
525                 for (AnnotationMirror m : annotations) {
526                     if ("annotations.NoArgAnnotation".equals(((TypeElement) m.getAnnotationType().asElement()).getQualifiedName().toString())) {
527                         found = true;
528                         break;
529                     }
530                 }
531                 
532                 assertTrue(found);
533             }
534         });
535     }
536     
537     private static AnnotationValue findValue(AnnotationMirror m, String JavaDoc attributeName) {
538         for (Entry<? extends ExecutableElement, ? extends AnnotationValue> entry : m.getElementValues().entrySet()) {
539             if (attributeName.equals(entry.getKey().getSimpleName().toString())) {
540                 return entry.getValue();
541             }
542         }
543         
544         fail("required attribute not found");
545         throw new AssertionError JavaDoc("cannot happen");
546     }
547     
548     private static class ValidateAnnotationWithPrimitiveTypeValue implements Validator {
549         private String JavaDoc annotationName;
550         private Object JavaDoc value;
551         
552         public ValidateAnnotationWithPrimitiveTypeValue(String JavaDoc annotationName, Object JavaDoc value) {
553             this.annotationName = annotationName;
554             this.value = value;
555         }
556         
557         public void validate(CompilationInfo info, Element t) {
558             List JavaDoc<? extends AnnotationMirror> annotations = t.getAnnotationMirrors();
559             boolean found = false;
560             
561             for (AnnotationMirror m : annotations) {
562                 if (("annotations." + annotationName).equals(((TypeElement) m.getAnnotationType().asElement()).getQualifiedName().toString())) {
563                     AnnotationValue v = findValue(m, "value");
564                     
565                     Object JavaDoc proposedValue = v.getValue();
566                     
567                     if (this.value instanceof Collection JavaDoc) {
568                         List JavaDoc proposed = new ArrayList JavaDoc();
569                         
570                         for (AnnotationValue value : (Collection JavaDoc<AnnotationValue>) proposedValue) {
571                             proposed.add(value.getValue());
572                         }
573                         
574                         assertEquals(new ArrayList JavaDoc((Collection JavaDoc) this.value), proposed);
575                     } else {
576                         assertEquals(this.value, proposedValue);
577                     }
578                     
579                     found = true;
580                     break;
581                 }
582             }
583             
584             assertTrue(found);
585         }
586     }
587     
588     public void testReadWriteAnnotationBooleanArg() throws Exception JavaDoc {
589         performReadWrite("package test; import annotations.BooleanArgAnnotation; public @BooleanArgAnnotation(true) class test {\n}",
590             new ValidateAnnotationWithPrimitiveTypeValue("BooleanArgAnnotation", Boolean.TRUE));
591     }
592     
593     public void testReadWriteAnnotationByteArg() throws Exception JavaDoc {
594         performReadWrite("package test; import annotations.ByteArgAnnotation; public @ByteArgAnnotation(2) class test {\n}",
595             new ValidateAnnotationWithPrimitiveTypeValue("ByteArgAnnotation", Byte.valueOf((byte) 2)));
596     }
597     
598     public void testReadWriteAnnotationShortArg() throws Exception JavaDoc {
599         performReadWrite("package test; import annotations.ShortArgAnnotation; public @ShortArgAnnotation(2) class test {\n}",
600             new ValidateAnnotationWithPrimitiveTypeValue("ShortArgAnnotation", Short.valueOf((short) 2)));
601     }
602     
603     public void testReadWriteAnnotationIntArg() throws Exception JavaDoc {
604         performReadWrite("package test; import annotations.IntArgAnnotation; public @IntArgAnnotation(2) class test {\n}",
605             new ValidateAnnotationWithPrimitiveTypeValue("IntArgAnnotation", Integer.valueOf(2)));
606     }
607     
608     public void testReadWriteAnnotationLongArg() throws Exception JavaDoc {
609         performReadWrite("package test; import annotations.LongArgAnnotation; public @LongArgAnnotation(2) class test {\n}",
610             new ValidateAnnotationWithPrimitiveTypeValue("LongArgAnnotation", Long.valueOf(2)));
611     }
612         
613     public void testReadWriteAnnotationFloatArg() throws Exception JavaDoc {
614         performReadWrite("package test; import annotations.FloatArgAnnotation; public @FloatArgAnnotation(2.45F) class test {\n}",
615             new ValidateAnnotationWithPrimitiveTypeValue("FloatArgAnnotation", Float.valueOf(2.45F)));
616     }
617         
618     public void testReadWriteAnnotationDoubleArg() throws Exception JavaDoc {
619         performReadWrite("package test; import annotations.DoubleArgAnnotation; public @DoubleArgAnnotation(2.45) class test {\n}",
620             new ValidateAnnotationWithPrimitiveTypeValue("DoubleArgAnnotation", Double.valueOf(2.45)));
621     }
622         
623     public void testReadWriteAnnotationCharArg() throws Exception JavaDoc {
624         performReadWrite("package test; import annotations.CharArgAnnotation; public @CharArgAnnotation('@') class test {\n}",
625             new ValidateAnnotationWithPrimitiveTypeValue("CharArgAnnotation", Character.valueOf('@')));
626     }
627     
628     public void testReadWriteAnnotationStringArg() throws Exception JavaDoc {
629         performReadWrite("package test; import annotations.StringArgAnnotation; public @StringArgAnnotation(\"test@;;\\\\\") class test {\n}",
630             new ValidateAnnotationWithPrimitiveTypeValue("StringArgAnnotation", "test@;;\\"));
631     }
632     
633     public void testReadWriteAnnotationArrayOfStringArg() throws Exception JavaDoc {
634         performReadWrite("package test; import annotations.*; public @AnnotationArgAnnotation(@ArrayOfStringArgAnnotation(\"test@;;\\\\\")) class test {\n}", new Validator() {
635             public void validate(CompilationInfo info, Element t) {
636                 List JavaDoc<? extends AnnotationMirror> annotations = t.getAnnotationMirrors();
637                 boolean found = false;
638                 
639                 for (AnnotationMirror m : annotations) {
640                     if (("annotations.AnnotationArgAnnotation").equals(((TypeElement) m.getAnnotationType().asElement()).getQualifiedName().toString())) {
641                         AnnotationValue v = findValue(m, "value");
642                         Object JavaDoc proposedValue = v.getValue();
643                         
644                         assertTrue(proposedValue instanceof AnnotationMirror);
645                         
646                         found = true;
647                         break;
648                     }
649                 }
650                 
651                 assertTrue(found);
652             }
653         });
654     }
655     
656     public void testReadWriteAnnotationEnumArg() throws Exception JavaDoc {
657         performReadWrite("package test; import annotations.*; public @EnumArgAnnotation(TestEnum.X) class test {\n}", new Validator() {
658             public void validate(CompilationInfo info, Element t) {
659                 List JavaDoc<? extends AnnotationMirror> annotations = t.getAnnotationMirrors();
660                 boolean found = false;
661                 
662                 for (AnnotationMirror m : annotations) {
663                     if (("annotations.EnumArgAnnotation").equals(((TypeElement) m.getAnnotationType().asElement()).getQualifiedName().toString())) {
664                         AnnotationValue v = findValue(m, "value");
665                         Object JavaDoc proposedValue = v.getValue();
666                         VariableElement value = (VariableElement) proposedValue;
667                         
668                         assertEquals("X", value.getSimpleName().toString());
669                         
670                         assertEquals("annotations.TestEnum", ((TypeElement) value.getEnclosingElement()).getQualifiedName().toString());
671                         
672                         found = true;
673                         break;
674                     }
675                 }
676                 
677                 assertTrue(found);
678             }
679         });
680     }
681     
682     public void testReadWriteAnnotationWithAnnotation() throws Exception JavaDoc {
683         performReadWrite("package test; import annotations.ArrayOfStringArgAnnotation; public @ArrayOfStringArgAnnotation(\"test@;;\\\\\") class test {\n}",
684             new ValidateAnnotationWithPrimitiveTypeValue("ArrayOfStringArgAnnotation", Arrays.asList(new String JavaDoc[] {"test@;;\\"})));
685     }
686     
687     public void testReadWriteRecursiveAnnotation() throws Exception JavaDoc {
688         performReadWrite("package test; @test(\"test\")public @interface test {public String value();\n}");
689     }
690     
691     public void testReadWriteEnum1() throws Exception JavaDoc {
692         performReadWrite("package test; public enum test {VALUE1, VALUE2;\n}", new Validator() {
693             public void validate(CompilationInfo info, Element t) {
694                 assertEquals(ElementKind.ENUM, t.getKind());
695                 assertEquals(2, ElementFilter.fieldsIn(t.getEnclosedElements()).size());
696                 assertEquals(ElementKind.ENUM_CONSTANT, ElementFilter.fieldsIn(t.getEnclosedElements()).get(0).getKind());
697                 assertEquals(ElementKind.ENUM_CONSTANT, ElementFilter.fieldsIn(t.getEnclosedElements()).get(1).getKind());
698             }
699         });
700     }
701     
702     public void testReadWriteEnum2() throws Exception JavaDoc {
703         performReadWrite("package test; public enum test {\n" + "AUTO,\n" + "YES,\n" + "NO;\n" + "\n" + "public String getDisplayName() {\n" + " return null;\n" + "}\n}", new Validator() {
704             public void validate(CompilationInfo info, Element t) {
705                 assertEquals(ElementKind.ENUM, t.getKind());
706                 assertEquals(3, ElementFilter.fieldsIn(t.getEnclosedElements()).size());
707                 assertEquals(ElementKind.ENUM_CONSTANT, ElementFilter.fieldsIn(t.getEnclosedElements()).get(0).getKind());
708                 assertEquals(ElementKind.ENUM_CONSTANT, ElementFilter.fieldsIn(t.getEnclosedElements()).get(1).getKind());
709                 assertEquals(ElementKind.ENUM_CONSTANT, ElementFilter.fieldsIn(t.getEnclosedElements()).get(2).getKind());
710             }
711         });
712     }
713     
714     public void testReadWriteAnnonymousInnerclasses1() throws Exception JavaDoc {
715         performReadWrite("package test; public class test {public void testMethod() {new Runnable() {public void run(){}};}}\n", new Validator() {
716             public void validate(CompilationInfo info, Element t) {
717                 assertEquals(ElementKind.CLASS, t.getKind());
718                 
719                 JavacElements jels = (JavacElements) info.getElements();
720                 
721                 TypeElement annonymous = jels.getTypeElementByBinaryName("test.test$1");
722                 
723                 assertEquals(1, ElementFilter.methodsIn(t.getEnclosedElements()).size());
724                 
725                 ExecutableElement ee = ElementFilter.methodsIn(t.getEnclosedElements()).get(0);
726                 
727                 assertEquals(ee, annonymous.getEnclosingElement());
728                 
729                 assertEquals("java.lang.Runnable", ((TypeElement) ((DeclaredType) annonymous.getInterfaces().get(0)).asElement()).getQualifiedName().toString());
730             }
731         }, false);
732     }
733     
734     public void testReadWriteAnnonymousInnerclasses2() throws Exception JavaDoc {
735         performReadWrite("package test; public class test {public void testMethod() {new Runnable() {public void run(){}}; new Runnable() {public void run(){}};}}\n", new Validator() {
736             public void validate(CompilationInfo info, Element t) {
737                 assertEquals(ElementKind.CLASS, t.getKind());
738                 
739                 JavacElements jels = (JavacElements) info.getElements();
740                 
741                 TypeElement annonymous = jels.getTypeElementByBinaryName("test.test$1");
742                 
743                 assertEquals(1, annonymous.getInterfaces().size());
744                 
745                 assertEquals("java.lang.Runnable", ((TypeElement) ((DeclaredType) annonymous.getInterfaces().get(0)).asElement()).getQualifiedName().toString());
746                 
747                 annonymous = jels.getTypeElementByBinaryName("test.test$2");
748                 
749                 assertEquals(1, annonymous.getInterfaces().size());
750                 
751                 assertEquals("java.lang.Runnable", ((TypeElement) ((DeclaredType) annonymous.getInterfaces().get(0)).asElement()).getQualifiedName().toString());
752             }
753         }, false);
754     }
755     
756     public void testReadWriteLocalClasses1() throws Exception JavaDoc {
757         performReadWrite("package test; public class test {public void testMethod() {class Test implements Runnable {public void run(){}};}}\n", new Validator() {
758             public void validate(CompilationInfo info, Element t) {
759                 assertEquals(ElementKind.CLASS, t.getKind());
760                 
761                 JavacElements jels = (JavacElements) info.getElements();
762                 
763                 TypeElement annonymous = jels.getTypeElementByBinaryName("test.test$1Test");
764                 
765                 assertEquals(1, annonymous.getInterfaces().size());
766                 
767                 assertEquals("java.lang.Runnable", ((TypeElement) ((DeclaredType) annonymous.getInterfaces().get(0)).asElement()).getQualifiedName().toString());
768             }
769         }, false);
770     }
771     
772     private static interface Validator {
773         public void validate(CompilationInfo info, Element t);
774     }
775     
776     private String JavaDoc dump(Types types, TypeElement type) {
777         //!!!well:
778
StringWriter JavaDoc w = new StringWriter JavaDoc();
779         PrintWriter JavaDoc pw = new PrintWriter JavaDoc(w);
780         
781         SymbolDumper.dump(pw, types, type, null);
782         
783         pw.close();
784         return w.toString();
785     }
786     
787     private Map JavaDoc<String JavaDoc, String JavaDoc> dumpIncludingInnerClasses(CompilationInfo info, TypeElement type) {
788         SourceAnalyserImpl sa = new SourceAnalyserImpl((JavacTaskImpl) SourceUtilsTestUtil.getJavacTaskFor(info), info.getCompilationUnit());
789         
790         info.getCompilationUnit().accept(sa, new HashMap JavaDoc<String JavaDoc,Map JavaDoc<String JavaDoc,Set JavaDoc<UsageType>>>());
791         
792         return sa.class2Sig;
793     }
794     
795     protected void performReadWrite(String JavaDoc source) throws Exception JavaDoc {
796         performReadWrite(source, null);
797     }
798     
799     protected void performReadWrite(String JavaDoc source, Validator validator) throws Exception JavaDoc {
800         performReadWrite(source, validator, true);
801     }
802     
803     protected void performReadWrite(String JavaDoc source, Validator validator, boolean verifySignatures) throws Exception JavaDoc {
804         FileSystem fs = FileUtil.createMemoryFileSystem();
805         FileObject file = fs.getRoot().createData("test.java");
806         
807         writeIntoFile(file, source);
808         
809         JavaSource js = JavaSource.forFileObject(file);
810         CompilationInfo info = SourceUtilsTestUtil.getCompilationInfo(js, Phase.RESOLVED);
811         CompilationUnitTree unit = info.getCompilationUnit();
812         assertTrue(info.getDiagnostics().toString(), info.getDiagnostics().isEmpty());
813         
814         Tree main = unit.getTypeDecls().iterator().next();
815         TypeElement type = (TypeElement) info.getTrees().getElement(new TreePath(new TreePath(unit), main));
816         
817         final Map JavaDoc<String JavaDoc, String JavaDoc> signatures = dumpIncludingInnerClasses(info, type);
818         
819         System.err.println("sig=" + signatures);
820         
821         FileObject file2 = fs.getRoot().createData("test2.java");
822         ClasspathInfo cpInfo = ClasspathInfo.create(file2);
823         JavaSource js2 = JavaSource.create(cpInfo);
824         final CountDownLatch JavaDoc l = new CountDownLatch JavaDoc(1);
825         
826         final String JavaDoc[] newSig = new String JavaDoc[1];
827         final Symbol[] symbol = new Symbol[1];
828         final CompilationInfo[] infoOut = new CompilationInfo[1];
829         
830         js2.runUserActionTask(new CancellableTask<CompilationController>() {
831             public void cancel() {
832             }
833             public void run(CompilationController parameter) {
834                 try {
835                     JavacTaskImpl task = (JavacTaskImpl) SourceUtilsTestUtil.getJavacTaskFor(parameter);
836                     Context context = task.getContext();
837                     SymbolClassReader reader = (SymbolClassReader) ClassReader.instance(context);
838                     Name className = Name.Table.instance(context).fromString("test");
839                     
840                     PackageSymbol pack = reader.enterPackage(Name.Table.instance(context).fromString("test"));
841                     
842                     assertNotNull(pack);
843                     
844                     pack.complete();
845                     
846                     for (Map.Entry JavaDoc<String JavaDoc, String JavaDoc> entry : signatures.entrySet()) {
847                         reader.includeClassFile(pack, FileObjects.memoryFileObject(entry.getValue(), entry.getKey() + ".sig"));
848                     }
849                     
850                     ClassSymbol cs = reader.enterClass(className, pack);
851                     
852                     cs.complete();
853                     
854                     symbol[0] = cs;
855                     JavacTaskImpl jt = (JavacTaskImpl)SourceUtilsTestUtil.getJavacTaskFor(parameter);
856                     newSig[0] = dump(Types.instance(jt.getContext()), cs);
857                     infoOut[0] = parameter;
858                 } finally {
859                     l.countDown();
860                 }
861             }
862         },true);
863         
864         l.await();
865         
866         System.err.println("newSig=" + newSig[0]);
867         if (verifySignatures)
868             assertEquals(signatures.get("test"), newSig[0]);
869         
870         if (validator != null)
871             validator.validate(infoOut[0], symbol[0]);
872     }
873     
874     public void testCompileAgainstSimple() throws Exception JavaDoc {
875         performCompileAgainst("package test; public class test2 {\npublic void testMethod2() {test.method();}\n}", "package test; public class test {\npublic static void method() {}\n}");
876     }
877     
878     public void testCompileAgainstWithThrows() throws Exception JavaDoc {
879         performCompileAgainst("package test; public class test2 {\npublic void testMethod2() {try {test.method();} catch (Exception e) {}}\n}", "package test; public class test {\npublic static void method() throws Exception {}\n}");
880     }
881     
882     public void testCompileAgainstConstantInt() throws Exception JavaDoc {
883         performCompileAgainst("package test; public class test2 {\npublic static final int x = test.C + 1;\n}", "package test; public class test {\npublic static final int C = 0;\n}");
884     }
885     
886     public void testCompileAgainstConstantString() throws Exception JavaDoc {
887         performCompileAgainst("package test; public class test2 {\npublic static final String x = test.C;\n}", "package test; public class test {\npublic static final String C = \"\";\n}");
888     }
889     
890     //TODO: produces (intentional) errors, the infrastructure needs to be extended to handle this:
891
// public void testCompileAgainstWithThrowsUnknownException() throws Exception {
892
// performCompileAgainst("package test; public class test2 {\nString x() {return \"\";} public void testMethod2() {try {test t = new test(); XXX x; x = t.method(x(), x(), null);} catch (Exception e) {}}\n}", "package test; public class test {\npublic XXX method(String sd, GGG g, HHH[] h) throws YYY {}\n}");
893
// }
894

895     public void testCompileAgainstWithConstructors() throws Exception JavaDoc {
896         performCompileAgainst("package test; public class test2 {\npublic void testMethod2() {new test(test2.class);}\n}", "package test; public class test {\npublic test(Class clazz){}\n}");
897     }
898     
899     public void testCompileAgainstWithGenerics1() throws Exception JavaDoc {
900         performCompileAgainst("package test; public class test2 {\npublic void testMethod2() {test t;}\n}", "package test; public class test<T> {\npublic T testMethod(T t) {return null;}\n}");
901     }
902     
903     public void testCompileAgainstWithGenerics2() throws Exception JavaDoc {
904         performCompileAgainst("package test; public class test2 {\npublic void testMethod2() {test<String> t = new test<String>();}\n}", "package test; public class test<T> {\npublic T testMethod(T t) {return null;}\n}");
905     }
906     
907     public void testCompileAgainstWithGenerics3() throws Exception JavaDoc {
908         performCompileAgainst("package test; public class test2 {\npublic void testMethod2() {test t = new test();}\n}", "1.4", "package test; public class test<T> {\njava.util.Map<String, java.io.PrintWriter> m = new java.util.HashMap<String, java.io.PrintWriter>();\n}", "1.5", false);
909     }
910
911     public void testCompileAgainstInnerClassWithGenerics1() throws Exception JavaDoc {
912         performCompileAgainst("package test; public class test2 {\npublic void testMethod2() {test.Inner t;}\n}", "1.4", "package test; public class test {\npublic static class Inner<T> {}\n}", "1.5", false);
913     }
914     
915     public void testCompileAgainstInnerClassWithGenerics2() throws Exception JavaDoc {
916         performCompileAgainst("package test; public class test2 {\npublic void testMethod2() {test.Inner2 t2;test.Inner1 t1;}\n}", "1.4", "package test; public class test {\npublic static class Inner1<T> {} public static class Inner2<T> {}\n}", "1.5", false);
917     }
918     
919     public void testCompileAgainstInnerClassWithGenerics3() throws Exception JavaDoc {
920         performCompileAgainst("package test; public class test2 {\npublic void testMethod2() {test.Inner2 t2;test.Inner1 t1;}\n}", "1.4", "package test; public class test {\npublic static class Inner1<T> {private Inner2<T> i1;} public static class Inner2<T> {}\n}", "1.5", false);
921     }
922     
923     public void testCompileAgainstInnerClassWithGenerics4() throws Exception JavaDoc {
924         performCompileAgainst("package test; public class test2 {\npublic void testMethod2() {test.Inner2 t2;test.Inner1 t1;}\n}", "1.5", "package test; public class test {\npublic static class Inner1<T> {private Inner2<T> i1;} public static class Inner2<T> {}\n}", "1.5", true);
925     }
926     
927     public void testCompileAgainstInnerClassWithGenerics5() throws Exception JavaDoc {
928         performCompileAgainst("package test; public class test2 {\npublic void testMethod2() {test.Inner2 t2;test.Inner1 t1;}\n}", "1.5", "package test; public class test {\npublic static class Inner0 {} public static class Inner1<T> {private Inner2<T> i1;} public static class Inner2<T> {}\n}", "1.5", true);
929     }
930     
931     public void testCompileAgainstInnerClassWithGenerics6() throws Exception JavaDoc {
932         performCompileAgainst("package test; public class test2 {\npublic void testMethod2() {test.Inner1 t1;}\n}", "1.5", "package test; public class test {\npublic static abstract class Inner1<T> {}\n}", "1.5", true);
933     }
934     
935     public void testCompileAgainstInnerClassWithGenerics7() throws Exception JavaDoc {
936         performCompileAgainst("package test; public class test2 {\npublic void testMethod2() {test.Inner1 t1;}\n}", "1.5", "package test; public class test {\npublic static abstract class Inner1<T> {} public <T> Inner1<T> ret() {return null;}\n}", "1.5", true);
937     }
938     
939     public void testCompileAgainstInnerClassWithGenerics8() throws Exception JavaDoc {
940         performCompileAgainst("package test; public class test2 {\npublic void testMethod2() {test.Inner1 t1;}\n}", "1.5", "package test; public class test {\npublic static abstract class Inner1<T> {} public <T> Inner1<T> ret() {return null;}\n}", "1.5", true, "test.test$Inner1");
941     }
942     
943     public void testCompileAgainstInnerClassWithGenerics9() throws Exception JavaDoc {
944         performCompileAgainst("package test; public class test2 {\npublic void testMethod2() {test<String>.Inner1<java.util.Comparator> t1;}\n}", "1.5", "package test; public class test<E> {\npublic abstract class Inner1<T> {} public <T> Inner1<T> ret() {return null;}\n}", "1.5", true, "test.test$Inner1");
945     }
946     
947     public void testCompileAgainstLocalClassWithGenerics1() throws Exception JavaDoc {
948         performCompileAgainst("package test; public class test2 {\npublic void testMethod2() {test.Inner1<java.util.Comparator> t1;}\n}", "1.5", "package test; public class test {\npublic static abstract class Inner1<T> {} public <T> Inner1<T> ret() {class X extends Inner1<T>{} return null;}\n}", "1.5", false, "test.test$Inner1");
949     }
950     
951     public void testCompileAgainstInnerClass1() throws Exception JavaDoc {
952         performCompileAgainst("package test; public class test2 {\npublic void testMethod2() {test.Inner t = new test.Inner(null);}\n}", "1.5", "package test; public class test {\npublic static class Inner {Inner(Runnable r){}}\n}", "1.5", false);
953     }
954     
955     public void testCompileAgainstInnerClass2() throws Exception JavaDoc {
956         performCompileAgainst("package test; import test.test.Inner; public class test2 {\npublic void testMethod2() {test t = new test(); Inner i = t.new Inner(null);}\n}", "1.5", "package test; public class test {\npublic class Inner {Inner(Runnable r){}}\n}", "1.5", false);
957     }
958     
959     public void testCompileAgainstEnum1() throws Exception JavaDoc {
960         performCompileAgainst("package test; public class test2 {\npublic void testMethod2() {test t = null; switch (t) {case VALUE1: break;case VALUE2: break;}}}", "package test; public enum test {VALUE1, VALUE2; public int test() {return 0;}\n}");
961     }
962     
963     public void testCompileAgainstEnum2() throws Exception JavaDoc {
964         performCompileAgainst("package test; public class test2 {\npublic test get() {return null;} public void testMethod2() {switch (get()) {case VALUE1: break;case VALUE2: break;}}}", "package test; public enum test {VALUE1, VALUE2; public int test() {return 0;}\n}");
965     }
966     
967     public void testCompileAgainstEnum3() throws Exception JavaDoc {
968         performCompileAgainst("package test; public class test2 {\npublic void testMethod2() {for (test t : test.values()) ;}}", "package test; public enum test {VALUE1, VALUE2; public int test() {return 0;}\n}");
969     }
970     
971     public void testCompileAgainstAnnotation1() throws Exception JavaDoc {
972         performCompileAgainst("package test; @test(review=2) public class test2 {}", "package test; public @interface test {\n String author() default \"unknown\";\n int review();\n}");
973     }
974     
975     public void testCompileAgainstAnnotation2() throws Exception JavaDoc {
976         performCompileAgainst("package test; @test(review=2) public class test2 {}", "package test; public @interface test {\n Class x() default Object.class;\n int review();\n}");
977     }
978     
979     public void testCompileAgainstAnnotation3() throws Exception JavaDoc {
980         performCompileAgainst("package test; @test(review=2) public class test2 {}", "package test; public @interface test {\n Class x() default int.class;\n int review();\n}");
981     }
982     
983     public void testCompileAgainstAnnotation4() throws Exception JavaDoc {
984         performCompileAgainst("package test; @test(review=2) public class test2 {}", "package test; public @interface test {\n Class x() default java.util.List.class;\n int review();\n}");
985     }
986     
987     public void testCompileAgainstInterface1() throws Exception JavaDoc {
988         performCompileAgainst("package test; public class test2 {public void x() {java.util.Set<test> s;}}", "package test; public interface test {\n}");
989     }
990     
991     public void testCompileAgainstInterface2() throws Exception JavaDoc {
992         performCompileAgainst("package test; public class test2 {public <T> T x(Class<T> c) {return null;} public void xx() {x(test.class);}}", "package test; public interface test {\n}");
993     }
994     
995     public void testCompileAgainstInterface3() throws Exception JavaDoc {
996         performCompileAgainst("package test; public class test2 {public void x() {test s = null; if (s == null) return;}}", "package test; public interface test {\n}");
997     }
998     
999     protected void performCompileAgainst(String JavaDoc what, String JavaDoc against) throws Exception JavaDoc {
1000        performCompileAgainst(what, "1.5", against, "1.5", true);
1001    }
1002    
1003    protected void performCompileAgainst(String JavaDoc what, String JavaDoc whatSourceLevel, String JavaDoc against, String JavaDoc againstLevel, boolean compareSignatures) throws Exception JavaDoc {
1004        performCompileAgainst(what, whatSourceLevel, against, againstLevel, compareSignatures, null);
1005    }
1006    
1007    protected void performCompileAgainst(String JavaDoc what, String JavaDoc whatSourceLevel, String JavaDoc against, String JavaDoc againstLevel, boolean compareSignatures, final String JavaDoc firstToComplete) throws Exception JavaDoc {
1008        FileSystem fs = FileUtil.createMemoryFileSystem();
1009        FileObject file = fs.getRoot().createData("test.java");
1010        
1011        writeIntoFile(file, against);
1012        
1013        SourceUtilsTestUtil.setSourceLevel(file, againstLevel);
1014        
1015        JavaSource js = JavaSource.forFileObject(file);
1016        CompilationInfo info = SourceUtilsTestUtil.getCompilationInfo(js, Phase.RESOLVED);
1017        CompilationUnitTree unit = info.getCompilationUnit();
1018        assertTrue(info.getDiagnostics().toString(), info.getDiagnostics().isEmpty());
1019        
1020        Tree main = unit.getTypeDecls().iterator().next();
1021        TypeElement type = (TypeElement) info.getTrees().getElement(new TreePath(new TreePath(unit), main));
1022        
1023        final Map JavaDoc<String JavaDoc, String JavaDoc> signatures = dumpIncludingInnerClasses(info, type);
1024        
1025        System.err.println("sig=" + signatures);
1026        
1027        FileObject file2 = fs.getRoot().createData("test2.java");
1028        
1029        writeIntoFile(file2, what);
1030        
1031        SourceUtilsTestUtil.setSourceLevel(file2, whatSourceLevel);
1032        
1033        JavaSource js2 = JavaSource.forFileObject(file2);
1034        final CountDownLatch JavaDoc l = new CountDownLatch JavaDoc(1);
1035        
1036        final String JavaDoc[] newSig = new String JavaDoc[1];
1037        final List JavaDoc[] errors = new List JavaDoc[1];
1038        
1039        js2.runUserActionTask(new CancellableTask<CompilationController>() {
1040            public void cancel() {
1041            }
1042            public void run(CompilationController parameter) {
1043                try {
1044                    parameter.toPhase(Phase.PARSED);
1045                    JavacTaskImpl task = (JavacTaskImpl) SourceUtilsTestUtil.getJavacTaskFor(parameter);
1046                    Context context = task.getContext();
1047                    Table table = Table.instance(context);
1048                    SymbolClassReader reader = (SymbolClassReader) ClassReader.instance(context);
1049                    Name className = Name.Table.instance(context).fromString("test");
1050                    
1051                    PackageSymbol pack = reader.enterPackage(Name.Table.instance(context).fromString("test"));
1052                    
1053                    assertNotNull(pack);
1054                    
1055                    pack.complete();
1056                    
1057                    for (Map.Entry JavaDoc<String JavaDoc, String JavaDoc> entry : signatures.entrySet()) {
1058                        reader.includeClassFile(pack, FileObjects.memoryFileObject(entry.getValue(), entry.getKey() + ".sig"));
1059                    }
1060                    
1061                    if (firstToComplete != null) {
1062                        Name flatName = table.fromString(firstToComplete);
1063                        
1064                        reader.enterClass(flatName).complete();
1065                    }
1066                    
1067                    ClassSymbol cs = reader.enterClass(className, pack);
1068                    
1069                    cs.complete();
1070                    
1071                    parameter.toPhase(Phase.RESOLVED);
1072                    
1073                    JavacTaskImpl jt = (JavacTaskImpl)SourceUtilsTestUtil.getJavacTaskFor(parameter);
1074                    newSig[0] = dump(Types.instance(jt.getContext()), cs);
1075                    
1076                    errors[0] = parameter.getDiagnostics();
1077                } catch (Exception JavaDoc e) {
1078                    e.printStackTrace();
1079                }
1080                
1081                l.countDown();
1082            }
1083        },false);
1084        
1085        l.await();
1086        
1087                    
1088        assertTrue(errors[0].toString(), errors[0].isEmpty());
1089        
1090        if (compareSignatures)
1091            assertEquals(signatures.get("test"), newSig[0]);
1092    }
1093
1094    protected void performCompileAgainstSingature(String JavaDoc what, final String JavaDoc againstSignature) throws Exception JavaDoc {
1095        FileSystem fs = FileUtil.createMemoryFileSystem();
1096        FileObject file2 = fs.getRoot().createData("test2.java");
1097        
1098        writeIntoFile(file2, what);
1099        
1100        SourceUtilsTestUtil.setSourceLevel(file2, "1.5");
1101        
1102        JavaSource js2 = JavaSource.forFileObject(file2);
1103        final CountDownLatch JavaDoc l = new CountDownLatch JavaDoc(1);
1104        
1105        final Map JavaDoc<String JavaDoc, String JavaDoc>[] newSig = new Map JavaDoc[1];
1106        final List JavaDoc[] errors = new List JavaDoc[1];
1107        
1108        js2.runUserActionTask(new CancellableTask<CompilationController>() {
1109            public void cancel() {
1110            }
1111            public void run(CompilationController parameter) {
1112                try {
1113                    parameter.toPhase(Phase.PARSED);
1114                    JavacTaskImpl task = (JavacTaskImpl) SourceUtilsTestUtil.getJavacTaskFor(parameter);
1115                    Context context = task.getContext();
1116                    Table table = Table.instance(context);
1117                    SymbolClassReader reader = (SymbolClassReader) ClassReader.instance(context);
1118                    Name className = Name.Table.instance(context).fromString("test");
1119                    
1120                    PackageSymbol pack = reader.enterPackage(Name.Table.instance(context).fromString("test"));
1121                    
1122                    assertNotNull(pack);
1123                    
1124                    pack.complete();
1125                    
1126                    reader.includeClassFile(pack, FileObjects.memoryFileObject(againstSignature, "test.sig"));
1127                    
1128                    ClassSymbol cs = reader.enterClass(className, pack);
1129                    
1130                    cs.complete();
1131                    
1132                    parameter.toPhase(Phase.RESOLVED);
1133                    
1134                    newSig[0] = dumpIncludingInnerClasses(parameter, cs);
1135                    
1136                    errors[0] = parameter.getDiagnostics();
1137                } catch (Exception JavaDoc e) {
1138                    e.printStackTrace();
1139                }
1140                
1141                l.countDown();
1142            }
1143        },false);
1144        
1145        l.await();
1146        
1147                    
1148        assertTrue(errors[0].toString(), errors[0].isEmpty());
1149// System.err.println("newSig=" + newSig[0]);
1150
}
1151    
1152    public void testNarazecka() throws Exception JavaDoc {
1153        performTestNarazecka("package test; public class test {public void testMethod() {new Runnable() {public void run(){}};}}\n", "test.test$1");
1154    }
1155    
1156    //TODO: the following two tests represent unfixed bugs:
1157
// public void testNarazecka2() throws Exception {
1158
// performTestNarazecka("package test; public class test<I, T> {private java.util.List<Snap> snaps; private class Snap {}}\n", "test.test$Snap");
1159
// }
1160
//
1161
// public void testNarazecka3() throws Exception {
1162
// performTestNarazecka("package test; public class test {private annotations.RequestProcessor.Task task; public static class O {}}\n", "test.test$O");
1163
// }
1164

1165    public void testNarazecka4() throws Exception JavaDoc {
1166        performTestNarazecka("package test;import java.util.Collection;" +
1167                " abstract class Lookup {" +
1168                " public static final Lookup EMPTY = null;" +
1169                " private static Lookup defaultLookup;" +
1170                " public Lookup() {}" +
1171                " public static synchronized Lookup getDefault() {return null;}" +
1172                " private static final class DefLookup {}" +
1173                " private static void resetDefaultLookup() {}" +
1174                " public abstract <T> T lookup(Class<T> clazz);" +
1175                " public abstract <T> Result<T> lookup(Template<T> template);" +
1176                " public <T> Item<T> lookupItem(Template<T> template) {return null;}" +
1177                " public <T> Lookup.Result<T> lookupResult(Class<T> clazz) {return null;}" +
1178                " public <T> Collection<? extends T> lookupAll(Class<T> clazz) {return null;}" +
1179                " public interface Provider {}" +
1180                " public static final class Template<T> extends Object {}" +
1181                " public static abstract class Result<T> extends Object {}" +
1182                " public static abstract class Item<T> extends Object {}" +
1183                " private static abstract class Empty extends Lookup {}" +
1184                "}", "test.Lookup$Template");
1185    }
1186
1187    public void testNarazecka5() throws Exception JavaDoc {
1188        performTestNarazecka("package test; public class test {private static Deleg cur; private static class Deleg extends test {}}\n", "test.test$Deleg");
1189    }
1190    
1191    public void testNarazecka6() throws Exception JavaDoc {
1192        performTestNarazecka("package test; public class test {public final class Deleg {Deleg(Runnable r) {} Deleg(Runnable r, int x) {}}}\n", "test.test$Deleg");
1193    }
1194    
1195    public void testNarazecka7() throws Exception JavaDoc {
1196        performTestNarazecka("package test; public class test {public <T> Two<T> lookup(One<T> o){return null;} public static class One<T> {}public static class Two<T> {}}\n", "test.test$One");
1197    }
1198    
1199    private void performTestNarazecka(String JavaDoc what, final String JavaDoc innerclassName) throws Exception JavaDoc {
1200        FileSystem fs = FileUtil.createMemoryFileSystem();
1201        FileObject file = fs.getRoot().createData("test.java");
1202        
1203        writeIntoFile(file, what);
1204        
1205        JavaSource js = JavaSource.forFileObject(file);
1206        CompilationInfo info = SourceUtilsTestUtil.getCompilationInfo(js, Phase.RESOLVED);
1207        CompilationUnitTree unit = info.getCompilationUnit();
1208        assertTrue(info.getDiagnostics().toString(), info.getDiagnostics().isEmpty());
1209        
1210        Tree main = unit.getTypeDecls().iterator().next();
1211        TypeElement type = (TypeElement) info.getTrees().getElement(new TreePath(new TreePath(unit), main));
1212        
1213        final Map JavaDoc<String JavaDoc, String JavaDoc> signatures = dumpIncludingInnerClasses(info, type);
1214        
1215        System.err.println("sig=" + signatures);
1216        
1217        FileObject file2 = fs.getRoot().createData("test2.java");
1218        
1219        writeIntoFile(file2, "package test; public class test2{}");
1220        
1221        JavaSource js2 = JavaSource.create(ClasspathInfo.create(file), file2, file);
1222        
1223        final List JavaDoc[] errors = new List JavaDoc[1];
1224        
1225        js2.runUserActionTask(new CancellableTask<CompilationController>() {
1226            private TypeElement firstClass;
1227            private TypeElement innerClass;
1228            public void cancel() {
1229            }
1230            public void run(CompilationController parameter) throws Exception JavaDoc {
1231                CouplingAbort.wasCouplingError = false;
1232                try {
1233                    JavacTaskImpl task = (JavacTaskImpl) SourceUtilsTestUtil.getJavacTaskFor(parameter);
1234                    Context context = task.getContext();
1235                    Table table = Table.instance(context);
1236                    SymbolClassReader reader = (SymbolClassReader) ClassReader.instance(context);
1237                    Name className = Name.Table.instance(context).fromString("test");
1238                    
1239                    PackageSymbol pack = reader.enterPackage(Name.Table.instance(context).fromString("test"));
1240                    
1241                    assertNotNull(pack);
1242                    
1243                    pack.complete();
1244                    
1245                    for (Map.Entry JavaDoc<String JavaDoc, String JavaDoc> entry : signatures.entrySet()) {
1246                        reader.includeClassFile(pack, FileObjects.memoryFileObject(entry.getValue(), entry.getKey() + ".sig"));
1247                    }
1248                    
1249                    parameter.toPhase(Phase.RESOLVED);
1250                    
1251                    assertFalse(CouplingAbort.wasCouplingError);
1252                    
1253                    if (firstClass == null) {
1254                        JavacElements jels = (JavacElements) parameter.getElements();
1255                        
1256                        firstClass = jels.getTypeElementByBinaryName("test.test");
1257                        innerClass = jels.getTypeElementByBinaryName(innerclassName);
1258                        return;
1259                    }
1260                } catch (Exception JavaDoc e) {
1261                    e.printStackTrace();
1262                }
1263                
1264                assertFalse(CouplingAbort.wasCouplingError);
1265            }
1266        },true);
1267    }
1268    
1269// public void testCompileAgainstSignature1() throws Exception {
1270
// performCompileAgainstSingature("package test; public class test2 {\npublic void testMethod2() {try {org.openide.nodes.Node.Property p = null; Long.parseLong(p.toString());} catch (Exception e) {}}\n}",
1271
// "GM1;<T:Ljava.lang.Object;;>Ntest.test;Ljava.lang.Object;@\n" +
1272
// "EM1040000001;N<init>;()()V\n" +
1273
// "AM40000;Lorg.openide.nodes.Node;Nm;X;"
1274
// );
1275
// }
1276

1277    private static class SourceAnalyserImpl extends SourceAnalyser.UsagesVisitor {
1278        
1279        private Map JavaDoc<String JavaDoc, String JavaDoc> class2Sig = new TreeMap JavaDoc<String JavaDoc, String JavaDoc>();
1280        
1281        public SourceAnalyserImpl(JavacTaskImpl jt, CompilationUnitTree cu) {
1282            super(jt, cu, null);
1283        }
1284        
1285        @Override JavaDoc void dump(TypeElement clazz, String JavaDoc className, Element enclosingMethod) {
1286            StringWriter JavaDoc w = new StringWriter JavaDoc();
1287            PrintWriter JavaDoc pw = new PrintWriter JavaDoc(w);
1288            
1289            SymbolDumper.dump(pw, getTypes(), clazz, enclosingMethod);
1290            
1291            pw.close();
1292            
1293            String JavaDoc flatName = ((ClassSymbol) clazz).flatname.toString();
1294            String JavaDoc fileName = flatName.substring(flatName.lastIndexOf('.') + 1);
1295            
1296            class2Sig.put(fileName, w.toString());
1297        }
1298        
1299        @Override JavaDoc protected boolean shouldGenerate (final String JavaDoc binaryName, ClassSymbol sym) {
1300            return true;
1301        }
1302        
1303    }
1304  
1305    //XXX: test for writing and reading java.lang.Object:
1306
// public void testJavaLangObject() throws Exception {
1307
// FileSystem fs = FileUtil.createMemoryFileSystem();
1308
// FileObject obj = FileUtil.createData(fs.getRoot(), "java/lang/Object.java");
1309
//
1310
// writeIntoFile(obj, "package java.lang; public class Object {public Object(){} public Object get() {return null;}}");
1311
//
1312
// JavaSource js = JavaSource.forFileObject(obj);
1313
// CompilationInfo info = SourceUtilsTestUtil.getCompilationInfo(js, Phase.RESOLVED);
1314
// CompilationUnitTree unit = info.getCompilationUnit();
1315
// assertTrue(info.getDiagnostics().toString(), info.getDiagnostics().isEmpty());
1316
//
1317
// Tree main = unit.getTypeDecls().iterator().next();
1318
// TypeElement type = (TypeElement) info.getTrees().getElement(new TreePath(new TreePath(unit), main));
1319
//
1320
// final Map<String, String> signatures = dumpIncludingInnerClasses(info, type);
1321
//
1322
// System.err.println("sig=" + signatures);
1323
//
1324
// FileObject file2 = fs.getRoot().createData("test2.java");
1325
//
1326
// writeIntoFile(file2, "package test; public class test2{private Object x = get();}");
1327
//
1328
// JavaSource js2 = JavaSource.create(ClasspathInfo.create(obj), file2, obj);
1329
//
1330
// final List[] errors = new List[1];
1331
//
1332
// js2.runUserActionTask(new CancellableTask<CompilationController>() {
1333
// public void cancel() {
1334
// }
1335
// public void run(CompilationController parameter) {
1336
// try {
1337
// JavacTaskImpl task = (JavacTaskImpl) SourceUtilsTestUtil.getJavacTaskFor(parameter);
1338
// Context context = task.getContext();
1339
// Table table = Table.instance(context);
1340
// SymbolClassReader reader = (SymbolClassReader) ClassReader.instance(context);
1341
// Name className = Name.Table.instance(context).fromString("Object");
1342
//
1343
// PackageSymbol pack = reader.enterPackage(Name.Table.instance(context).fromString("java.lang"));
1344
//
1345
// assertNotNull(pack);
1346
//
1347
// pack.complete();
1348
//
1349
// for (Map.Entry<String, String> entry : signatures.entrySet()) {
1350
// reader.includeClassFile(pack, FileObjects.memoryFileObject(entry.getValue(), entry.getKey() + ".sig"));
1351
// }
1352
//
1353
// parameter.toPhase(Phase.RESOLVED);
1354
// } catch (Exception e) {
1355
// e.printStackTrace();
1356
// }
1357
// }
1358
// },true);
1359
// }
1360
}
1361
Popular Tags