KickJava   Java API By Example, From Geeks To Geeks.

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


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-2006 Sun
17  * Microsystems, Inc. All Rights Reserved.
18  */

19
20 package org.netbeans.modules.java.source.usages;
21
22 import com.sun.source.util.JavacTask;
23 import com.sun.tools.javac.api.JavacTaskImpl;
24 import com.sun.tools.javac.model.JavacElements;
25 import java.util.Arrays JavaDoc;
26 import java.util.Collections JavaDoc;
27 import java.util.LinkedList JavaDoc;
28 import java.util.StringTokenizer JavaDoc;
29 import java.util.zip.ZipEntry JavaDoc;
30 import java.util.zip.ZipFile JavaDoc;
31 import javax.lang.model.element.Element;
32 import javax.lang.model.element.ElementKind;
33 import javax.lang.model.element.ExecutableElement;
34 import javax.lang.model.element.TypeElement;
35 import javax.lang.model.element.VariableElement;
36 import javax.lang.model.util.Elements;
37 import javax.tools.JavaCompiler;
38 import javax.tools.JavaCompiler.CompilationTask;
39 import javax.tools.JavaFileObject;
40 import javax.tools.StandardJavaFileManager;
41 import javax.tools.ToolProvider;
42 import java.io.File JavaDoc;
43 import java.io.InputStream JavaDoc;
44 import java.util.EnumSet JavaDoc;
45 import java.util.HashSet JavaDoc;
46 import java.util.List JavaDoc;
47 import java.util.Set JavaDoc;
48 import org.netbeans.junit.NbTestCase;
49 import org.netbeans.modules.classfile.ClassFile;
50 import org.netbeans.modules.classfile.ClassName;
51 import org.netbeans.modules.classfile.Method;
52 import org.netbeans.modules.classfile.Variable;
53 import org.netbeans.modules.java.source.parsing.FileObjects;
54 import org.netbeans.modules.java.source.usages.ClassIndexImpl.UsageType;
55
56 /**
57  *
58  * @author Tomas Zezula
59  */

