KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > test > java > editor > completion > CompletionTest


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 package org.netbeans.test.java.editor.completion;
20
21 import java.io.*;
22 import java.util.Arrays JavaDoc;
23 import java.util.Collection JavaDoc;
24 import java.util.Collections JavaDoc;
25 import java.util.Comparator JavaDoc;
26 import java.util.Iterator JavaDoc;
27 import java.util.List JavaDoc;
28 import javax.swing.JEditorPane JavaDoc;
29 import javax.swing.SwingUtilities JavaDoc;
30 import javax.swing.text.BadLocationException JavaDoc;
31 import lib.EditorTestCase;
32 import lib.EditorTestCase.ValueResolver;
33 import org.netbeans.api.editor.mimelookup.MimeLookup;
34 import org.netbeans.api.editor.mimelookup.MimePath;
35 import org.openide.filesystems.FileObject;
36 import org.netbeans.editor.*;
37 import org.netbeans.editor.ext.Completion;
38 import org.netbeans.editor.ext.CompletionQuery;
39 import org.netbeans.editor.ext.ExtUtilities;
40 import org.netbeans.junit.ide.ProjectSupport;
41 import org.netbeans.modules.editor.completion.CompletionImpl;
42 import org.netbeans.modules.editor.completion.CompletionResultSetImpl;
43 import org.netbeans.modules.editor.java.JavaCompletionProvider;
44 import org.netbeans.modules.editor.java.LazyTypeCompletionItem;
45 import org.netbeans.spi.editor.completion.CompletionItem;
46 import org.netbeans.spi.editor.completion.CompletionProvider;
47 import org.netbeans.spi.editor.completion.CompletionResultSet;
48 import org.netbeans.spi.editor.completion.CompletionTask;
49 import org.openide.cookies.CloseCookie;
50 import org.openide.cookies.EditorCookie;
51 import org.openide.cookies.SaveCookie;
52 import org.openide.filesystems.FileUtil;
53 import org.openide.loaders.DataObject;
54 import org.openide.util.Lookup;
55
56 /**<FONT COLOR="#CC3333" FACE="Courier New, Monospaced" SIZE="+1">
57  * <B>
58  * Editor module API test: completion/CompletionTest
59  * </B>
60  * </FONT>
61  *
62  * <P>
63  * <B>What it tests:</B><BR>
64  * The purpose of this test is to test Java (and HTML) code completion. This test
65  * is done on some layer between user and API. It uses file and completion
66  * is called on the top of the file, but it is never shown.
67  * </P>
68  *
69  * <P>
70  * <B>How it works:</B><BR>
71  * TestFile is opened, given text is written to it, and code completion is
72  * asked to return response. The type of completion is defined by the type of
73  * the file. Unfortunately, it is not possible to ask completion for response
74  * without opening the file.
75  * </P>
76  *
77  * <P>
78  * <B>Settings:</B><BR>
79  * This test is not complete test, it's only stub, so for concrete test instance
80  * it's necessary to provide text to add and whether the response should be
81  * sorted. No more settings needed, when runned on clean build.
82  * </P>
83  *
84  * <P>
85  * <B>Output:</B><BR>
86  * The output should be completion reponse in human readable form.
87  * </P>
88  *
89  * <P>
90  * <B>Possible reasons of failure:</B><BR>
91  * <UL>
92  * <LI>An exception when obtaining indent engine (for example if it doesn't exist).</LI>
93  * <LI>An exception when writting to indent engine.</LI>
94  * <LI>Possibly unrecognized MIME type.</LI>
95  * <LI>Indent engine error.</LI>
96  * <LI>The file can not be opened. This test must be able to open the file.
97  * The test will fail if it is not able to open the file. In case it starts
98  * opening sequence, but the editor is not opened, it may lock.</LI>
99  * </UL>
100  * </P>
101  *
102  * @author Jan Lahoda
103  * @version 1.0
104  */

