KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > modules > java > editor > codegen > GeneratorUtilsTest


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.editor.codegen;
21
22 import com.sun.source.util.TreePath;
23 import java.beans.PropertyVetoException JavaDoc;
24 import java.io.File JavaDoc;
25 import java.io.IOException JavaDoc;
26 import java.io.OutputStream JavaDoc;
27 import javax.lang.model.element.ExecutableElement;
28 import javax.lang.model.element.TypeElement;
29 import javax.lang.model.type.TypeMirror;
30 import javax.lang.model.util.ElementFilter;
31 import org.netbeans.api.java.source.CancellableTask;
32 import org.netbeans.api.java.source.CompilationController;
33 import org.netbeans.api.java.source.CompilationInfo;
34 import org.netbeans.api.java.source.JavaSource;
35 import org.netbeans.api.java.source.JavaSource.Phase;
36 import org.netbeans.api.java.source.ModificationResult;
37 import org.netbeans.api.java.source.SourceUtilsTestUtil;
38 import org.netbeans.api.java.source.WorkingCopy;
39 import org.netbeans.junit.NbTestCase;
40 import org.openide.filesystems.FileLock;
41 import org.openide.filesystems.FileObject;
42 import org.openide.filesystems.FileUtil;
43 import org.openide.filesystems.LocalFileSystem;
44 import org.openide.filesystems.Repository;
45
46 /**
47  *
48  * @author Jan Lahoda
49  */