60 public class CompromiseSATest extends NbTestCase {
61     
62     private static final String JavaDoc TEST_CLASS = "java.util.ArrayList"; //NOI18N
63
private static final String JavaDoc TEST_INNER_CLASS = "java.util.Collections$SingletonSet"; //NOI18N
64
private static final String JavaDoc TEST_INNER_CLASS_2 = "java.util.Collections$SingletonMap$ImmutableEntry"; //NOI18N
65
private static final String JavaDoc TEST_INNER_CLASS_3 = "javax.swing.JTable$AccessibleJTable$AccessibleJTableCell"; //NOI18N
66
private static final String JavaDoc TEST_ANNON_CLASS = "java.lang.String$1"; //NOI18N
67

68     private static final String JavaDoc[] METHOD_TYPE_SIGNATURES = new String JavaDoc[] {
69         "<S:Ljava/lang/String;L:Ljava/lang/Long;>(TS;TL;)TT;",
70         "<C::Ljava/lang/Comparable<+Lfoo/A;>;>(TC;Lfoo/A;)I",
71         "(ILjava/util/Set<Ljava/lang/Integer;>;)V",
72         "<X:Ljava/lang/Object;:Ljava/lang/Comparable<-TX;>;>(Ljava/util/Set<TX;>;)TX;"
73     };
74     
75     private static final String JavaDoc[][] METHOD_TYPE_SIGNATURES_RESULT = new String JavaDoc[][] {
76         new String JavaDoc[] {
77             "java/lang/String",
78             "java/lang/Long"
79         },
80         new String JavaDoc[] {
81             "java/lang/Comparable",
82             "foo/A"
83         },
84         new String JavaDoc[] {
85             "java/lang/Integer"
86         },
87         new String JavaDoc[] {
88             "java/lang/Object",
89             "java/lang/Comparable",
90         }
91     };
92     
93     private static final String JavaDoc[] FIELD_TYPE_SIGNATURES = new String JavaDoc[] {
94         "TT;",
95         "Ljava/util/Collection<Ljava/lang/Long;>;",
96         "Lfoo/A<TT;>;",
97         "Ljava/util/Set<Ljava/lang/Integer;>;",
98         "Ljava/util/Set<TX;>;",
99     };
100     
101     private static final String JavaDoc[][] FIELD_TYPE_SIGNATURES_RESULT = new String JavaDoc[][] {
102         new String JavaDoc[0],
103         new String JavaDoc[] {
104             "java/lang/Long"
105         },
106         new String JavaDoc[0],
107         new String JavaDoc[] {
108             "java/lang/Integer",
109         },
110         new String JavaDoc[0]
111     };
112     
113     private static final String JavaDoc[] CLASS_TYPE_SIGNATURES = new String JavaDoc[] {
114         "<T:Ljava/lang/Integer;>Ljava/lang/Object;"
115     };
116     
117     private static final String JavaDoc[][] CLASS_TYPE_SIGNATURES_RESLT = new String JavaDoc[][] {
118         new String JavaDoc[] {
119             "java/lang/Integer"
120         }
121     };
122     
123     public CompromiseSATest(String JavaDoc testName) {
124         super(testName);
125     }
126
127     protected @Override JavaDoc void setUp() throws Exception JavaDoc {
128         super.setUp();
129     this.clearWorkDir();
130     }
131     
132
133     /**
134      * Tests (=(decode (encode T)) T)
135      */

136     public void testEncodeUsageType() {
137         EnumSet JavaDoc<UsageType> c = EnumSet.noneOf(UsageType.class);
138         c.add (UsageType.SUPER_CLASS);
139         c.add (UsageType.SUPER_INTERFACE);
140         String JavaDoc s = DocumentUtil.encodeUsage("foo", c);
141         Set JavaDoc<UsageType> r = EnumSet.noneOf(UsageType.class);
142         DocumentUtil.decodeUsage(s,r);
143         assertEquals(c.size(), r.size());
144         assertTrue(r.containsAll(c));
145         c.clear();
146         c.add (UsageType.TYPE_REFERENCE);
147         s = DocumentUtil.encodeUsage("foo", c);
148         r = EnumSet.noneOf(UsageType.class);
149         DocumentUtil.decodeUsage(s,r);
150         assertEquals(c.size(), r.size());
151         assertTrue(r.containsAll(c));
152         c.clear();
153         c.add (UsageType.SUPER_CLASS);
154         c.add (UsageType.TYPE_REFERENCE);
155         c.add (UsageType.FIELD_REFERENCE);
156         s = DocumentUtil.encodeUsage("foo", c);
157         r = EnumSet.noneOf(UsageType.class);
158         DocumentUtil.decodeUsage(s,r);
159         assertEquals(c.size(), r.size());
160         assertTrue(r.containsAll(c));
161         c.clear();
162         c.add (UsageType.SUPER_CLASS);
163         c.add (UsageType.METHOD_REFERENCE);
164         s = DocumentUtil.encodeUsage("foo", c);
165         r = EnumSet.noneOf(UsageType.class);
166         DocumentUtil.decodeUsage(s,r);
167         assertEquals(c.size(), r.size());
168         assertTrue(r.containsAll(c));
169         c.clear();
170         c.allOf(UsageType.class);
171         s = DocumentUtil.encodeUsage("foo", c);
172         r = EnumSet.noneOf(UsageType.class);
173         DocumentUtil.decodeUsage(s,r);
174         assertEquals(c.size(), r.size());
175         assertTrue(r.containsAll(c));
176         c.clear();
177         c.add (UsageType.SUPER_INTERFACE);
178         c.add (UsageType.METHOD_REFERENCE);
179         s = DocumentUtil.encodeUsage("foo", c);
180         r = EnumSet.noneOf(UsageType.class);
181         DocumentUtil.decodeUsage(s,r);
182         assertEquals(c.size(), r.size());
183         assertTrue(r.containsAll(c));
184         c.clear();
185     }
186     
187     
188     public void testClassTypeSignatureParser () {
189         for (int i=0; i< CLASS_TYPE_SIGNATURES.length; i++) {
190             String JavaDoc sig = CLASS_TYPE_SIGNATURES[i];
191             ClassName[] names = ClassFileUtil.getTypesFromClassTypeSignature(sig);
192             assertEquals(CLASS_TYPE_SIGNATURES_RESLT[i].length, names.length);
193             assertEqulas (CLASS_TYPE_SIGNATURES_RESLT[i], names);
194         }
195     }
196     
197     public void testFieldTypeSignatureParser () {
198         for (int i=0; i< FIELD_TYPE_SIGNATURES.length; i++) {
199             String JavaDoc sig = FIELD_TYPE_SIGNATURES[i];
200             ClassName[] names = ClassFileUtil.getTypesFromFiledTypeSignature(sig);
201             assertEquals(FIELD_TYPE_SIGNATURES_RESULT[i].length, names.length);
202             assertEqulas (FIELD_TYPE_SIGNATURES_RESULT[i], names);
203         }
204     }
205     
206     public void testMethodTypeSignatureParser () {
207         for (int i=0; i< METHOD_TYPE_SIGNATURES.length; i++) {
208             String JavaDoc sig = METHOD_TYPE_SIGNATURES[i];
209             ClassName[] names = ClassFileUtil.getTypesFromMethodTypeSignature(sig);
210             assertEquals(METHOD_TYPE_SIGNATURES_RESULT[i].length, names.length);
211             assertEqulas (METHOD_TYPE_SIGNATURES_RESULT[i], names);
212         }
213     }
214     
215     public void testClassSignatureFromElement () throws Exception JavaDoc {
216             performClassSignatureFromElementTest (TEST_CLASS);
217             performClassSignatureFromElementTest (TEST_INNER_CLASS);
218             performClassSignatureFromElementTest (TEST_INNER_CLASS_2);
219             performClassSignatureFromElementTest (TEST_INNER_CLASS_3);
220             performClassSignatureFromElementTest (TEST_ANNON_CLASS);
221     }
222
223     private void performClassSignatureFromElementTest (final String JavaDoc testClassName) throws Exception JavaDoc {
224         InputStream JavaDoc in = this.prepareData (testClassName);
225     try {
226         JavacTask jt = prepareJavac ();
227         JavacElements elements = (JavacElements) jt.getElements();
228         TypeElement be = elements.getTypeElementByBinaryName(testClassName);
229             assertNotNull ("Javac Error", be);
230         String JavaDoc className = ClassFileUtil.encodeClassName(be);
231         ClassFile cf = new ClassFile (in, true);
232         String JavaDoc expectedName = cf.getName().getInternalName().replace('/','.'); //NOI18N
233
assertEquals (expectedName, className);
234     } finally {
235         in.close ();
236     }
237     }
238     
239     public void testMethodSignatureFromElement () throws Exception JavaDoc {
240     InputStream JavaDoc in = this.prepareData(TEST_CLASS);
241     try {
242         JavacTask jt = prepareJavac ();
243         Elements elements = jt.getElements();
244         TypeElement be = elements.getTypeElement(TEST_CLASS);
245         ClassFile cf = new ClassFile (in, true);
246         String JavaDoc className = cf.getName().getInternalName().replace('/','.'); //NOI18N
247
List JavaDoc<? extends Element> members = be.getEnclosedElements();
248         for (Element e : members) {
249         if (e.getKind() == ElementKind.METHOD) {
250             String JavaDoc[] msig = ClassFileUtil.createExecutableDescriptor((ExecutableElement) e);
251             assertEquals (className,msig[0]);
252             assertEquals (e.getSimpleName().toString(),msig[1]);
253             Method m = cf.getMethod(e.getSimpleName().toString(),msig[2]);
254             assertNotNull (m);
255         }
256         }
257     } finally {
258         in.close ();
259     }
260     }
261     
262     public void testConstructorSignatureFromElement () throws Exception JavaDoc {
263     InputStream JavaDoc in = this.prepareData(TEST_CLASS);
264     try {
265         JavacTask jt = prepareJavac ();
266         Elements elements = jt.getElements();
267         TypeElement be = elements.getTypeElement(TEST_CLASS);
268         ClassFile cf = new ClassFile (in, true);
269         String JavaDoc className = cf.getName().getInternalName().replace('/','.'); //NOI18N
270
List JavaDoc<? extends Element> members = be.getEnclosedElements();
271         for (Element e : members) {
272         if (e.getKind() == ElementKind.CONSTRUCTOR) {
273             String JavaDoc[] msig = ClassFileUtil.createExecutableDescriptor((ExecutableElement) e);
274             assertEquals (className,msig[0]);
275             assertEquals (e.getSimpleName().toString(),msig[1]);
276             Method m = cf.getMethod (e.getSimpleName().toString(),msig[2]);
277             assertNotNull (m);
278         }
279         }
280     } finally {
281         in.close ();
282     }
283     }
284     
285     public void testFieldSignatureFromElement () throws Exception JavaDoc {
286     InputStream JavaDoc in = this.prepareData(TEST_CLASS);
287     try {
288         JavacTask jt = prepareJavac ();
289         Elements elements = jt.getElements();
290         TypeElement be = elements.getTypeElement(TEST_CLASS);
291         ClassFile cf = new ClassFile (in, true);
292         String JavaDoc className = cf.getName().getInternalName().replace('/','.'); //NOI18N
293
List JavaDoc<? extends Element> members = be.getEnclosedElements();
294         for (Element e : members) {
295         if (e.getKind() == ElementKind.FIELD) {
296             String JavaDoc[] msig = ClassFileUtil.createFieldDescriptor((VariableElement) e);
297             assertEquals (className,msig[0]);
298             assertEquals (e.getSimpleName().toString(),msig[1]);
299             Variable v = cf.getVariable (e.getSimpleName().toString());
300             assertNotNull (v);
301             assertEquals (v.getDescriptor(), msig[2]);
302         }
303         }
304     } finally {
305         in.close ();
306     }
307     }
308     
309 // public void testTypeSignatureFromErrorType () throws Exception {
310
// JavacTaskImpl jt = (JavacTaskImpl) prepareJavac (Collections.singletonList(FileObjects.memoryFileObject("public class Test { public TTT foo () {}}","Test")));
311
// jt.parse();
312
// Iterable<? extends TypeElement> elements = jt.enter();
313
// assertTrue (env.getElements().iterator().hasNext());
314
// TypeElement e = env.getElements().iterator().next();
315
// List<? extends Element> members = e.getEnclosedElements();
316
// ExecutableElement emember = null;
317
// for (Element member : members) {
318
// if (member.getKind() == ElementKind.METHOD && "foo".contentEquals(member.getSimpleName())) {
319
// emember = (ExecutableElement) member;
320
// break;
321
// }
322
// }
323
// assertNotNull (emember);
324
// String[] sig = ClassFileUtil.createExecutableDescriptor(emember);
325
// assertEquals("Test",sig[0]);
326
// assertEquals("foo",sig[1]);
327
// assertEquals("()LTTT;",sig[2]);
328
// }
329

330     private String JavaDoc getBootClassPath () {
331     String JavaDoc bootCp = System.getProperty ("sun.boot.class.path");
332     assert bootCp != null;
333     return bootCp;
334     }
335     
336     private File JavaDoc getRT_JAR () {
337     StringTokenizer JavaDoc tk = new StringTokenizer JavaDoc (getBootClassPath (), File.pathSeparator);
338     while (tk.hasMoreTokens()) {
339         String JavaDoc token = tk.nextToken();
340         if (token.endsWith("rt.jar")) {
341         File JavaDoc f = new File JavaDoc (token);
342         assert f.canRead();
343         return f;
344         }
345     }
346     throw new AssertionError JavaDoc ();
347     }
348     
349     private InputStream JavaDoc prepareData (final String JavaDoc testClassName) throws Exception JavaDoc {
350     ZipFile JavaDoc zf = new ZipFile JavaDoc (getRT_JAR());
351     ZipEntry JavaDoc ze = zf.getEntry(testClassName.replace('.','/')+".class");
352     InputStream JavaDoc in = zf.getInputStream(ze);
353     return in;
354     }
355     
356     private JavacTask prepareJavac () throws Exception JavaDoc {
357         return prepareJavac (Collections.<JavaFileObject>emptySet());
358     }
359     
360     
361     private JavacTask prepareJavac (Iterable JavaDoc<JavaFileObject> toParse) throws Exception JavaDoc {
362     JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
363         StandardJavaFileManager fm = tool.getStandardFileManager(null, null, null);
364         List JavaDoc<String JavaDoc> options = new LinkedList JavaDoc<String JavaDoc>();
365         options.add ("-Xjcov"); // Make the compiler store end positions
366
options.add ("-g:"); // Enable some debug info
367
options.add ("-g:lines" ); // Make the compiler to maintain line table
368
options.add("-g:vars" ); // Make the compiler to maintain local variables table
369
options.add ("-bootclasspath");
370         options.add (getBootClassPath());
371         CompilationTask jt = tool.getTask(null,fm,null,options,null,toParse);
372         assert jt instanceof JavacTask;
373     return (JavacTask)jt;
374     }
375     
376     private void assertEqulas (String JavaDoc[] result, ClassName[] names) {
377         Set JavaDoc<String JavaDoc> res = new HashSet JavaDoc<String JavaDoc> (Arrays.asList(result));
378         for (ClassName cn: names) {
379             String JavaDoc in = cn.getInternalName();
380             if (!res.remove(in)) {
381                 assertTrue(false);
382             }
383         }
384     }
385
386
387     
388 }
389
Popular Tags