KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > modules > java > editor > completion > CompletionTestBase


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.completion;
21
22 import java.io.File JavaDoc;
23 import java.io.FileInputStream JavaDoc;
24 import java.io.FileOutputStream JavaDoc;
25 import java.io.FileWriter JavaDoc;
26 import java.io.IOException JavaDoc;
27 import java.io.InputStream JavaDoc;
28 import java.io.OutputStream JavaDoc;
29 import java.io.Writer JavaDoc;
30 import java.net.MalformedURLException JavaDoc;
31 import java.net.URL JavaDoc;
32 import java.util.ArrayList JavaDoc;
33 import java.util.Collections JavaDoc;
34 import java.util.List JavaDoc;
35 import java.util.StringTokenizer JavaDoc;
36 import java.util.regex.Pattern JavaDoc;
37 import javax.swing.JEditorPane JavaDoc;
38 import javax.swing.text.Document JavaDoc;
39 import junit.framework.Assert;
40
41 import org.netbeans.api.editor.mimelookup.MimePath;
42 import org.netbeans.api.java.classpath.ClassPath;
43 import org.netbeans.api.java.lexer.JavaTokenId;
44 import org.netbeans.api.java.source.JavaSource;
45 import org.netbeans.api.java.source.SourceUtilsTestUtil2;
46 import org.netbeans.api.java.source.gen.WhitespaceIgnoringDiff;
47 import org.netbeans.api.lexer.Language;
48 import org.netbeans.junit.NbTestCase;
49 import org.netbeans.modules.editor.completion.CompletionItemComparator;
50 import org.netbeans.modules.editor.java.JavaCompletionProvider;
51 import org.netbeans.modules.editor.java.JavaKit;
52 import org.netbeans.modules.editor.java.Utilities;
53 import org.netbeans.modules.java.JavaDataLoader;
54 import org.netbeans.modules.java.JavaDataObject.JavaEditorSupport;
55 import org.netbeans.modules.java.source.usages.ClassIndexImpl;
56 import org.netbeans.modules.java.source.usages.ClassIndexManager;
57 import org.netbeans.modules.java.source.usages.IndexUtil;
58 import org.netbeans.spi.editor.completion.CompletionItem;
59 import org.netbeans.spi.editor.completion.CompletionProvider;
60 import org.netbeans.spi.editor.mimelookup.MimeDataProvider;
61 import org.netbeans.spi.java.classpath.ClassPathProvider;
62 import org.netbeans.spi.java.classpath.support.ClassPathSupport;
63
64 import org.openide.cookies.EditorCookie;
65 import org.openide.filesystems.FileObject;
66 import org.openide.filesystems.FileUtil;
67 import org.openide.filesystems.FileUtil;
68 import org.openide.filesystems.Repository;
69 import org.openide.filesystems.XMLFileSystem;
70 import org.openide.loaders.DataObject;
71 import org.openide.util.Lookup;
72 import org.openide.util.SharedClassObject;
73 import org.openide.util.lookup.Lookups;
74 import org.openide.util.lookup.ProxyLookup;
75
76 /**
77  *
78  * @author Dusan Balek, Jan Lahoda
79  */