50 public class GeneratorUtilsTest extends NbTestCase {
51     
52     public GeneratorUtilsTest(String JavaDoc testName) {
53         super(testName);
54     }
55
56     protected void setUp() throws Exception JavaDoc {
57         SourceUtilsTestUtil.prepareTest(new String JavaDoc[0], new Object JavaDoc[0]);
58     }
59
60     private void writeIntoFile(FileObject file, String JavaDoc what) throws Exception JavaDoc {
61         FileLock lock = file.lock();
62         OutputStream JavaDoc out = file.getOutputStream(lock);
63         
64         try {
65             out.write(what.getBytes());
66         } finally {
67             out.close();
68             lock.releaseLock();
69         }
70     }
71     
72     public void testImplementAllAbstractMethods1() throws Exception JavaDoc {
73         performTest("package test;\npublic class Test implements Runnable {\npublic Test(){\n}\n }\n", 54, new RunnableValidator());
74     }
75     
76 // public void testImplementAllAbstractMethods2() throws Exception {
77
// performTest("package test;\npublic class Test implements Runnable {\n }\n", 54, new RunnableValidator());
78
// }
79
//
80
// public void testImplementAllAbstractMethods3() throws Exception {
81
// performTest("package test;\npublic class Test implements Runnable {\npublic void testMethod() {\n} }\n", 54, new RunnableValidator());
82
// }
83

84     public void testImplementAllAbstractMethods4() throws Exception JavaDoc {
85         performTest("package test;\npublic class Test implements Runnable {\npublic Test(){\n}\npublic void testMethod() {\n} }\n", 54, new RunnableValidator());
86     }
87     
88     public void testImplementAllAbstractMethods5() throws Exception JavaDoc {
89         performTest("package test;import java.util.concurrent.*;\npublic class Test implements Future<String>{\npublic Test(){\n} }\n", 89, new SimpleFutureValidator("java.lang.String"));
90     }
91     
92 // public void testImplementAllAbstractMethods6() throws Exception {
93
// performTest("package test;import java.util.concurrent.*;\npublic class Test implements Future<java.util.List<? extends java.util.List>>{\npublic Test(){\n} }\n", 123, new FutureValidator() {
94
// protected TypeMirror returnType(CompilationInfo info) {
95
// return SourceUtils.parseType(info, "java.util.List<? extends java.util.List>", info.getElements().getTypeElement("test.Test"));
96
// }
97
// });
98
// }
99

100     public void testImplementAllAbstractMethods7() throws Exception JavaDoc {
101         performTest("package test;\npublic class Test extends java.util.AbstractList{\npublic Test(){\n} }\n", 64, new Validator() {
102             public void validate(CompilationInfo info) {
103             }
104         });
105     }
106     
107     /** issue #85966
108      */

109 // public void testImplementAllAbstractMethods8() throws Exception {
110
// performTest("package test;\npublic class Test implements XX {\npublic Test(){\n} }\ninterface XX {\npublic void test(String ... a);}", 42, new Validator() {
111
// public void validate(CompilationInfo info) {
112
// TypeElement clazz = info.getElements().getTypeElement("test.Test");
113
// ExecutableElement method = ElementFilter.methodsIn(clazz.getEnclosedElements()).get(0);
114
//
115
// assertTrue(method.isVarArgs());
116
// }
117
// });
118
// }
119

120     public void testImplementAllAbstractMethods9() throws Exception JavaDoc {
121         performTest("package test;\npublic class Test implements java.util.concurrent.ExecutorService {\npublic Test(){\n} }\n", 30, new Validator() {
122             public void validate(CompilationInfo info) {
123             }
124         });
125     }
126     
127     public void testImplementAllAbstractMethodsa() throws Exception JavaDoc {
128         performTest("package test;\npublic class Test implements XX {\npublic Test(){\n} }\ninterface XX {public <T extends java.util.List> void test(T t);}", 30, new Validator() {
129             public void validate(CompilationInfo info) {
130             }
131         });
132     }
133     
134     public static interface Validator {
135         
136         public void validate(CompilationInfo info);
137         
138     }
139     
140     private final class RunnableValidator implements Validator {
141         
142         public void validate(CompilationInfo info) {
143             TypeElement test = info.getElements().getTypeElement("test.Test");
144             
145             boolean foundRunMethod = false;
146             
147             for (ExecutableElement ee : ElementFilter.methodsIn(test.getEnclosedElements())) {
148                 if ("run".equals(ee.getSimpleName().toString())) {
149                     if (ee.getParameters().isEmpty()) {
150                         assertFalse(foundRunMethod);
151                         foundRunMethod = true;
152                     }
153                 }
154             }
155             
156             assertTrue(foundRunMethod);
157         }
158         
159     }
160     
161     private final class SimpleFutureValidator extends FutureValidator {
162         
163         private String JavaDoc returnTypeName;
164         
165         public SimpleFutureValidator(String JavaDoc returnTypeName) {
166             this.returnTypeName = returnTypeName;
167         }
168         
169         protected TypeMirror returnType(CompilationInfo info) {
170             TypeElement returnTypeElement = info.getElements().getTypeElement(returnTypeName);
171             
172             return returnTypeElement.asType();
173         }
174     }
175     
176     private abstract class FutureValidator implements Validator {
177         
178         protected abstract TypeMirror returnType(CompilationInfo info);
179
180         public void validate(CompilationInfo info) {
181             TypeElement test = info.getElements().getTypeElement("test.Test");
182             TypeMirror returnType = returnType(info);
183             
184             boolean hasShortGet = false;
185             boolean hasLongGet = false;
186             
187             for (ExecutableElement ee : ElementFilter.methodsIn(test.getEnclosedElements())) {
188                 if ("get".equals(ee.getSimpleName().toString())) {
189                     if (ee.getParameters().isEmpty()) {
190                         assertFalse(hasShortGet);
191                         assertTrue(info.getTypes().isSameType(returnType, ee.getReturnType()));
192                         hasShortGet = true;
193                     }
194                     if (ee.getParameters().size() == 2) {
195                         assertFalse(hasLongGet);
196                         assertTrue(info.getTypes().isSameType(returnType, ee.getReturnType()));
197                         hasLongGet = true;
198                     }
199                 }
200             }
201             
202             assertTrue(hasShortGet);
203             assertTrue(hasLongGet);
204         }
205         
206     }
207     
208     private void performTest(String JavaDoc sourceCode, final int offset, final Validator validator) throws Exception JavaDoc {
209         FileObject root = makeScratchDir(this);
210         
211         FileObject sourceDir = root.createFolder("src");
212         FileObject buildDir = root.createFolder("build");
213         FileObject cacheDir = root.createFolder("cache");
214         
215         FileObject source = sourceDir.createFolder("test").createData("Test.java");
216         
217         writeIntoFile(source, sourceCode);
218         
219         SourceUtilsTestUtil.prepareTest(sourceDir, buildDir, cacheDir, new FileObject[0]);
220         
221         JavaSource js = JavaSource.forFileObject(source);
222         
223         ModificationResult result = js.runModificationTask(new CancellableTask<WorkingCopy>() {
224             public void cancel() {
225             }
226             public void run(WorkingCopy copy) throws Exception JavaDoc {
227                 copy.toPhase(Phase.RESOLVED);
228                 TreePath tp = copy.getTreeUtilities().pathFor(offset);
229                 GeneratorUtils.generateAllAbstractMethodImplementations(copy, tp);
230             }
231         });
232         
233         result.commit();
234         
235         js.runUserActionTask(new CancellableTask<CompilationController>() {
236             public void cancel() {
237             }
238             public void run(CompilationController controller) throws Exception JavaDoc {
239                 System.err.println("text:");
240                 System.err.println(controller.getText());
241                 controller.toPhase(Phase.RESOLVED);
242                 
243                 assertEquals(controller.getDiagnostics().toString(), 0, controller.getDiagnostics().size());
244                 
245                 validator.validate(controller);
246             }
247         }, true);
248     }
249     
250     /**Copied from org.netbeans.api.project.
251      * Create a scratch directory for tests.
252      * Will be in /tmp or whatever, and will be empty.
253      * If you just need a java.io.File use clearWorkDir + getWorkDir.
254      */

255     public static FileObject makeScratchDir(NbTestCase test) throws IOException JavaDoc {
256         test.clearWorkDir();
257         File JavaDoc root = test.getWorkDir();
258         assert root.isDirectory() && root.list().length == 0;
259         FileObject fo = FileUtil.toFileObject(root);
260         if (fo != null) {
261             // Presumably using masterfs.
262
return fo;
263         } else {
264             // For the benefit of those not using masterfs.
265
LocalFileSystem lfs = new LocalFileSystem();
266             try {
267                 lfs.setRootDirectory(root);
268             } catch (PropertyVetoException JavaDoc e) {
269                 assert false : e;
270             }
271             Repository.getDefault().addFileSystem(lfs);
272             return lfs.getRoot();
273         }
274     }
275     
276 }
277
Popular Tags