KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > api > java > source > JavaSourceTest


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.api.java.source;
21
22 import com.sun.source.tree.ClassTree;
23 import com.sun.source.tree.CompilationUnitTree;
24 import com.sun.source.tree.IdentifierTree;
25 import com.sun.source.util.TreePathScanner;
26 import com.sun.source.util.TreeScanner;
27 import java.io.File JavaDoc;
28 import java.io.FileWriter JavaDoc;
29 import java.io.PrintWriter JavaDoc;
30 import java.lang.ref.Reference JavaDoc;
31 import java.lang.ref.WeakReference JavaDoc;
32 import java.lang.reflect.Field JavaDoc;
33 import java.net.MalformedURLException JavaDoc;
34 import java.net.URI JavaDoc;
35 import java.net.URL JavaDoc;
36 import java.text.MessageFormat JavaDoc;
37 import java.util.concurrent.CountDownLatch JavaDoc;
38 import java.util.concurrent.atomic.AtomicBoolean JavaDoc;
39 import java.util.concurrent.atomic.AtomicInteger JavaDoc;
40 import javax.lang.model.element.Modifier;
41 import javax.swing.text.StyledDocument JavaDoc;
42 import javax.tools.JavaFileObject;
43 import junit.framework.*;
44 import java.io.IOException JavaDoc;
45 import java.io.OutputStreamWriter JavaDoc;
46 import java.io.Writer JavaDoc;
47 import java.util.ArrayList JavaDoc;
48 import java.util.Arrays JavaDoc;
49 import java.util.Collections JavaDoc;
50 import java.util.List JavaDoc;
51 import java.util.concurrent.TimeUnit JavaDoc;
52 import javax.swing.text.BadLocationException JavaDoc;
53 import org.netbeans.api.java.classpath.ClassPath;
54 import org.netbeans.junit.NbTestCase;
55 import org.netbeans.junit.NbTestSuite;
56 import org.netbeans.modules.java.source.parsing.SourceFileObject;
57 import org.netbeans.spi.java.classpath.support.ClassPathSupport;
58 import org.openide.cookies.EditorCookie;
59 import org.openide.cookies.SaveCookie;
60 import org.openide.filesystems.FileObject;
61 import org.openide.filesystems.FileUtil;
62 import org.openide.loaders.DataObject;
63 import org.openide.text.NbDocument;
64 import org.openide.util.Lookup;
65 import org.openide.util.lookup.Lookups;
66 import org.openide.util.lookup.ProxyLookup;
67 import org.netbeans.api.java.source.JavaSource.Phase;
68 import org.netbeans.api.java.source.JavaSource.Priority;
69 import org.netbeans.modules.java.preprocessorbridge.spi.JavaFileFilterImplementation;
70 import org.netbeans.modules.java.source.classpath.CacheClassPath;
71 import org.netbeans.modules.java.source.usages.IndexUtil;
72 import org.netbeans.modules.java.source.usages.RepositoryUpdater;
73 import org.netbeans.spi.java.classpath.ClassPathProvider;
74 /**
75  *
76  * @author Tomas Zezula
77  */

