KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > modules > java > hints > JavaHintsTestBase


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.hints;
20
21 import java.beans.PropertyVetoException JavaDoc;
22 import java.io.File JavaDoc;
23 import java.io.FileWriter JavaDoc;
24 import java.io.FilenameFilter JavaDoc;
25 import java.io.IOException JavaDoc;
26 import java.io.Writer JavaDoc;
27 import java.net.URL JavaDoc;
28 import java.util.ArrayList JavaDoc;
29 import java.util.List JavaDoc;
30 import javax.swing.text.Document JavaDoc;
31 import org.netbeans.api.editor.mimelookup.MimePath;
32 import org.netbeans.api.java.lexer.JavaTokenId;
33 import org.netbeans.api.java.source.CancellableTask;
34 import org.netbeans.api.java.source.CompilationInfo;
35 import org.netbeans.api.java.source.JavaSource;
36 import org.netbeans.api.java.source.JavaSource.Phase;
37 import org.netbeans.api.java.source.SourceUtilsTestUtil;
38 import org.netbeans.api.java.source.SourceUtilsTestUtil2;
39 import org.netbeans.api.java.source.gen.WhitespaceIgnoringDiff;
40 import org.netbeans.api.lexer.InputAttributes;
41 import org.netbeans.api.lexer.Language;
42 import org.netbeans.api.lexer.LanguagePath;
43 import org.netbeans.api.lexer.Token;
44 import org.netbeans.api.lexer.TokenId;
45 import org.netbeans.api.progress.ProgressHandle;
46 import org.netbeans.api.progress.ProgressHandleFactory;
47 import org.netbeans.junit.NbTestCase;
48 import org.netbeans.modules.editor.java.JavaKit;
49 import org.netbeans.modules.java.JavaDataLoader;
50 import org.netbeans.modules.java.JavaDataObject.JavaEditorSupport;
51 import org.netbeans.spi.editor.hints.ErrorDescription;
52 import org.netbeans.spi.editor.hints.Fix;
53 import org.netbeans.spi.editor.hints.LazyFixList;
54 import org.openide.cookies.EditorCookie;
55 import org.openide.loaders.DataObject;
56 import org.netbeans.modules.java.source.TestUtil;
57 import org.netbeans.modules.java.source.usages.ClassIndexImpl;
58 import org.netbeans.modules.java.source.usages.ClassIndexManager;
59 import org.netbeans.modules.java.source.usages.IndexUtil;
60 import org.netbeans.spi.editor.mimelookup.MimeDataProvider;
61 import org.netbeans.spi.lexer.LanguageEmbedding;
62 import org.netbeans.spi.lexer.LanguageProvider;
63 import org.openide.filesystems.FileObject;
64 import org.openide.filesystems.FileUtil;
65 import org.openide.filesystems.LocalFileSystem;
66 import org.openide.filesystems.Repository;
67 import org.openide.filesystems.URLMapper;
68 import org.openide.util.Lookup;
69 import org.openide.util.lookup.Lookups;
70
71 /**
72  * @author Jan Lahoda
73  */