80 public class CompletionTestBase extends NbTestCase {
81     
82     static {
83         JavaCompletionProviderBasicTest.class.getClassLoader().setDefaultAssertionStatus(true);
84         System.setProperty("org.openide.util.Lookup", Lkp.class.getName());
85         Assert.assertEquals(Lkp.class, Lookup.getDefault().getClass());
86     }
87
88     static final int FINISH_OUTTIME = 5 * 60 * 1000;
89     
90     public static class Lkp extends ProxyLookup {
91         
92         private static Lkp DEFAULT;
93         
94         public Lkp() {
95             Assert.assertNull(DEFAULT);
96             DEFAULT = this;
97         }
98         
99         public static void initLookups(Object JavaDoc[] objs) throws Exception JavaDoc {
100             ClassLoader JavaDoc l = Lkp.class.getClassLoader();
101             DEFAULT.setLookups(new Lookup [] {
102                 Lookups.fixed(objs),
103                 Lookups.metaInfServices(l),
104                 Lookups.singleton(l)
105             });
106         }
107     }
108     
109     public CompletionTestBase(String JavaDoc testName) {
110         super(testName);
111     }
112     
113     protected void setUp() throws Exception JavaDoc {
114         XMLFileSystem system = new XMLFileSystem();
115         system.setXmlUrls(new URL JavaDoc[] {
116             JavaCompletionProviderBasicTest.class.getResource("/org/netbeans/modules/java/editor/resources/layer.xml"),
117             JavaCompletionProviderBasicTest.class.getResource("/org/netbeans/modules/defaults/mf-layer.xml")
118         });
119         Repository repository = new Repository(system);
120         File JavaDoc cacheFolder = new File JavaDoc(getWorkDir(), "var/cache/index");
121         cacheFolder.mkdirs();
122         IndexUtil.setCacheFolder(cacheFolder);
123         final ClassPath sourcePath = ClassPathSupport.createClassPath(new FileObject[] {FileUtil.toFileObject(getDataDir())});
124         final ClassIndexManager mgr = ClassIndexManager.getDefault();
125         for (ClassPath.Entry entry : sourcePath.entries()) {
126             mgr.createUsagesQuery(entry.getURL(), true);
127         }
128         final ClassPath bootPath = createClassPath(System.getProperty("sun.boot.class.path"));
129         for (ClassPath.Entry entry : bootPath.entries()) {
130             URL JavaDoc url = entry.getURL();
131             ClassIndexImpl cii = mgr.createUsagesQuery(url, false);
132             cii.getBinaryAnalyser().analyse(url, null);
133             
134         }
135         ClassPathProvider cpp = new ClassPathProvider() {
136             public ClassPath findClassPath(FileObject file, String JavaDoc type) {
137                 if (type == ClassPath.SOURCE)
138                     return sourcePath;
139                     if (type == ClassPath.COMPILE)
140                         return ClassPathSupport.createClassPath(new FileObject[0]);
141                     if (type == ClassPath.BOOT)
142                         return bootPath;
143                     return null;
144             }
145         };
146         SharedClassObject loader = JavaDataLoader.findObject(JavaDataLoader.class, true);
147         MimeDataProvider mdp = new MimeDataProvider() {
148             public Lookup getLookup(MimePath mimePath) {
149                 return Lookups.singleton(new JavaKit());
150             }
151         };
152         Lkp.initLookups(new Object JavaDoc[] {repository, loader, cpp, mdp});
153         JEditorPane.registerEditorKitForContentType("text/x-java", "org.netbeans.modules.editor.java.JavaKit");
154         Utilities.setCaseSensitive(true);
155     }
156     
157     protected void tearDown() throws Exception JavaDoc {
158     }
159     
160     protected void performTest(String JavaDoc source, int caretPos, String JavaDoc textToInsert, String JavaDoc goldenFileName) throws Exception JavaDoc {
161         performTest(source, caretPos, textToInsert, goldenFileName, null, null);
162     }
163     
164     protected void performTest(String JavaDoc source, int caretPos, String JavaDoc textToInsert, String JavaDoc goldenFileName, String JavaDoc toPerformItemRE, String JavaDoc goldenFileName2) throws Exception JavaDoc {
165         File JavaDoc testSource = new File JavaDoc(getWorkDir(), "test/Test.java");
166         testSource.getParentFile().mkdirs();
167         copyToWorkDir(new File JavaDoc(getDataDir(), "org/netbeans/modules/java/editor/completion/data/" + source + ".java"), testSource);
168         FileObject testSourceFO = FileUtil.toFileObject(testSource);
169         assertNotNull(testSourceFO);
170         DataObject testSourceDO = DataObject.find(testSourceFO);
171         assertNotNull(testSourceDO);
172         EditorCookie ec = (EditorCookie) testSourceDO.getCookie(EditorCookie.class);
173         assertNotNull(ec);
174         final Document JavaDoc doc = ec.openDocument();
175         assertNotNull(doc);
176         doc.putProperty(Language.class, JavaTokenId.language());
177         int textToInsertLength = textToInsert != null ? textToInsert.length() : 0;
178         if (textToInsertLength > 0)
179             doc.insertString(caretPos, textToInsert, null);
180         JavaSource js = JavaSource.forDocument(doc);
181         List JavaDoc<? extends CompletionItem> items = JavaCompletionProvider.query(js, CompletionProvider.COMPLETION_QUERY_TYPE, caretPos + textToInsertLength, caretPos + textToInsertLength);
182         Collections.sort(items, CompletionItemComparator.BY_PRIORITY);
183         
184         File JavaDoc output = new File JavaDoc(getWorkDir(), getName() + ".out");
185         Writer JavaDoc out = new FileWriter JavaDoc(output);
186         for (Object JavaDoc item : items) {
187             out.write(item.toString());
188             out.write("\n");
189         }
190         out.close();
191         
192         File JavaDoc goldenFile = new File JavaDoc(getDataDir(), "/goldenfiles/org/netbeans/modules/java/editor/completion/JavaCompletionProviderTest/" + goldenFileName);
193         File JavaDoc diffFile = new File JavaDoc(getWorkDir(), getName() + ".diff");
194         assertFile(output, goldenFile, diffFile);
195         
196         if (toPerformItemRE != null) {
197             assertNotNull(goldenFileName2);
198
199             Pattern JavaDoc p = Pattern.compile(toPerformItemRE);
200             CompletionItem item = null;
201             for (CompletionItem i : items) {
202                 if (p.matcher(i.toString()).find()) {
203                     item = i;
204                     break;
205                 }
206             }
207             assertNotNull(item);
208             
209             JEditorPane JavaDoc editor = new JEditorPane JavaDoc();
210             editor.setDocument(doc);
211             editor.setCaretPosition(caretPos + textToInsertLength);
212             item.defaultAction(editor);
213             
214             File JavaDoc output2 = new File JavaDoc(getWorkDir(), getName() + ".out2");
215             Writer JavaDoc out2 = new FileWriter JavaDoc(output2);
216             out2.write(doc.getText(0, doc.getLength()));
217             out2.close();
218             
219             File JavaDoc goldenFile2 = new File JavaDoc(getDataDir(), "/goldenfiles/org/netbeans/modules/java/editor/completion/JavaCompletionProviderTest/" + goldenFileName2);
220             File JavaDoc diffFile2 = new File JavaDoc(getWorkDir(), getName() + ".diff2");
221             
222             assertFile(output2, goldenFile2, diffFile2, new WhitespaceIgnoringDiff());
223         }
224         
225         JavaEditorSupport s = (JavaEditorSupport) ec;
226         SourceUtilsTestUtil2.ignoreCompileRequests();
227         s.close(false);
228     }
229
230     private void copyToWorkDir(File JavaDoc resource, File JavaDoc toFile) throws IOException JavaDoc {
231         InputStream JavaDoc is = new FileInputStream JavaDoc(resource);
232         OutputStream JavaDoc outs = new FileOutputStream JavaDoc(toFile);
233         int read;
234         while ((read = is.read()) != (-1)) {
235             outs.write(read);
236         }
237         outs.close();
238         is.close();
239     }
240     
241     private static ClassPath createClassPath(String JavaDoc classpath) {
242         StringTokenizer JavaDoc tokenizer = new StringTokenizer JavaDoc(classpath, File.pathSeparator);
243         List JavaDoc/*<PathResourceImplementation>*/ list = new ArrayList JavaDoc();
244         while (tokenizer.hasMoreTokens()) {
245             String JavaDoc item = tokenizer.nextToken();
246             File JavaDoc f = FileUtil.normalizeFile(new File JavaDoc(item));
247             URL JavaDoc url = getRootURL(f);
248             if (url!=null) {
249                 list.add(ClassPathSupport.createResource(url));
250             }
251         }
252         return ClassPathSupport.createClassPath(list);
253     }
254     
255     // XXX this method could probably be removed... use standard FileUtil stuff
256
private static URL JavaDoc getRootURL (File JavaDoc f) {
257         URL JavaDoc url = null;
258         try {
259             if (isArchiveFile(f)) {
260                 url = FileUtil.getArchiveRoot(f.toURI().toURL());
261             } else {
262                 url = f.toURI().toURL();
263                 String JavaDoc surl = url.toExternalForm();
264                 if (!surl.endsWith("/")) {
265                     url = new URL JavaDoc(surl+"/");
266                 }
267             }
268         } catch (MalformedURLException JavaDoc e) {
269             throw new AssertionError JavaDoc(e);
270         }
271         return url;
272     }
273     
274     private static boolean isArchiveFile(File JavaDoc f) {
275         // the f might not exist and so you cannot use e.g. f.isFile() here
276
String JavaDoc fileName = f.getName().toLowerCase();
277         return fileName.endsWith(".jar") || fileName.endsWith(".zip"); //NOI18N
278
}
279 }
280
Popular Tags