105 public class CompletionTest extends java.lang.Object JavaDoc {
106     
107     private static final long OPENING_TIMEOUT = 60 * 1000;
108     private static final long SLEEP_TIME = 1000;
109     
110     /** Creates new CompletionTest */
111     public CompletionTest() {
112     }
113     
114     private class ResultReadyResolver implements ValueResolver {
115         private CompletionResultSetImpl crs;
116         
117         public ResultReadyResolver(CompletionResultSetImpl crs) {
118             this.crs = crs;
119         }
120
121         public Object JavaDoc getValue() {
122             return crs.isFinished();
123         }
124     }
125     
126     private void completionQuery(PrintWriter out,
127             PrintWriter log,
128             JEditorPane JavaDoc editor,
129             boolean unsorted,
130             int queryType
131             ) {
132         BaseDocument doc = Utilities.getDocument(editor);
133         SyntaxSupport support = doc.getSyntaxSupport();
134         
135         CompletionImpl completion = CompletionImpl.get();
136         String JavaDoc mimeType = (String JavaDoc) doc.getProperty("mimeType");
137         Lookup lookup = MimeLookup.getLookup(MimePath.get(mimeType));
138         Collection JavaDoc<? extends CompletionProvider> col = lookup.lookupAll(CompletionProvider.class);
139         JavaCompletionProvider jcp = null;
140         for (Iterator JavaDoc<? extends CompletionProvider> it = col.iterator(); it.hasNext();) {
141             CompletionProvider completionProvider = it.next();
142             if(completionProvider instanceof JavaCompletionProvider) jcp = (JavaCompletionProvider) completionProvider;
143         }
144         if(jcp==null) log.println("JavaCompletionProvider not found");
145         CompletionTask task = jcp.createTask(queryType, editor);
146         CompletionResultSetImpl result = completion.createTestResultSet(task,queryType);
147         task.query(result.getResultSet());
148         EditorTestCase.waitMaxMilisForValue(5000, new ResultReadyResolver(result), Boolean.TRUE);
149         if(!result.isFinished()) log.println("Result is not finished");
150         List JavaDoc<? extends CompletionItem> list = result.getItems();
151         CompletionItem[] array = list.toArray(new CompletionItem[]{});
152         if(!unsorted) {
153             Arrays.sort(array, new Comparator JavaDoc<CompletionItem>(){
154                 public int compare(CompletionItem arg0, CompletionItem arg1) {
155                     String JavaDoc a0 = (arg0 instanceof LazyTypeCompletionItem)? arg0.getSortText().toString():arg0.toString();
156                     String JavaDoc a1 = (arg1 instanceof LazyTypeCompletionItem)? arg1.getSortText().toString():arg1.toString();
157                     return a0.compareTo(a1);
158                 }
159             });
160         }
161         for (int i = 0; i < array.length; i++) {
162             CompletionItem completionItem = array[i];
163             if(completionItem instanceof LazyTypeCompletionItem) out.println(completionItem.getSortText().toString());
164             else out.println(completionItem.toString());
165         }
166         /*Completion completion = ExtUtilities.getCompletion(editor);
167         if (completion != null) {
168             CompletionQuery completionQuery = completion.getQuery();
169             if (completionQuery != null) {
170                 CompletionQuery.Result query = completionQuery.query(editor, editor.getCaret().getDot(), support);
171                 
172                 if (query != null) {
173                     List list = query.getData();
174                     
175                     if (list != null) {
176                         
177                         String[] texts = new String[list.size()];
178                         for (int cntr = 0; cntr < list.size(); cntr++) {
179                             texts[cntr] = list.get(cntr).toString();
180                         };
181                         if (sort)
182                             Arrays.sort(texts);
183                         
184                         for (int cntr = 0; cntr < texts.length; cntr++) {
185                             out.println(texts[cntr].toString());
186                         };
187                     } else {
188                         log.println("CompletionTest: query.getData() == null");
189                         throw new IllegalStateException("CompletionTest: query.getData() == null");
190                     }
191                 } else {
192                     log.println("CompletionTest: completionQuery.query(pane, end, support) == null");
193                     throw new IllegalStateException("CompletionTest: completionQuery.query(pane, end, support) == null");
194                 }
195             } else {
196                 log.println("CompletionTest: completion.getQuery() == null");
197                 throw new IllegalStateException("CompletionTest: completion.getQuery() == null");
198             }
199         } else {
200             log.println("CompletionTest: ExtUtilities.getCompletion(pane) == null");
201             throw new IllegalStateException("CompletionTest: ExtUtilities.getCompletion(pane) == null");
202         }*/

203     }
204     
205     
206     /**Currently, this method is supposed to be runned inside the AWT thread.
207      * If this condition is not fullfilled, an IllegalStateException is
208      * thrown. Do NOT modify this behaviour, or deadlock (or even Swing
209      * or NetBeans winsys data corruption) may occur.
210      *
211      * Currently threading model of this method is compatible with
212      * editor code completion threading model. Revise if this changes
213      * in future.
214      */

215     private void testPerform(PrintWriter out, PrintWriter log,
216             JEditorPane JavaDoc editor,
217             boolean unsorted,
218             String JavaDoc assign,
219             int lineIndex,
220             int queryType) throws BadLocationException JavaDoc, IOException {
221         if (!SwingUtilities.isEventDispatchThread())
222             throw new IllegalStateException JavaDoc("The testPerform method may be called only inside AWT event dispatch thread.");
223         
224         BaseDocument doc = Utilities.getDocument(editor);
225         int lineOffset = Utilities.getRowStartFromLineOffset(doc, lineIndex -1);
226         
227         editor.grabFocus();
228         editor.getCaret().setDot(lineOffset);
229         doc.insertString(lineOffset, assign, null);
230         reparseDocument((DataObject) doc.getProperty(doc.StreamDescriptionProperty));
231         completionQuery(out, log, editor, unsorted, queryType);
232     }
233     
234     public void test(final PrintWriter out, final PrintWriter log,
235             final String JavaDoc assign, final boolean unsorted,
236             final File dataDir, final String JavaDoc projectName,
237             final String JavaDoc testFileName, final int line) throws Exception JavaDoc {
238             test(out, log, assign, unsorted, dataDir, projectName, testFileName, line, CompletionProvider.COMPLETION_QUERY_TYPE);
239     }
240     
241     public void test(final PrintWriter out, final PrintWriter log,
242             final String JavaDoc assign, final boolean unsorted,
243             final File dataDir, final String JavaDoc projectName,
244             final String JavaDoc testFileName, final int line, final int queryType) throws Exception JavaDoc {
245         try {
246             log.println("Completion test start.");
247             log.flush();
248             
249             FileObject testFileObject = getTestFile(dataDir, projectName, testFileName, log);
250             final DataObject testFile = DataObject.find(testFileObject);
251             
252             try {
253                 Runnable JavaDoc test = new Runnable JavaDoc() {
254                     public void run() {
255                         try {
256                             JEditorPane JavaDoc editor = getAnEditorPane(testFile, log);
257                             testPerform(out, log, editor, unsorted, assign, line, queryType);
258                         } catch (Exception JavaDoc e) {
259                             e.printStackTrace(log);
260                         };
261                     }
262                 };
263                 if (SwingUtilities.isEventDispatchThread()) {
264                     test.run();
265                 } else {
266                     SwingUtilities.invokeAndWait(test);
267                 }
268             } finally {
269                 testFile.setModified(false);
270                 //((CloseCookie) testFile.getCookie(CloseCookie.class)).close();
271
}
272         } catch (Exception JavaDoc e) {
273             e.printStackTrace(log);
274             throw e;
275         }
276     }
277     
278     private FileObject getTestFile(File dataDir, String JavaDoc projectName, String JavaDoc testFile, PrintWriter log) throws IOException, InterruptedException JavaDoc {
279         File projectFile = new File(dataDir, projectName);
280         FileObject project = FileUtil.toFileObject(projectFile);
281         Object JavaDoc prj= ProjectSupport.openProject(projectFile);
282         
283         if (prj == null)
284             throw new IllegalStateException JavaDoc("Given directory \"" + project + "\" does not contain a project.");
285         
286         log.println("Project found: " + prj);
287         
288         FileObject test = project.getFileObject("src/" + testFile);
289         
290         if (test == null)
291             throw new IllegalStateException JavaDoc("Given test file does not exist.");
292         
293         return test;
294     }
295     
296     // public static void main(String[] args) throws Exception {
297
// PrintWriter out = new PrintWriter(System.out);
298
// PrintWriter log = new PrintWriter(System.err);
299
// new CompletionTest().test(out, log, "int[] a; a.", false, "org/netbeans/test/editor/completion/data/testfiles/CompletionTestPerformer/TestFile.java", 20);
300
// out.flush();
301
// log.flush();
302
// }
303

304     //Utility methods:
305
// private static void checkEditorCookie(DataObject od) {
306
// EditorCookie ec =(EditorCookie) od.getCookie(EditorCookie.class);
307
//
308
// if (ec == null)
309
// throw new IllegalStateException("Given file (\"" + od.getName() + "\") does not have EditorCookie.");
310
// }
311

312     private static JEditorPane JavaDoc getAnEditorPane(DataObject file, PrintWriter log) throws Exception JavaDoc {
313         EditorCookie cookie = (EditorCookie)file.getCookie(EditorCookie.class);
314         
315         if (cookie == null)
316             throw new IllegalStateException JavaDoc("Given file (\"" + file.getName() + "\") does not have EditorCookie.");
317         
318         JEditorPane JavaDoc[] panes = cookie.getOpenedPanes();
319         long start = System.currentTimeMillis();
320         
321         if (panes == null) {
322             //Prepare by opening a document. The actual opening into the editor
323
//should be faster (hopefully...).
324
cookie.openDocument();
325             cookie.open();
326             while ((panes = cookie.getOpenedPanes()) == null && (System.currentTimeMillis() - start) < OPENING_TIMEOUT) {
327                 try {
328                     Thread.sleep(SLEEP_TIME);
329                 } catch (InterruptedException JavaDoc e) {
330                     e.printStackTrace(log);
331                 }
332             };
333             
334             log.println("Waiting spent: " + (System.currentTimeMillis() - start) + "ms.");
335         };
336         
337         if (panes == null)
338             throw new IllegalStateException JavaDoc("The editor was not opened. The timeout was: " + OPENING_TIMEOUT + "ms.");
339         
340         return panes[0];
341     }
342     
343     // private static boolean isSomePaneOpened(DataObject file) {
344
// EditorCookie cookie = (EditorCookie) file.getCookie(EditorCookie.class);
345
//
346
// if (cookie == null) {
347
// return false;
348
// }
349
//
350
// return cookie.getOpenedPanes() != null;
351
// }
352

353     private static void reparseDocument(DataObject file) throws IOException {
354         saveDocument(file);
355      /* SourceCookie sc = (SourceCookie) file.getCookie(SourceCookie.class);
356       
357         if (sc != null) {
358             SourceElement se = sc.getSource();
359             se.prepare().waitFinished();
360         } else {
361             System.err.println("reparseDocument: SourceCookie cookie not found in testFile!");
362         }*/

363         // XXX waiting to reparse - should be repalaced by smtg more sofisticated
364
try {
365             Thread.sleep(1000);
366         } catch (InterruptedException JavaDoc e) {
367             
368         }
369     }
370     
371     private static void saveDocument(DataObject file) throws IOException { //!!!WARNING: if this exception is thrown, the test may be locked (the file in editor may be modified, but not saved. problems with IDE finishing are supposed in this case).
372
SaveCookie sc = (SaveCookie) file.getCookie(SaveCookie.class);
373         
374         if (sc != null) {
375             sc.save();
376         }
377     }
378     
379 }
380
Popular Tags