74 public class JavaHintsTestBase extends NbTestCase {
75     
76     /** Need to be defined because of JUnit */
77     public JavaHintsTestBase(String JavaDoc name) {
78         super(name);
79         
80     }
81     
82     private FileObject packageRoot;
83     private FileObject testSource;
84     private JavaSource js;
85     protected CompilationInfo info;
86     
87     private static File JavaDoc cache;
88     private static FileObject cacheFO;
89     
90     private CancellableTask<CompilationInfo> task;
91     
92     protected void setUp() throws Exception JavaDoc {
93         doSetUp("org/netbeans/modules/java/hints/resources/layer.xml");
94     }
95     
96     protected void doSetUp(String JavaDoc resource) throws Exception JavaDoc {
97         SourceUtilsTestUtil.prepareTest(new String JavaDoc[] {"org/netbeans/modules/java/editor/resources/layer.xml", resource}, new Object JavaDoc[] {
98             JavaDataLoader.class,
99             new MimeDataProvider() {
100                 public Lookup getLookup(MimePath mimePath) {
101                     return Lookups.fixed(new Object JavaDoc[] {
102                         new JavaKit(),
103                     });
104                 }
105             },
106             new LanguageProvider() {
107                 public Language<? extends TokenId> findLanguage(String JavaDoc mimePath) {
108                     return JavaTokenId.language();
109                 }
110                 
111                 public LanguageEmbedding<? extends TokenId> findLanguageEmbedding(Token<? extends TokenId> token,
112                         LanguagePath languagePath,
113                         InputAttributes inputAttributes) {
114                     return null;
115                 }
116             }
117         });
118         
119         if (cache == null) {
120             cache = FileUtil.normalizeFile(TestUtil.createWorkFolder());
121             cacheFO = FileUtil.toFileObject(cache);
122             
123             cache.deleteOnExit();
124             
125             IndexUtil.setCacheFolder(cache);
126             
127             if (createCaches()) {
128                 for (URL JavaDoc u : SourceUtilsTestUtil.getBootClassPath()) {
129                     FileObject file = URLMapper.findFileObject(u);
130                     
131                     if (file == null)
132                         continue;
133                     
134                     file = FileUtil.getArchiveFile(file);
135                     
136                     if (file == null)
137                         continue;
138                     
139                     File JavaDoc jioFile = FileUtil.toFile(file);
140                     
141                     if (jioFile == null)
142                         continue;
143                     
144                     final ClassIndexImpl ci = ClassIndexManager.getDefault().createUsagesQuery(u, false);
145                     ProgressHandle handle = ProgressHandleFactory.createHandle("cache creation");
146                     ci.getBinaryAnalyser().analyse(u, handle);
147                 }
148             }
149         }
150     }
151     
152     protected boolean createCaches() {
153         return true;
154     }
155     
156     protected String JavaDoc testDataExtension() {
157         return "org/netbeans/test/java/hints/";
158     }
159     
160     protected void prepareTest(String JavaDoc capitalizedName) throws Exception JavaDoc {
161         FileObject workFO = makeScratchDir(this);
162         
163         assertNotNull(workFO);
164         
165         FileObject sourceRoot = workFO.createFolder("src");
166         FileObject buildRoot = workFO.createFolder("build");
167 // FileObject cache = workFO.createFolder("cache");
168

169         packageRoot = FileUtil.createFolder(sourceRoot, testDataExtension());
170         
171         SourceUtilsTestUtil.prepareTest(sourceRoot, buildRoot, cacheFO);
172         
173         String JavaDoc testPackagePath = testDataExtension();
174         File JavaDoc testPackageFile = new File JavaDoc(getDataDir(), testPackagePath);
175         
176         String JavaDoc[] names = testPackageFile.list(new FilenameFilter JavaDoc() {
177             public boolean accept(File JavaDoc dir, String JavaDoc name) {
178                 if (name.endsWith(".java"))
179                     return true;
180                 
181                 return false;
182             }
183         });
184         
185         String JavaDoc[] files = new String JavaDoc[names.length];
186         
187         for (int cntr = 0; cntr < files.length; cntr++) {
188             files[cntr] = testPackagePath + names[cntr];
189         }
190         
191         TestUtil.copyFiles(getDataDir(), FileUtil.toFile(sourceRoot), files);
192         
193         packageRoot.refresh();
194         
195         capitalizedName = capitalizedName.substring(capitalizedName.lastIndexOf('.') + 1);
196         
197         testSource = packageRoot.getFileObject(capitalizedName + ".java");
198         
199         assertNotNull(testSource);
200         
201         js = JavaSource.forFileObject(testSource);
202         
203         assertNotNull(js);
204         
205         info = SourceUtilsTestUtil.getCompilationInfo(js, Phase.RESOLVED);
206         
207         assertNotNull(info);
208         
209         task = new LazyHintComputationFactory().createTask(testSource);
210     }
211     
212     /**Copied from org.netbeans.api.project.
213      * Create a scratch directory for tests.
214      * Will be in /tmp or whatever, and will be empty.
215      * If you just need a java.io.File use clearWorkDir + getWorkDir.
216      */

217     public static FileObject makeScratchDir(NbTestCase test) throws IOException JavaDoc {
218         test.clearWorkDir();
219         File JavaDoc root = test.getWorkDir();
220         assert root.isDirectory() && root.list().length == 0;
221         FileObject fo = FileUtil.toFileObject(root);
222         if (fo != null) {
223             // Presumably using masterfs.
224
return fo;
225         } else {
226             // For the benefit of those not using masterfs.
227
LocalFileSystem lfs = new LocalFileSystem();
228             try {
229                 lfs.setRootDirectory(root);
230             } catch (PropertyVetoException JavaDoc e) {
231                 assert false : e;
232             }
233             Repository.getDefault().addFileSystem(lfs);
234             return lfs.getRoot();
235         }
236     }
237     
238 // private int getOffset(Document doc, int linenumber, int column) {
239
// return NbDocument.findLineOffset((StyledDocument) doc, linenumber - 1) + column - 1;
240
// }
241

242     private List JavaDoc<Fix> getFixes(ErrorDescription d) throws Exception JavaDoc {
243         LazyFixList f = d.getFixes();
244         
245         f.getFixes();
246         
247         task.run(info);
248         
249         return f.getFixes();
250     }
251     
252     private int getStartLine(ErrorDescription d) throws IOException JavaDoc {
253         return d.getRange().getBegin().getLine();
254     }
255     
256     protected void performHintsPresentCheck(String JavaDoc className, int line, int column, boolean present) throws Exception JavaDoc {
257         prepareTest(className);
258         DataObject od = DataObject.find(testSource);
259         EditorCookie ec = (EditorCookie) od.getCookie(EditorCookie.class);
260         
261         Document JavaDoc doc = ec.openDocument();
262         
263         List JavaDoc<ErrorDescription> errors = new JavaHintsProvider(testSource).computeErrors(info, doc);
264         List JavaDoc<Fix> fixes = new ArrayList JavaDoc<Fix>();
265         
266         for (ErrorDescription d : errors) {
267             if (getStartLine(d) + 1 == line)
268                 fixes.addAll(getFixes(d));
269         }
270         
271         if (present) {
272             assertTrue(fixes != null && !fixes.isEmpty());
273         } else {
274             assertTrue(fixes == null || fixes.isEmpty());
275         }
276     }
277     
278     protected void performTestDoNotPerform(String JavaDoc className, int line, int column) throws Exception JavaDoc {
279         prepareTest(className);
280         DataObject od = DataObject.find(testSource);
281         EditorCookie ec = (EditorCookie) od.getCookie(EditorCookie.class);
282         
283         Document JavaDoc doc = ec.openDocument();
284         
285         List JavaDoc<ErrorDescription> errors = new JavaHintsProvider(testSource).computeErrors(info, doc);
286         List JavaDoc<Fix> fixes = new ArrayList JavaDoc<Fix>();
287         
288         for (ErrorDescription d : errors) {
289             if (getStartLine(d) + 1 == line)
290                 fixes.addAll(getFixes(d));
291         }
292         
293         File JavaDoc fixesDump = new File JavaDoc(getWorkDir(), getName() + "-hints.out");
294         File JavaDoc diff = new File JavaDoc(getWorkDir(), getName() + "-hints.diff");
295         
296         Writer JavaDoc hintsWriter = new FileWriter JavaDoc(fixesDump);
297         
298         for (Fix f : fixes) {
299             hintsWriter.write(f.getText());
300             hintsWriter.write("\n");
301         }
302         
303         hintsWriter.close();
304         
305         File JavaDoc hintsGolden = getGoldenFile(getName() + "-hints.pass");
306         
307         assertFile(fixesDump, hintsGolden, diff);
308     }
309     
310     protected void performTest(String JavaDoc className, String JavaDoc performHint, int line, int column) throws Exception JavaDoc {
311         performTest(className, className, performHint, line, column, true);
312     }
313     
314     protected void performTest(String JavaDoc className, String JavaDoc modifiedClassName,
315             String JavaDoc performHint, int line, int column, boolean checkHintList) throws Exception JavaDoc {
316         prepareTest(className);
317         DataObject od = DataObject.find(testSource);
318         EditorCookie ec = (EditorCookie) od.getCookie(EditorCookie.class);
319         
320         try {
321             Document JavaDoc doc = ec.openDocument();
322             
323             List JavaDoc<ErrorDescription> errors = new JavaHintsProvider(testSource).computeErrors(info, doc);
324             List JavaDoc<Fix> fixes = new ArrayList JavaDoc<Fix>();
325             
326             for (ErrorDescription d : errors) {
327                 if (getStartLine(d) + 1 == line)
328                     fixes.addAll(getFixes(d));
329             }
330             
331             Fix toPerform = null;
332             
333             if (checkHintList) {
334                 File JavaDoc fixesDump = new File JavaDoc(getWorkDir(), getName() + "-hints.out");
335                 
336                 Writer JavaDoc hintsWriter = new FileWriter JavaDoc(fixesDump);
337                 
338                 for (Fix f : fixes) {
339                     if (f.getText().indexOf(performHint) != (-1)) {
340                         toPerform = f;
341                     }
342                     
343                     hintsWriter.write(f.getText());
344                     hintsWriter.write("\n");
345                 }
346                 
347                 hintsWriter.close();
348                 
349                 File JavaDoc hintsGolden = getGoldenFile(getName() + "-hints.pass");
350                 File JavaDoc diff = new File JavaDoc(getWorkDir(), getName() + "-hints.diff");
351                 
352                 assertFile(fixesDump, hintsGolden, diff);
353             } else {
354                 for (Fix f : fixes) {
355                     if (f.getText().indexOf(performHint) != (-1)) {
356                         toPerform = f;
357                     }
358                 }
359             }
360             
361             assertNotNull(toPerform);
362             
363             toPerform.implement();
364             
365             File JavaDoc dump = new File JavaDoc(getWorkDir(), getName() + ".out");
366             
367             Writer JavaDoc writer = new FileWriter JavaDoc(dump);
368             
369             Document JavaDoc modifDoc;
370             if (className.equals(modifiedClassName)) {
371                 modifDoc = doc;
372             } else {
373                 FileObject modFile = packageRoot.getFileObject(modifiedClassName + ".java");
374                 od = DataObject.find(modFile);
375                 ec = od.getCookie(EditorCookie.class);
376                 modifDoc = ec.openDocument();
377             }
378             
379             writer.write(modifDoc.getText(0, modifDoc.getLength()));
380             
381             writer.close();
382             
383             File JavaDoc golden = getGoldenFile();
384             
385             assertNotNull(golden);
386             
387             File JavaDoc diff = new File JavaDoc(getWorkDir(), getName() + ".diff");
388             
389             assertFile(dump, golden, diff, new WhitespaceIgnoringDiff());
390         } finally {
391             //discard changes in the file:
392
JavaEditorSupport s = (JavaEditorSupport) ec;
393             
394             SourceUtilsTestUtil2.ignoreCompileRequests();
395             
396             s.close(false);
397         }
398     }
399     
400 }
401
Popular Tags