78 public class JavaSourceTest extends NbTestCase {
79     
80     static {
81         JavaSourceTest.class.getClassLoader().setDefaultAssertionStatus(true);
82         System.setProperty("org.openide.util.Lookup", JavaSourceTest.Lkp.class.getName());
83         Assert.assertEquals(JavaSourceTest.Lkp.class, Lookup.getDefault().getClass());
84     }
85     
86     public static class Lkp extends ProxyLookup {
87         
88         private static Lkp DEFAULT;
89         
90         public Lkp () {
91             Assert.assertNull(DEFAULT);
92             DEFAULT = this;
93             ClassLoader JavaDoc l = Lkp.class.getClassLoader();
94             this.setLookups(
95                  new Lookup [] {
96                     Lookups.metaInfServices(l),
97                     Lookups.singleton(l),
98             });
99         }
100         
101         public void setLookupsWrapper(Lookup... l) {
102             setLookups(l);
103         }
104         
105     }
106         
107     private static final String JavaDoc REPLACE_PATTERN = "/*TODO:Changed-by-test*/";
108     private static final String JavaDoc TEST_FILE_CONTENT=
109                 "public class {0} '{\n"+
110                 " public static void main (String[] args) {\n"+
111                 " javax.swing.JTable table = new javax.swing.JTable ();\n"+
112                 " Class c = table.getModel().getClass();\n"+
113                 " "+REPLACE_PATTERN+"\n"+
114                 " }\n"+
115                 "}'\n";
116
117     
118     
119     public JavaSourceTest(String JavaDoc testName) {
120         super(testName);
121     }
122
123     protected void setUp() throws Exception JavaDoc {
124     
125     }
126
127     protected void tearDown() throws Exception JavaDoc {
128     }
129
130     public static Test suite() {
131         TestSuite suite = new NbTestSuite(JavaSourceTest.class);
132         return suite;
133     }
134     
135     
136     public void testPhaseCompletionTask () throws MalformedURLException JavaDoc, InterruptedException JavaDoc, IOException JavaDoc {
137         FileObject test = createTestFile ("Test1");
138         ClassPath bootPath = createBootPath ();
139         ClassPath compilePath = createCompilePath ();
140         JavaSource js = JavaSource.create(ClasspathInfo.create(bootPath, compilePath, null), test);
141         CountDownLatch JavaDoc[] latches1 = new CountDownLatch JavaDoc[] {
142             new CountDownLatch JavaDoc (1),
143             new CountDownLatch JavaDoc (1)
144         };
145         CountDownLatch JavaDoc[] latches2 = new CountDownLatch JavaDoc[] {
146             new CountDownLatch JavaDoc (1),
147             new CountDownLatch JavaDoc (1)
148         };
149         AtomicInteger JavaDoc counter = new AtomicInteger JavaDoc (0);
150         CancellableTask<CompilationInfo> task1 = new DiagnosticTask(latches1, counter, Phase.RESOLVED);
151         CancellableTask<CompilationInfo> task2 = new DiagnosticTask(latches2, counter, Phase.PARSED);
152         js.addPhaseCompletionTask (task1,Phase.RESOLVED,Priority.HIGH);
153         js.addPhaseCompletionTask(task2,Phase.PARSED,Priority.LOW);
154         assertTrue ("Time out",waitForMultipleObjects(new CountDownLatch JavaDoc[] {latches1[0], latches2[0]}, 15000));
155         assertEquals ("Called more times than expected",2,counter.getAndSet(0));
156         
157         DataObject dobj = DataObject.find(test);
158         EditorCookie ec = (EditorCookie) dobj.getCookie(EditorCookie.class);
159         final StyledDocument JavaDoc doc = ec.openDocument();
160         Thread.sleep(500); //Making test a more deterministic, when the task is cancelled by DocListener, it's hard for test to recover from it
161
NbDocument.runAtomic (doc,
162             new Runnable JavaDoc () {
163                 public void run () {
164                     try {
165                         String JavaDoc text = doc.getText(0,doc.getLength());
166                         int index = text.indexOf(REPLACE_PATTERN);
167                         assertTrue (index != -1);
168                         doc.remove(index,REPLACE_PATTERN.length());
169                         doc.insertString(index,"System.out.println();",null);
170                     } catch (BadLocationException JavaDoc ble) {
171                         ble.printStackTrace(System.out);
172                     }
173                 }
174         });
175         assertTrue ("Time out",waitForMultipleObjects(new CountDownLatch JavaDoc[] {latches1[1], latches2[1]}, 15000));
176         assertEquals ("Called more times than expected",2,counter.getAndSet(0));
177         js.removePhaseCompletionTask (task1);
178         js.removePhaseCompletionTask (task2);
179     }
180     
181     public void testCompileControlJob () throws MalformedURLException JavaDoc, IOException JavaDoc, InterruptedException JavaDoc {
182         FileObject test = createTestFile ("Test1");
183         ClassPath bootPath = createBootPath ();
184         ClassPath compilePath = createCompilePath ();
185         JavaSource js = JavaSource.create(ClasspathInfo.create(bootPath, compilePath, null), test);
186         CountDownLatch JavaDoc latch = new CountDownLatch JavaDoc (1);
187         js.runUserActionTask(new CompileControlJob(latch),true);
188         assertTrue ("Time out",latch.await(15,TimeUnit.SECONDS));
189     }
190     
191     public void testModificationJob () throws Exception JavaDoc {
192         final FileObject testFile1 = createTestFile("Test1");
193         final FileObject testFile2 = createTestFile("Test2");
194         final ClassPath bootPath = createBootPath();
195         final ClassPath compilePath = createCompilePath();
196         final JavaSource js = JavaSource.create(ClasspathInfo.create(bootPath, compilePath, null), testFile1, testFile2);
197         CountDownLatch JavaDoc latch = new CountDownLatch JavaDoc (2);
198         js.runModificationTask(new WorkingCopyJob (latch)).commit();
199         assertTrue ("Time out",latch.await(15,TimeUnit.SECONDS));
200     }
201
202     public void testInterference () throws MalformedURLException JavaDoc, IOException JavaDoc, InterruptedException JavaDoc {
203         FileObject testFile1 = createTestFile ("Test1");
204         FileObject testFile2 = createTestFile ("Test2");
205         ClassPath bootPath = createBootPath ();
206         ClassPath compilePath = createCompilePath ();
207         JavaSource js1 = JavaSource.create(ClasspathInfo.create(bootPath, compilePath, null), testFile1);
208         JavaSource js2 = JavaSource.create(ClasspathInfo.create(bootPath, compilePath, null), testFile2);
209         CountDownLatch JavaDoc[] latches1 = new CountDownLatch JavaDoc[] {
210             new CountDownLatch JavaDoc (1),
211             new CountDownLatch JavaDoc (1),
212         };
213         CountDownLatch JavaDoc[] latches2 = new CountDownLatch JavaDoc[] {
214             new CountDownLatch JavaDoc (1),
215         };
216         CountDownLatch JavaDoc latch3 = new CountDownLatch JavaDoc (1);
217         AtomicInteger JavaDoc counter = new AtomicInteger JavaDoc (0);
218         
219         DiagnosticTask task1 = new DiagnosticTask(latches1, counter, Phase.RESOLVED);
220         CancellableTask<CompilationInfo> task2 = new DiagnosticTask(latches2, counter, Phase.RESOLVED);
221         
222         js1.addPhaseCompletionTask(task1,Phase.RESOLVED,Priority.HIGH);
223         Thread.sleep(500); //Making test a more deterministic, when the task is cancelled by DocListener, it's hard for test to recover from it
224
js2.runUserActionTask(new CompileControlJob(latch3),true);
225         js2.addPhaseCompletionTask(task2,Phase.RESOLVED,Priority.MAX);
226         boolean result = waitForMultipleObjects (new CountDownLatch JavaDoc[] {latches1[0], latches2[0], latch3}, 15000);
227         if (!result) {
228             assertTrue (String.format("Time out, latches1[0]: %d latches2[0]: %d latches3: %d",latches1[0].getCount(), latches2[0].getCount(), latch3.getCount()), false);
229         }
230         assertEquals ("Called more times than expected",2,counter.getAndSet(0));
231         
232         DataObject dobj = DataObject.find(testFile1);
233         EditorCookie ec = (EditorCookie) dobj.getCookie(EditorCookie.class);
234         final StyledDocument JavaDoc doc = ec.openDocument();
235         Thread.sleep(500); //Making test a more deterministic, when the task is cancelled by DocListener, it's hard for test to recover from it
236
NbDocument.runAtomic (doc,
237             new Runnable JavaDoc () {
238                 public void run () {
239                     try {
240                         String JavaDoc text = doc.getText(0,doc.getLength());
241                         int index = text.indexOf(REPLACE_PATTERN);
242                         assertTrue (index != -1);
243                         doc.remove(index,REPLACE_PATTERN.length());
244                         doc.insertString(index,"System.out.println();",null);
245                     } catch (BadLocationException JavaDoc ble) {
246                         ble.printStackTrace(System.out);
247                     }
248                 }
249         });
250         assertTrue ("Time out",waitForMultipleObjects(new CountDownLatch JavaDoc[] {latches1[1]}, 15000));
251         assertEquals ("Called more times than expected",1,counter.getAndSet(0));
252         js1.removePhaseCompletionTask(task1);
253         js2.removePhaseCompletionTask(task2);
254     }
255     
256     public void testDocumentChanges () throws Exception JavaDoc {
257         FileObject testFile1 = createTestFile ("Test1");
258         ClassPath bootPath = createBootPath ();
259         ClassPath compilePath = createCompilePath ();
260         JavaSource js1 = JavaSource.create(ClasspathInfo.create(bootPath, compilePath, null), testFile1);
261
262         final CountDownLatch JavaDoc start = new CountDownLatch JavaDoc (1);
263         final CountDownLatch JavaDoc stop = new CountDownLatch JavaDoc (1);
264         final AtomicBoolean JavaDoc last = new AtomicBoolean JavaDoc (false);
265         final AtomicInteger JavaDoc counter = new AtomicInteger JavaDoc (0);
266         
267         CancellableTask<CompilationInfo> task = new CancellableTask<CompilationInfo>() {
268             
269             private int state = 0;
270
271             public void cancel() {
272             }
273
274             public void run(CompilationInfo ci) throws Exception JavaDoc {
275                 switch (state) {
276                     case 0:
277                         state = 1;
278                         start.countDown();
279                         break;
280                     case 1:
281                         counter.incrementAndGet();
282                         if (last.get()) {
283                             stop.countDown();
284                         }
285                         break;
286                 }
287             }
288         };
289         js1.addPhaseCompletionTask(task,Phase.PARSED,Priority.HIGH);
290         start.await();
291         Thread.sleep(500);
292         final DataObject dobj = DataObject.find(testFile1);
293         final EditorCookie ec = (EditorCookie) dobj.getCookie(EditorCookie.class);
294         final StyledDocument JavaDoc doc = ec.openDocument();
295         for (int i=0; i<10; i++) {
296             if (i == 9) {
297                 last.set(true);
298             }
299             NbDocument.runAtomic (doc,
300                 new Runnable JavaDoc () {
301                     public void run () {
302                         try {
303                             doc.insertString(0," ",null);
304                         } catch (BadLocationException JavaDoc ble) {
305                             ble.printStackTrace(System.out);
306                         }
307                     }
308             });
309             Thread.sleep(100);
310         }
311         assertTrue ("Time out",stop.await(15000, TimeUnit.MILLISECONDS));
312         assertEquals("Called more time than expected",1,counter.get());
313         js1.removePhaseCompletionTask(task);
314     }
315     
316     
317 // public void testDataFlow () throws MalformedURLException, IOException, InterruptedException {
318
// FileObject testFile = createTestFile ("Test");
319
// ClassPath bootPath = createBootPath ();
320
// ClassPath compilePath = createCompilePath ();
321
// JavaSource js = new JavaSource (testFile, bootPath, compilePath);
322
// CountDownLatch latch = new CountDownLatch (1);
323
// CancellableTask<CompilationInfo> task = new DiagnosticTask(new CountDownLatch[] {latch}, null, Phase.DATA_FLOW_CHECKED);
324
// js.addPhaseCompletionTask(task,Phase.DATA_FLOW_CHECKED, 10);
325
// latch.await(15000,TimeUnit.MILLISECONDS);
326
// js.removePhaseCompletionTask(task);
327
// }
328

329     public void testParsingDelay() throws MalformedURLException JavaDoc, InterruptedException JavaDoc, IOException JavaDoc, BadLocationException JavaDoc {
330         FileObject test = createTestFile ("Test1");
331         ClassPath bootPath = createBootPath ();
332         ClassPath compilePath = createCompilePath ();
333         JavaSource js = JavaSource.create(ClasspathInfo.create(bootPath, compilePath, null), test);
334         CountDownLatch JavaDoc[] latches = new CountDownLatch JavaDoc[] {
335             new CountDownLatch JavaDoc (1),
336             new CountDownLatch JavaDoc (1)
337         };
338         long[] timers = new long[2];
339         AtomicInteger JavaDoc counter = new AtomicInteger JavaDoc (0);
340         CancellableTask<CompilationInfo> task = new DiagnosticTask(latches, timers, counter, Phase.PARSED);
341         js.addPhaseCompletionTask (task,Phase.PARSED, Priority.HIGH);
342         assertTrue ("Time out",waitForMultipleObjects(new CountDownLatch JavaDoc[] {latches[0]}, 15000));
343         assertEquals ("Called more times than expected",1,counter.getAndSet(0));
344         Thread.sleep(1000); //It may happen that the js is invalidated before the dispatch of task is done and the test of timers may fail
345
DataObject dobj = DataObject.find(test);
346         EditorCookie ec = (EditorCookie) dobj.getCookie(EditorCookie.class);
347         final StyledDocument JavaDoc doc = ec.openDocument();
348         long start = System.currentTimeMillis();
349         Thread.sleep(500); //Making test a more deterministic, when the task is cancelled by DocListener, it's hard for test to recover from it
350
NbDocument.runAtomic (doc,
351             new Runnable JavaDoc () {
352                 public void run () {
353                     try {
354                         String JavaDoc text = doc.getText(0,doc.getLength());
355                         int index = text.indexOf(REPLACE_PATTERN);
356                         assertTrue (index != -1);
357                         doc.remove(index,REPLACE_PATTERN.length());
358                         doc.insertString(index,"System.out.println();",null);
359                     } catch (BadLocationException JavaDoc ble) {
360                         ble.printStackTrace(System.out);
361                     }
362                 }
363         });
364         
365         assertTrue ("Time out",waitForMultipleObjects(new CountDownLatch JavaDoc[] {latches[1]}, 15000));
366         assertEquals ("Called more times than expected",1,counter.getAndSet(0));
367         assertTrue("Took less time than expected time=" + (timers[1] - start), (timers[1] - start) >= JavaSource.REPARSE_DELAY);
368         js.removePhaseCompletionTask (task);
369     }
370     
371     public void testJavaSourceIsReclaimable() throws MalformedURLException JavaDoc, InterruptedException JavaDoc, IOException JavaDoc, BadLocationException JavaDoc {
372         FileObject test = createTestFile ("Test1");
373         ClassPath bootPath = createBootPath ();
374         ClassPath compilePath = createCompilePath ();
375         JavaSource js = JavaSource.create(ClasspathInfo.create(bootPath, compilePath, null), test);
376         CountDownLatch JavaDoc[] latches = new CountDownLatch JavaDoc[] {
377             new CountDownLatch JavaDoc (1),
378             new CountDownLatch JavaDoc (1)
379         };
380         AtomicInteger JavaDoc counter = new AtomicInteger JavaDoc (0);
381         CancellableTask<CompilationInfo> task = new DiagnosticTask(latches, counter, Phase.PARSED);
382         js.addPhaseCompletionTask (task,Phase.PARSED,Priority.HIGH);
383         assertTrue ("Time out",waitForMultipleObjects(new CountDownLatch JavaDoc[] {latches[0]}, 15000));
384         
385         DataObject dobj = DataObject.find(test);
386         EditorCookie ec = (EditorCookie) dobj.getCookie(EditorCookie.class);
387         final StyledDocument JavaDoc[] doc = new StyledDocument JavaDoc[] {ec.openDocument()};
388         Thread.sleep(500); //Making test a more deterministic, when the task is cancelled by DocListener, it's hard for test to recover from it
389
NbDocument.runAtomic (doc[0],
390             new Runnable JavaDoc () {
391                 public void run () {
392                     try {
393                         String JavaDoc text = doc[0].getText(0,doc[0].getLength());
394                         int index = text.indexOf(REPLACE_PATTERN);
395                         assertTrue (index != -1);
396                         doc[0].remove(index,REPLACE_PATTERN.length());
397                         doc[0].insertString(index,"System.out.println();",null);
398                     } catch (BadLocationException JavaDoc ble) {
399                         ble.printStackTrace(System.out);
400                     }
401                 }
402         });
403         
404         assertTrue ("Time out",waitForMultipleObjects(new CountDownLatch JavaDoc[] {latches[1]}, 15000));
405         js.removePhaseCompletionTask (task);
406         
407         Reference JavaDoc jsWeak = new WeakReference JavaDoc(js);
408         Reference JavaDoc testWeak = new WeakReference JavaDoc(test);
409         
410         SaveCookie sc = (SaveCookie) dobj.getCookie(SaveCookie.class);
411         
412         sc.save();
413         
414         sc = null;
415         
416         js = null;
417         test = null;
418         dobj = null;
419         ec = null;
420         doc[0] = null;
421         
422         //give the worker thread chance to remove the task:
423
//if the tests starts to fail randomly, try to increment the timeout
424
Thread.sleep(1000);
425         
426         assertGC("JavaSource is reclaimable", jsWeak);
427         //the file objects is held by the timers component
428
//and maybe others:
429
assertGC("FileObject is reclaimable", testWeak);
430     }
431     
432     public void testChangeInvalidates() throws MalformedURLException JavaDoc, InterruptedException JavaDoc, IOException JavaDoc, BadLocationException JavaDoc {
433         int originalReparseDelay = JavaSource.REPARSE_DELAY;
434         try {
435             JavaSource.REPARSE_DELAY = Integer.MAX_VALUE; //never automatically reparse
436

437             FileObject test = createTestFile ("Test1");
438             ClassPath bootPath = createBootPath ();
439             ClassPath compilePath = createCompilePath ();
440             JavaSource js = JavaSource.create(ClasspathInfo.create(bootPath, compilePath, null), test);
441             CountDownLatch JavaDoc latch1 = new CountDownLatch JavaDoc (1);
442             final CountDownLatch JavaDoc latch2 = new CountDownLatch JavaDoc (1);
443             AtomicInteger JavaDoc counter = new AtomicInteger JavaDoc (0);
444             CancellableTask<CompilationInfo> task = new DiagnosticTask(new CountDownLatch JavaDoc[] {latch1}, counter, Phase.PARSED);
445             js.addPhaseCompletionTask (task,Phase.PARSED,Priority.HIGH);
446             assertTrue ("Time out",waitForMultipleObjects(new CountDownLatch JavaDoc[] {latch1}, 15000));
447
448             DataObject dobj = DataObject.find(test);
449             EditorCookie ec = (EditorCookie) dobj.getCookie(EditorCookie.class);
450             final StyledDocument JavaDoc[] doc = new StyledDocument JavaDoc[] {ec.openDocument()};
451             Thread.sleep(500); //Making test a more deterministic, when the task is cancelled by DocListener, it's hard for test to recover from it
452
NbDocument.runAtomic (doc[0],
453                     new Runnable JavaDoc () {
454                 public void run () {
455                     try {
456                         String JavaDoc text = doc[0].getText(0,doc[0].getLength());
457                         int index = text.indexOf(REPLACE_PATTERN);
458                         assertTrue (index != -1);
459                         doc[0].remove(index,REPLACE_PATTERN.length());
460                         doc[0].insertString(index,"System.out.println();",null);
461                     } catch (BadLocationException JavaDoc ble) {
462                         ble.printStackTrace(System.out);
463                     }
464                 }
465             });
466
467             final boolean[] contentCorrect = new boolean[1];
468
469             js.runUserActionTask(new CancellableTask<CompilationController>() {
470                 public void run(CompilationController controler) {
471                     try {
472                         controler.toPhase(Phase.PARSED);
473                         contentCorrect[0] = controler.getText().contains("System.out.println");
474                         latch2.countDown();
475                     } catch (IOException JavaDoc ioe) {
476                         ioe.printStackTrace();
477                     }
478                 }
479                 public void cancel() {
480                 }
481             },true);
482
483             assertTrue("Time out",waitForMultipleObjects(new CountDownLatch JavaDoc[] {latch2}, 15000));
484             assertTrue("Content incorrect", contentCorrect[0]);
485
486             js.removePhaseCompletionTask (task);
487         } finally {
488             JavaSource.REPARSE_DELAY = originalReparseDelay;
489         }
490     }
491     
492     //this test is quite unreliable (it often passes even in cases it should fail):
493
public void testInvalidatesCorrectly() throws MalformedURLException JavaDoc, InterruptedException JavaDoc, IOException JavaDoc, BadLocationException JavaDoc {
494         FileObject test = createTestFile ("Test1");
495         ClassPath bootPath = createBootPath ();
496         ClassPath compilePath = createCompilePath ();
497         JavaSource js = JavaSource.create(ClasspathInfo.create(bootPath, compilePath, null), test);
498         CountDownLatch JavaDoc[] latches = new CountDownLatch JavaDoc[] {
499             new CountDownLatch JavaDoc (1),
500             new CountDownLatch JavaDoc (1),
501             new CountDownLatch JavaDoc (1),
502         };
503         AtomicInteger JavaDoc counter = new AtomicInteger JavaDoc (0);
504         DiagnosticTask task = new DiagnosticTask(latches, counter, Phase.PARSED);
505         js.addPhaseCompletionTask (task,Phase.PARSED,Priority.HIGH);
506         assertTrue ("Time out",waitForMultipleObjects(new CountDownLatch JavaDoc[] {latches[0]}, 15000));
507         
508         DataObject dobj = DataObject.find(test);
509         EditorCookie ec = (EditorCookie) dobj.getCookie(EditorCookie.class);
510         final StyledDocument JavaDoc[] doc = new StyledDocument JavaDoc[] {ec.openDocument()};
511         final int[] index = new int[1];
512         Thread.sleep(500); //Making test a more deterministic, when the task is cancelled by DocListener, it's hard for test to recover from it
513
NbDocument.runAtomic (doc[0],
514                 new Runnable JavaDoc () {
515             public void run () {
516                 try {
517                     String JavaDoc text = doc[0].getText(0,doc[0].getLength());
518                     index[0] = text.indexOf(REPLACE_PATTERN);
519                     assertTrue (index[0] != -1);
520                     doc[0].remove(index[0],REPLACE_PATTERN.length());
521                     doc[0].insertString(index[0],"System.out.println();",null);
522                 } catch (BadLocationException JavaDoc ble) {
523                     ble.printStackTrace(System.out);
524                 }
525             }
526         });
527         
528         assertTrue ("Time out",waitForMultipleObjects(new CountDownLatch JavaDoc[] {latches[1]}, 15000));
529         Thread.sleep(500); //Making test a more deterministic, when the task is cancelled by DocListener, it's hard for test to recover from it
530
NbDocument.runAtomic(doc[0],
531                 new Runnable JavaDoc() {
532             public void run() {
533                 try {
534                     doc[0].insertString(index[0],"System.out.println();",null);
535                 } catch (BadLocationException JavaDoc ble) {
536                     ble.printStackTrace(System.out);
537                 }
538             }
539         });
540         //not sure how to make this 100% reliable.
541
//this task has to be the first run after the previous change to document.
542
js.runUserActionTask(new CancellableTask<CompilationController>() {
543             public void run(CompilationController controler) {
544                 try {
545                     controler.toPhase(Phase.PARSED);
546                 } catch (IOException JavaDoc ioe) {
547                     ioe.printStackTrace();
548                 }
549             }
550             public void cancel() {
551             }
552         },true);
553         
554         assertTrue("Time out",waitForMultipleObjects(new CountDownLatch JavaDoc[] {latches[2]}, 15000));
555         
556         js.removePhaseCompletionTask (task);
557     }
558     
559     
560     /**
561      * Tests deadlock
562      */

563     public void testRTB_005 () throws Exception JavaDoc {
564         try {
565             Object JavaDoc lock = new String JavaDoc ("Lock");
566             JavaSource.jfoProvider = new TestProvider (lock);
567             FileObject test = createTestFile ("Test1");
568             ClassPath bootPath = createBootPath ();
569             ClassPath compilePath = createCompilePath ();
570             JavaSource js = JavaSource.create(ClasspathInfo.create(bootPath, compilePath, null), test);
571             js.addPhaseCompletionTask( new CancellableTask<CompilationInfo>() {
572                 public void run (CompilationInfo info) {
573                     
574                 }
575                 
576                 public void cancel () {
577                     
578                 }
579             },Phase.PARSED,Priority.NORMAL);
580             
581             synchronized (lock) {
582                 js.revalidate();
583                 Thread.sleep(2000);
584                 js.runUserActionTask(new CancellableTask<CompilationController> () {
585                     public void run (CompilationController c) {
586                         
587                     }
588                     
589                     public void cancel () {
590                         
591                     }
592                 },true);
593             }
594             
595         } finally {
596             JavaSource.jfoProvider = new JavaSource.DefaultJavaFileObjectProvider ();
597         }
598     }
599     
600     
601     public void testCancelCall () throws Exception JavaDoc {
602         FileObject test = createTestFile ("Test1");
603         ClassPath bootPath = createBootPath ();
604         ClassPath compilePath = createCompilePath ();
605         JavaSource js = JavaSource.create(ClasspathInfo.create(bootPath, compilePath, null), test);
606         WaitTask wt = new WaitTask (3000);
607         js.addPhaseCompletionTask(wt, Phase.PARSED, Priority.BELOW_NORMAL);
608         Thread.sleep(1000);
609         WaitTask wt2 = new WaitTask (0);
610         js.addPhaseCompletionTask(wt2, Phase.PARSED,Priority.MAX);
611         Thread.sleep(10000);
612         int cancelCount = wt.getCancelCount();
613         assertEquals(1,cancelCount);
614         int runCount = wt.getRunCount();
615         assertEquals(2,runCount);
616         js.removePhaseCompletionTask(wt);
617         js.removePhaseCompletionTask(wt2);
618     }
619     
620     public void testMultiJavaSource () throws Exception JavaDoc {
621         final FileObject testFile1 = createTestFile("Test1");
622         final FileObject testFile2 = createTestFile("Test2");
623         final FileObject testFile3 = createTestFile("Test3");
624         final ClassPath bootPath = createBootPath();
625         final ClassPath compilePath = createCompilePath();
626         final ClasspathInfo cpInfo = ClasspathInfo.create(bootPath,compilePath,null);
627         final JavaSource js = JavaSource.create(cpInfo,testFile1, testFile2, testFile3);
628         CountDownLatch JavaDoc latch = new CountDownLatch JavaDoc (3);
629         CompileControlJob ccj = new CompileControlJob (latch);
630         js.runUserActionTask(ccj,true);
631         assertTrue(waitForMultipleObjects(new CountDownLatch JavaDoc[] {latch},10000));
632         
633         latch = new CountDownLatch JavaDoc (4);
634         CompileControlJobWithOOM ccj2 = new CompileControlJobWithOOM (latch,1);
635         js.runUserActionTask(ccj2,true);
636         assertTrue(waitForMultipleObjects(new CountDownLatch JavaDoc[] {latch},10000));
637     }
638     
639     public void testEmptyJavaSource () throws Exception JavaDoc {
640         final ClassPath bootPath = createBootPath();
641         final ClassPath compilePath = createCompilePath();
642         final ClasspathInfo cpInfo = ClasspathInfo.create(bootPath,compilePath,null);
643         final JavaSource js = JavaSource.create(cpInfo);
644         CountDownLatch JavaDoc latch = new CountDownLatch JavaDoc (1);
645         EmptyCompileControlJob ccj = new EmptyCompileControlJob (latch);
646         js.runUserActionTask(ccj,true);
647         assertTrue(waitForMultipleObjects(new CountDownLatch JavaDoc[] {latch},10000));
648     }
649     
650     public void testCancelDeadLock () throws Exception JavaDoc {
651         final FileObject testFile1 = createTestFile("Test1");
652         final ClassPath bootPath = createBootPath();
653         final ClassPath compilePath = createCompilePath();
654         final ClasspathInfo cpInfo = ClasspathInfo.create(bootPath,compilePath,null);
655         final JavaSource js = JavaSource.create(cpInfo,testFile1);
656         js.runUserActionTask(
657                 new CancellableTask<CompilationController>() {
658             
659                     public void cancel() {
660                     }
661                     
662                     public void run(CompilationController parameter) throws Exception JavaDoc {
663                         final Thread JavaDoc t = new Thread JavaDoc (new Runnable JavaDoc() {
664                             public void run () {
665                                 try {
666                                 js.runUserActionTask(new CancellableTask<CompilationController>() {
667                                     public void cancel() {
668                                     }
669                                     public void run(CompilationController parameter) throws Exception JavaDoc {
670                                     }
671                                 },true);
672                                 } catch (IOException JavaDoc e) {
673                                     AssertionError JavaDoc er = new AssertionError JavaDoc ();
674                                     e.initCause(e);
675                                     throw er;
676                                 }
677                             }
678                         });
679                         t.start();
680                         Thread.sleep(1000);
681                         js.runUserActionTask (new CancellableTask<CompilationController>() {
682                             
683                             public void cancel() {
684                             }
685                             public void run(CompilationController parameter) throws Exception JavaDoc {
686                             }
687                         },true);
688                     }
689                 },true
690         );
691     }
692     
693     public void testCompileTaskStartedFromPhaseTask () throws Exception JavaDoc {
694         final FileObject testFile1 = createTestFile("Test1");
695         final ClassPath bootPath = createBootPath();
696         final ClassPath compilePath = createCompilePath();
697         final ClasspathInfo cpInfo = ClasspathInfo.create(bootPath,compilePath,null);
698         final JavaSource js = JavaSource.create(cpInfo,testFile1);
699         final AtomicBoolean JavaDoc canceled = new AtomicBoolean JavaDoc (false);
700         final CountDownLatch JavaDoc latch = new CountDownLatch JavaDoc (1);
701         js.addPhaseCompletionTask(new CancellableTask<CompilationInfo> () {
702             
703             private boolean called = false;
704             
705             public void cancel() {
706                 canceled.set(true);
707             }
708             
709             public void run(CompilationInfo parameter) throws Exception JavaDoc {
710                 if (!called) {
711                     js.runUserActionTask(new CancellableTask<CompilationController>() {
712                         public void cancel() {
713                         }
714                         public void run(CompilationController parameter) throws Exception JavaDoc {
715                         }
716                     },true);
717                     called = true;
718                     latch.countDown();
719                 }
720             }
721         }, Phase.PARSED, Priority.NORMAL);
722         assertTrue (waitForMultipleObjects(new CountDownLatch JavaDoc[] {latch}, 10000));
723         assertFalse ("Cancel called even for JavaSource dispatch thread!",canceled.get());
724     }
725     
726     public void testUnsharedUserActionTask () throws IOException JavaDoc {
727         final FileObject testFile1 = createTestFile("Test1");
728         final ClassPath bootPath = createBootPath();
729         final ClassPath compilePath = createCompilePath();
730         final ClasspathInfo cpInfo = ClasspathInfo.create(bootPath,compilePath,null);
731         final JavaSource js = JavaSource.create(cpInfo,testFile1);
732         final int[] identityHashCodes = new int[3];
733         js.runUserActionTask(new CancellableTask<CompilationController> () {
734             
735             public void run (CompilationController c) {
736                 identityHashCodes[0] = System.identityHashCode(c.delegate);
737             }
738             
739             public void cancel () {
740                 
741             }
742         },true);
743         
744         js.runUserActionTask(new CancellableTask<CompilationController> () {
745             
746             public void run (CompilationController c) {
747                 identityHashCodes[1] = System.identityHashCode(c.delegate);
748             }
749             
750             public void cancel () {
751                 
752             }
753         },false);
754         
755         
756         js.runUserActionTask(new CancellableTask<CompilationController> () {
757             
758             public void run (CompilationController c) {
759                 identityHashCodes[2] = System.identityHashCode(c.delegate);
760             }
761             
762             public void cancel () {
763                 
764             }
765         },false);
766         
767         assertEquals(identityHashCodes[0], identityHashCodes[1]);
768         assertFalse(identityHashCodes[1] == identityHashCodes[2]);
769     }
770     
771     public void testRescheduleDoesNotStore() throws IOException JavaDoc, InterruptedException JavaDoc {
772         final FileObject testFile1 = createTestFile("Test1");
773         final ClassPath bootPath = createBootPath();
774         final ClassPath compilePath = createCompilePath();
775         final ClasspathInfo cpInfo = ClasspathInfo.create(bootPath,compilePath,null);
776         final JavaSource js = JavaSource.create(cpInfo,testFile1);
777         final CountDownLatch JavaDoc waitFor = new CountDownLatch JavaDoc (1);
778         final CountDownLatch JavaDoc second = new CountDownLatch JavaDoc (3);
779         final int[] count = new int[1];
780         final CancellableTask<CompilationInfo> task = new CancellableTask<CompilationInfo> () {
781             public void cancel() { }
782             public void run(CompilationInfo parameter) throws Exception JavaDoc {
783                 count[0]++;
784                 second.countDown();
785             }
786         };
787         js.addPhaseCompletionTask(new CancellableTask<CompilationInfo> () {
788             public void cancel() { }
789             public void run(CompilationInfo parameter) throws Exception JavaDoc {
790                 waitFor.await();
791             }
792         }, Phase.PARSED, Priority.NORMAL);
793         js.addPhaseCompletionTask(task, Phase.PARSED, Priority.NORMAL);
794         js.rescheduleTask(task);
795         js.rescheduleTask(task);
796         waitFor.countDown();
797         second.await(10, TimeUnit.SECONDS);
798         assertEquals(1, count[0]);
799     }
800     
801     
802     public void testNestedActions () throws Exception JavaDoc {
803         final FileObject testFile1 = createTestFile("Test1");
804         final ClassPath bootPath = createBootPath();
805         final ClassPath compilePath = createCompilePath();
806         final ClasspathInfo cpInfo = ClasspathInfo.create(bootPath,compilePath,null);
807         final JavaSource js = JavaSource.create(cpInfo,testFile1);
808         final Object JavaDoc[] delegateRef = new Object JavaDoc[1];
809         // 1) Two consequent shared tasks have to share CompilationInfo
810
js.runUserActionTask(new CancellableTask<CompilationController>() {
811             
812             public void run (CompilationController control) {
813                 delegateRef[0] = control.delegate;
814             }
815             public void cancel () {
816                 
817             }
818         }, true);
819         
820         js.runUserActionTask(new CancellableTask<CompilationController>() {
821             
822             public void run (CompilationController control) {
823                 assertTrue(delegateRef[0] == control.delegate);
824             }
825             public void cancel () {
826                 
827             }
828         }, true);
829         
830         //2) Task following the unshared task has to have new CompilationInfo
831
js.runUserActionTask(new CancellableTask<CompilationController>() {
832             
833             public void run (CompilationController control) {
834                 delegateRef[0] = control.delegate;
835             }
836             public void cancel () {
837                 
838             }
839         }, false);
840         
841         js.runUserActionTask(new CancellableTask<CompilationController>() {
842             
843             public void run (CompilationController control) {
844                 assertTrue(delegateRef[0] != control.delegate);
845             }
846             public void cancel () {
847                 
848             }
849         }, true);
850         
851         //3) Shared task started from shared task has to have CompilationInfo from the parent
852
// The shared task follong these tasks has to have the same CompilationInfo
853
js.runUserActionTask(new CancellableTask<CompilationController>() {
854             
855             public void run (CompilationController control) {
856                 delegateRef[0] = control.delegate;
857                 final Object JavaDoc[] delegateRef2 = new Object JavaDoc[] {control.delegate};
858                 try {
859                     js.runUserActionTask(new CancellableTask<CompilationController> () {
860                         public void run (CompilationController control) {
861                             assertTrue (delegateRef2[0] == control.delegate);
862                         }
863
864                         public void cancel () {}
865                     }, true);
866                 } catch (IOException JavaDoc ioe) {
867                     RuntimeException JavaDoc re = new RuntimeException JavaDoc ();
868                     re.initCause(ioe);
869                     throw re;
870                 }
871             }
872             public void cancel () {}
873         }, true);
874         
875         js.runUserActionTask(new CancellableTask<CompilationController>() {
876             
877             public void run (CompilationController controll) {
878                 assertTrue(delegateRef[0] == controll.delegate);
879             }
880             public void cancel () {
881                 
882             }
883         }, true);
884         
885         //4) Shared task started from unshared task has to have CompilationInfo from the parent (unshared task)
886
// The shared task follong these tasks has to have new CompilationInfo
887
js.runUserActionTask(new CancellableTask<CompilationController>() {
888             
889             public void run (CompilationController control) {
890                 delegateRef[0] = control.delegate;
891                 final Object JavaDoc[] delegateRef2 = new Object JavaDoc[] {control.delegate};
892                 try {
893                     js.runUserActionTask(new CancellableTask<CompilationController> () {
894                         public void run (CompilationController control) {
895                             assertTrue (delegateRef2[0] == control.delegate);
896                         }
897
898                         public void cancel () {}
899                     }, true);
900                 } catch (IOException JavaDoc ioe) {
901                     RuntimeException JavaDoc re = new RuntimeException JavaDoc ();
902                     re.initCause(ioe);
903                     throw re;
904                 }
905             }
906             public void cancel () {}
907         }, false);
908         
909         js.runUserActionTask(new CancellableTask<CompilationController>() {
910             
911             public void run (CompilationController controll) {
912                 assertTrue(delegateRef[0] != controll.delegate);
913             }
914             public void cancel () {
915                 
916             }
917         }, true);
918         
919         //5) Unshared task started from unshared task has to have new CompilationInfo
920
// The shared task following these tasks has to also have new CompilationInfo
921
final Object JavaDoc[] delegateRef2 = new Object JavaDoc[1];
922         js.runUserActionTask(new CancellableTask<CompilationController>() {
923             public void run (CompilationController control) {
924                 delegateRef[0] = control.delegate;
925                 try {
926                     js.runUserActionTask(new CancellableTask<CompilationController> () {
927                         public void run (CompilationController control) {
928                             assertTrue (delegateRef[0] != control.delegate);
929                             delegateRef2[0] = control.delegate;
930                         }
931
932                         public void cancel () {}
933                     }, false);
934                 } catch (IOException JavaDoc ioe) {
935                     RuntimeException JavaDoc re = new RuntimeException JavaDoc ();
936                     re.initCause(ioe);
937                     throw re;
938                 }
939             }
940             public void cancel () {}
941         }, false);
942         
943         js.runUserActionTask(new CancellableTask<CompilationController>() {
944             
945             public void run (CompilationController controll) {
946                 assertTrue(delegateRef[0] != controll.delegate);
947                 assertTrue(delegateRef2[0] != controll.delegate);
948             }
949             public void cancel () {
950                 
951             }
952         }, true);
953         
954         //6)Shared task(3) started from unshared task(2) which is started from other unshared task (1)
955
// has to see the CompilationInfo from the task (2) which is not equal to CompilationInfo from (1)
956
js.runUserActionTask(new CancellableTask<CompilationController>() {
957             public void run (CompilationController control) {
958                 delegateRef[0] = control.delegate;
959                 try {
960                     js.runUserActionTask(new CancellableTask<CompilationController> () {
961                         public void run (CompilationController control) {
962                             assertTrue (delegateRef[0] != control.delegate);
963                             delegateRef2[0] = control.delegate;
964                             try {
965                                 js.runUserActionTask(new CancellableTask<CompilationController> () {
966                                     public void run (CompilationController control) {
967                                         assertTrue (delegateRef[0] != control.delegate);
968                                         assertTrue (delegateRef2[0] == control.delegate);
969                                     }
970                                     public void cancel () {}
971                                 }, true);
972                             } catch (IOException JavaDoc ioe) {
973                                 RuntimeException JavaDoc re = new RuntimeException JavaDoc ();
974                                 re.initCause(ioe);
975                                 throw re;
976                             }
977                         }
978                         public void cancel () {}
979                     }, false);
980                 } catch (IOException JavaDoc ioe) {
981                     RuntimeException JavaDoc re = new RuntimeException JavaDoc ();
982                     re.initCause(ioe);
983                     throw re;
984                 }
985             }
986             public void cancel () {}
987         }, false);
988         
989         //6)Task(4) started after unshared task(3) started from shared task(2) which is started from other shared task (1)
990
// has to have new CompilationInfo but the task (1) (2) (3) have to have the same CompilationInfo.
991
js.runUserActionTask(new CancellableTask<CompilationController>() {
992             public void run (CompilationController control) {
993                 delegateRef[0] = control.delegate;
994                 try {
995                     js.runUserActionTask(new CancellableTask<CompilationController> () {
996                         public void run (CompilationController control) {
997                             assertTrue (delegateRef[0] == control.delegate);
998                             try {
999                                 js.runUserActionTask(new CancellableTask<CompilationController> () {
1000                                    public void run (CompilationController control) {
1001                                        assertTrue (delegateRef[0] == control.delegate);
1002                                    }
1003                                    public void cancel () {}
1004                                }, false);
1005                                js.runUserActionTask(new CancellableTask<CompilationController> () {
1006                                    public void run (CompilationController control) {
1007                                        assertTrue (delegateRef[0] != control.delegate);
1008                                    }
1009                                    public void cancel () {}
1010                                }, true);
1011                            } catch (IOException JavaDoc ioe) {
1012                                RuntimeException JavaDoc re = new RuntimeException JavaDoc ();
1013                                re.initCause(ioe);
1014                                throw re;
1015                            }
1016                        }
1017                        public void cancel () {}
1018                    }, true);
1019                } catch (IOException JavaDoc ioe) {
1020                    RuntimeException JavaDoc re = new RuntimeException JavaDoc ();
1021                    re.initCause(ioe);
1022                    throw re;
1023                }
1024            }
1025            public void cancel () {}
1026        }, true);
1027        
1028    }
1029    
1030    public void testCouplingErrors() throws Exception JavaDoc {
1031        File JavaDoc workdir = this.getWorkDir();
1032        File JavaDoc src1File = new File JavaDoc (workdir, "src1");
1033        src1File.mkdir();
1034        final FileObject src1 = FileUtil.toFileObject(src1File);
1035        
1036        File JavaDoc src2File = new File JavaDoc (workdir, "src2");
1037        src2File.mkdir();
1038        final FileObject src2 = FileUtil.toFileObject(src2File);
1039        
1040        createTestFile(src1, "test/Test.java", "package test; public class Test {private long x;}");
1041        
1042        final FileObject test = createTestFile(src2, "test/Test.java", "package test; public class Test {private int x;}");
1043        final FileObject test2 = createTestFile(src2, "test/Test2.java", "package test; public class Test2 {private Test x;}");
1044        
1045        File JavaDoc cache = new File JavaDoc(workdir, "cache");
1046        
1047        cache.mkdirs();
1048        
1049        SourceUtilsTestUtil2.disableLocks();
1050        IndexUtil.setCacheFolder(cache);
1051
1052        ClassLoader JavaDoc l = JavaSourceTest.class.getClassLoader();
1053        Lkp.DEFAULT.setLookupsWrapper(
1054                Lookups.metaInfServices(l),
1055                Lookups.singleton(l),
1056                Lookups.singleton(new ClassPathProvider() {
1057            public ClassPath findClassPath(FileObject file, String JavaDoc type) {
1058                try {
1059                    if (ClassPath.BOOT == type) {
1060                        return createBootPath();
1061                    }
1062                    
1063                    if (ClassPath.SOURCE == type) {
1064                        return ClassPathSupport.createClassPath(new FileObject[] {
1065                            src1
1066                        });
1067                    }
1068                    
1069                    if (ClassPath.COMPILE == type) {
1070                        return createCompilePath();
1071                    }
1072                    
1073                    if (ClassPath.EXECUTE == type) {
1074                        return ClassPathSupport.createClassPath(new FileObject[] {
1075                        });
1076                    }
1077                } catch (Exception JavaDoc e) {
1078                    e.printStackTrace();
1079                }
1080                return null;
1081            }
1082            
1083        }));
1084        
1085        RepositoryUpdater.getDefault().scheduleCompilationAndWait(src1, src1).await();
1086        
1087        final ClassPath bootPath = createBootPath();
1088        final ClassPath compilePath = CacheClassPath.forSourcePath(ClassPathSupport.createClassPath(new FileObject[] {src1}));
1089        final ClasspathInfo cpInfo = ClasspathInfo.create(bootPath,compilePath,null);
1090        final JavaSource js = JavaSource.create(cpInfo, test2, test);
1091        
1092        final List JavaDoc<FileObject> files = new ArrayList JavaDoc<FileObject>();
1093        
1094        js.runUserActionTask(new CancellableTask<CompilationController>() {
1095            public void run(CompilationController cc) throws IOException JavaDoc {
1096                files.add(cc.getFileObject());
1097                cc.toPhase(Phase.RESOLVED);
1098            }
1099            public void cancel() {}
1100        }, true);
1101        
1102        assertEquals(Arrays.asList(test2, test, test), files);
1103        
1104        files.clear();
1105        
1106        js.runModificationTask(new CancellableTask<WorkingCopy>() {
1107            public void run(WorkingCopy cc) throws IOException JavaDoc {
1108                files.add(cc.getFileObject());
1109                cc.toPhase(Phase.RESOLVED);
1110            }
1111            public void cancel() {}
1112        });
1113        
1114        assertEquals(Arrays.asList(test2, test, test), files);
1115    }
1116    
1117    private static class TestProvider implements JavaSource.JavaFileObjectProvider {
1118        
1119        private Object JavaDoc lock;
1120        
1121        public TestProvider (Object JavaDoc lock) {
1122            assert lock != null;
1123            this.lock = lock;
1124        }
1125        
1126        public JavaFileObject createJavaFileObject(FileObject fo, JavaFileFilterImplementation filter) throws IOException JavaDoc {
1127            return new TestJavaFileObject (fo, lock);
1128        }
1129    }
1130    
1131    private static class TestJavaFileObject extends SourceFileObject {
1132        
1133        public TestJavaFileObject (FileObject fo, Object JavaDoc lock) throws IOException JavaDoc {
1134            super (fo,null, true);
1135            //Deadlock
1136
synchronized (lock) {
1137                lock.toString();
1138            }
1139        }
1140    }
1141    
1142    private static class CompileControlJob implements CancellableTask<CompilationController> {
1143        
1144        private final CountDownLatch JavaDoc latch;
1145        
1146        public CompileControlJob (CountDownLatch JavaDoc latch) {
1147            this.latch = latch;
1148        }
1149        
1150        public void cancel () {
1151        }
1152        
1153        public void run (CompilationController controler) {
1154            try {
1155                controler.toPhase(Phase.PARSED);
1156                if (!controler.delegate.needsRestart) {
1157                    assertTrue (Phase.PARSED.compareTo(controler.getPhase())<=0);
1158                    assertNotNull("No ComplationUnitTrees after parse",controler.getCompilationUnit());
1159                    controler.toPhase(Phase.RESOLVED);
1160                    assertTrue (Phase.RESOLVED.compareTo(controler.getPhase())<=0);
1161
1162                    //all elements should be resolved now:
1163
new ScannerImpl(controler).scan(controler.getCompilationUnit(), null);
1164
1165                    controler.toPhase(Phase.PARSED);
1166                    //Was not modified should stay in {@link Phase#RESOLVED}
1167
assertTrue (Phase.RESOLVED.compareTo(controler.getPhase())<=0);
1168                    this.latch.countDown();
1169                }
1170            } catch (IOException JavaDoc ioe) {
1171                ioe.printStackTrace();
1172            }
1173        }
1174    }
1175    
1176    private static class ScannerImpl extends TreePathScanner<Void JavaDoc, Void JavaDoc> {
1177        
1178        private CompilationInfo info;
1179        
1180        public ScannerImpl(CompilationInfo info) {
1181            this.info = info;
1182        }
1183        
1184        public Void JavaDoc visitIdentifier(IdentifierTree node, Void JavaDoc p) {
1185            assertNotNull(info.getTrees().getElement(getCurrentPath()));
1186            return super.visitIdentifier(node, p);
1187        }
1188
1189    }
1190    
1191    private static class WorkingCopyJob implements CancellableTask<WorkingCopy> {
1192        
1193        private final CountDownLatch JavaDoc latch;
1194        
1195        public WorkingCopyJob (CountDownLatch JavaDoc latch) {
1196            this.latch = latch;
1197        }
1198        
1199        public void cancel () {
1200        }
1201        
1202        public void run (WorkingCopy copy) throws IOException JavaDoc {
1203            copy.toPhase(Phase.RESOLVED);
1204            assertTrue (Phase.RESOLVED.compareTo(copy.getPhase())<=0);
1205            assertNotNull("No ComplationUnitTrees after parse",copy.getCompilationUnit());
1206            
1207            new TransformImpl(copy).scan(copy.getCompilationUnit(), null);
1208
1209            this.latch.countDown();
1210        }
1211    }
1212    
1213    private static class TransformImpl extends TreeScanner<Void JavaDoc, Object JavaDoc> {
1214
1215        private WorkingCopy copy;
1216        
1217        public TransformImpl(WorkingCopy copy) {
1218            this.copy = copy;
1219        }
1220        
1221        public Void JavaDoc visitClass(ClassTree node, Object JavaDoc p) {
1222            TreeMaker make = copy.getTreeMaker();
1223            ClassTree newNode = make.addClassMember(node, make.Variable(make.Modifiers(Collections.singleton(Modifier.PUBLIC)), "field", make.Identifier("int"), null));
1224            
1225            copy.rewrite(node, newNode);
1226            return null;
1227        }
1228
1229    }
1230    
1231    private static class CompileControlJobWithOOM implements CancellableTask<CompilationController> {
1232        
1233        private final CountDownLatch JavaDoc latch;
1234        private final int oomFor;
1235        private int currentIndex;
1236        private URI JavaDoc uri;
1237        
1238        public CompileControlJobWithOOM (CountDownLatch JavaDoc latch, int oomFor) {
1239            this.latch = latch;
1240            this.oomFor = oomFor;
1241        }
1242        
1243        public void cancel () {
1244        }
1245        
1246        public void run (CompilationController controler) {
1247            try {
1248                controler.toPhase(Phase.PARSED);
1249                assertTrue (Phase.PARSED.compareTo(controler.getPhase())<=0);
1250                CompilationUnitTree cut = controler.getCompilationUnit();
1251                assertNotNull("No ComplationUnitTree after parse",cut);
1252                controler.toPhase(Phase.RESOLVED);
1253                assertTrue (Phase.RESOLVED.compareTo(controler.getPhase())<=0);
1254                controler.toPhase(Phase.PARSED);
1255                //Was not modified should stay in {@link Phase#RESOLVED}
1256
assertTrue (Phase.RESOLVED.compareTo(controler.getPhase())<=0);
1257                if (currentIndex == oomFor) {
1258                    Class JavaDoc<CompilationController> clazz = CompilationController.class;
1259                    Field JavaDoc delegateField = clazz.getDeclaredField("delegate");
1260                    delegateField.setAccessible(true);
1261                    CompilationInfo delegate = (CompilationInfo) delegateField.get(controler);
1262                    delegate.needsRestart = true;
1263                    uri = cut.getSourceFile().toUri();
1264                }
1265                if (currentIndex == oomFor+1) {
1266                    assertNotNull (uri);
1267                    assertEquals(uri,cut.getSourceFile().toUri());
1268                    uri = null;
1269                }
1270                this.latch.countDown();
1271            } catch (Exception JavaDoc e) {
1272                e.printStackTrace();
1273            }
1274            finally {
1275                this.currentIndex++;
1276            }
1277        }
1278    }
1279    
1280    
1281    private static class EmptyCompileControlJob implements CancellableTask<CompilationController> {
1282        
1283        private final CountDownLatch JavaDoc latch;
1284        
1285        public EmptyCompileControlJob (CountDownLatch JavaDoc latch) {
1286            this.latch = latch;
1287        }
1288        
1289        public void cancel () {
1290        }
1291        
1292        public void run (CompilationController controler) {
1293            try {
1294                try {
1295                    //Should throw exception
1296
assertEquals(Phase.PARSED, controler.toPhase(Phase.PARSED));
1297                } catch (IllegalStateException JavaDoc e) {
1298                }
1299                try {
1300                    //Should throw exception
1301
controler.getCompilationUnit();
1302                    throw new AssertionError JavaDoc ();
1303                } catch (IllegalStateException JavaDoc e) {
1304                }
1305                controler.getPhase();
1306                controler.getTypes();
1307                controler.getTrees();
1308                controler.getElements();
1309                controler.getClasspathInfo();
1310                controler.getJavaSource();
1311                this.latch.countDown();
1312            } catch (IOException JavaDoc ioe) {
1313                ioe.printStackTrace();
1314            }
1315        }
1316    }
1317    
1318    
1319    
1320    private static boolean waitForMultipleObjects (CountDownLatch JavaDoc[] objects, int timeOut) throws InterruptedException JavaDoc {
1321        for (CountDownLatch JavaDoc latch : objects) {
1322            long ctms = System.currentTimeMillis();
1323            if (!latch.await(timeOut, TimeUnit.MILLISECONDS)) {
1324                return false;
1325            }
1326            long ctme = System.currentTimeMillis ();
1327            timeOut -= (ctme - ctms);
1328        }
1329        return true;
1330    }
1331    
1332    
1333    private static class DiagnosticTask implements CancellableTask<CompilationInfo> {
1334        
1335        private final Phase expectedPhase;
1336        private final CountDownLatch JavaDoc[] latches;
1337        private final long[] times;
1338        private final AtomicInteger JavaDoc counter;
1339        private int currentLatch;
1340        private int cancelCount;
1341        boolean verbose;
1342        
1343        public DiagnosticTask (final CountDownLatch JavaDoc[] latches, final AtomicInteger JavaDoc counter, final Phase expectedPhase) {
1344            this(latches, new long[latches.length], counter, expectedPhase);
1345        }
1346        
1347        public DiagnosticTask (final CountDownLatch JavaDoc[] latches, final long[] times, final AtomicInteger JavaDoc counter, final Phase expectedPhase) {
1348            assertEquals(times.length, latches.length);
1349            this.latches = latches;
1350            this.times = times;
1351            this.counter = counter;
1352            this.expectedPhase = expectedPhase;
1353        }
1354        
1355        public synchronized void run(CompilationInfo parameter) {
1356            if (verbose) {
1357                System.out.println("run called");
1358            }
1359            if (this.cancelCount>0) {
1360                this.cancelCount--;
1361                if (verbose) {
1362                    System.out.println("Cancel count: " + cancelCount);
1363                }
1364                return;
1365            }
1366            if (this.counter != null) {
1367                int current = this.counter.incrementAndGet();
1368                if (verbose) {
1369                    System.out.println("counter="+current);
1370                }
1371            }
1372            if (this.currentLatch < this.times.length) {
1373                if (verbose) {
1374                    System.out.println("Firing current latch: " + this.currentLatch);
1375                }
1376                this.times[this.currentLatch] = System.currentTimeMillis();
1377                this.latches[this.currentLatch++].countDown();
1378            }
1379            assertNotNull (parameter);
1380            assertTrue (String.format("Got wrong state, expected: %s got: %s", expectedPhase.name(), parameter.getPhase().name()), this.expectedPhase.compareTo(parameter.getPhase())<=0);
1381        }
1382
1383        public synchronized void cancel() {
1384            this.cancelCount++;
1385            if (verbose) {
1386                System.out.println("cancel called: " + cancelCount);
1387            }
1388        }
1389        
1390    }
1391    
1392    
1393    private static class WaitTask implements CancellableTask<CompilationInfo> {
1394        
1395        private long milisToWait;
1396        private int cancelCount;
1397        private int runCount;
1398        
1399        public WaitTask (long milisToWait) {
1400            this.milisToWait = milisToWait;
1401            this.cancelCount = 0;
1402            this.runCount = 0;
1403        }
1404        
1405        public void run (CompilationInfo info) {
1406            this.runCount++;
1407            if (this.milisToWait>0) {
1408                try {
1409                    Thread.sleep(this.milisToWait);
1410                } catch (InterruptedException JavaDoc ie) {}
1411            }
1412        }
1413        
1414        public void cancel () {
1415            this.cancelCount++;
1416        }
1417        
1418        public int getCancelCount () {
1419            return this.cancelCount;
1420        }
1421        
1422        public int getRunCount () {
1423            return this.runCount;
1424        }
1425        
1426    }
1427    
1428    private FileObject createTestFile (String JavaDoc className) {
1429        try {
1430            File JavaDoc workdir = this.getWorkDir();
1431            File JavaDoc root = new File JavaDoc (workdir, "src");
1432            root.mkdir();
1433            File JavaDoc data = new File JavaDoc (root, className+".java");
1434        
1435            PrintWriter JavaDoc out = new PrintWriter JavaDoc (new FileWriter JavaDoc (data));
1436            try {
1437                out.println(MessageFormat.format(TEST_FILE_CONTENT, new Object JavaDoc[] {className}));
1438            } finally {
1439                out.close ();
1440            }
1441            return FileUtil.toFileObject(data);
1442        } catch (IOException JavaDoc ioe) {
1443            return null;
1444        }
1445    }
1446    
1447    private ClassPath createBootPath () throws MalformedURLException JavaDoc {
1448        String JavaDoc bootPath = System.getProperty ("sun.boot.class.path");
1449        String JavaDoc[] paths = bootPath.split(File.pathSeparator);
1450        List JavaDoc<URL JavaDoc>roots = new ArrayList JavaDoc<URL JavaDoc> (paths.length);
1451        for (String JavaDoc path : paths) {
1452            File JavaDoc f = new File JavaDoc (path);
1453            if (!f.exists()) {
1454                continue;
1455            }
1456            URL JavaDoc url = f.toURI().toURL();
1457            if (FileUtil.isArchiveFile(url)) {
1458                url = FileUtil.getArchiveRoot(url);
1459            }
1460            roots.add (url);
1461        }
1462        return ClassPathSupport.createClassPath(roots.toArray(new URL JavaDoc[roots.size()]));
1463    }
1464    
1465    private ClassPath createCompilePath () {
1466        return ClassPathSupport.createClassPath(Collections.EMPTY_LIST);
1467    }
1468    
1469    private FileObject createTestFile (FileObject srcRoot, String JavaDoc relativeName, String JavaDoc content) throws IOException JavaDoc {
1470        FileObject f = FileUtil.createData(srcRoot, relativeName);
1471        Writer JavaDoc out = new OutputStreamWriter JavaDoc(f.getOutputStream());
1472        
1473        try {
1474            out.write(content);
1475        } finally {
1476            out.close();
1477        }
1478        
1479        return f;
1480    }
1481}
1482
Popular Tags