KickJava   Java API By Example, From Geeks To Geeks.

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


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.api.java.source;
20
21 import com.sun.source.util.JavacTask;
22 import java.beans.PropertyVetoException JavaDoc;
23 import java.io.File JavaDoc;
24 import java.io.IOException JavaDoc;
25 import java.net.URL JavaDoc;
26 import java.util.ArrayList JavaDoc;
27 import java.util.Arrays JavaDoc;
28 import java.util.LinkedList JavaDoc;
29 import java.util.List JavaDoc;
30 import java.util.Map JavaDoc;
31 import java.util.WeakHashMap JavaDoc;
32 import java.util.concurrent.CountDownLatch JavaDoc;
33 import java.util.concurrent.TimeUnit JavaDoc;
34 import java.util.regex.Pattern JavaDoc;
35 import javax.swing.event.ChangeListener JavaDoc;
36 import junit.framework.Assert;
37 import org.netbeans.api.java.classpath.ClassPath;
38 import org.netbeans.api.java.queries.SourceForBinaryQuery;
39 import org.netbeans.api.java.source.JavaSource.Phase;
40 import org.netbeans.junit.NbTestCase;
41 import org.netbeans.modules.java.JavaDataLoader;
42 import org.netbeans.modules.java.source.ActivatedDocumentListener;
43 import org.netbeans.modules.java.source.usages.IndexUtil;
44 import org.netbeans.modules.java.source.usages.RepositoryUpdater;
45 import org.netbeans.spi.java.classpath.ClassPathProvider;
46 import org.netbeans.spi.java.classpath.support.ClassPathSupport;
47 import org.netbeans.spi.java.queries.SourceForBinaryQueryImplementation;
48 import org.netbeans.spi.java.queries.SourceLevelQueryImplementation;
49 import org.openide.ErrorManager;
50 import org.openide.filesystems.FileObject;
51 import org.openide.filesystems.FileStateInvalidException;
52 import org.openide.filesystems.FileSystem;
53 import org.openide.filesystems.FileUtil;
54 import org.openide.filesystems.LocalFileSystem;
55 import org.openide.filesystems.MultiFileSystem;
56 import org.openide.filesystems.Repository;
57 import org.openide.filesystems.URLMapper;
58 import org.openide.filesystems.XMLFileSystem;
59 import org.openide.util.Lookup;
60 import org.openide.util.Utilities;
61 import org.openide.util.lookup.Lookups;
62 import org.openide.util.lookup.ProxyLookup;
63 import org.xml.sax.SAXException JavaDoc;
64
65 /**
66  *
67  * @author Jan Lahoda
68  */

69 public final class SourceUtilsTestUtil extends ProxyLookup {
70     
71     private static SourceUtilsTestUtil DEFAULT_LOOKUP = null;
72     
73     public SourceUtilsTestUtil() {
74         Assert.assertNull(DEFAULT_LOOKUP);
75         DEFAULT_LOOKUP = this;
76     }
77     
78     /**
79      * Set the global default lookup with some fixed instances including META-INF/services/*.
80      */

81     /**
82      * Set the global default lookup with some fixed instances including META-INF/services/*.
83      */

84     public static void setLookup(Object JavaDoc[] instances, ClassLoader JavaDoc cl) {
85         DEFAULT_LOOKUP.setLookups(new Lookup[] {
86             Lookups.fixed(instances),
87             Lookups.metaInfServices(cl),
88             Lookups.singleton(cl),
89         });
90     }
91     
92     private static Object JavaDoc[] extraLookupContent = null;
93     
94     public static void prepareTest(String JavaDoc[] additionalLayers, Object JavaDoc[] additionalLookupContent) throws IOException JavaDoc, SAXException JavaDoc, PropertyVetoException JavaDoc {
95         URL JavaDoc[] layers = new URL JavaDoc[additionalLayers.length];
96         
97         for (int cntr = 0; cntr < additionalLayers.length; cntr++) {
98             layers[cntr] = Thread.currentThread().getContextClassLoader().getResource(additionalLayers[cntr]);
99         }
100         
101         XMLFileSystem xmlFS = new XMLFileSystem();
102         xmlFS.setXmlUrls(layers);
103         
104         FileSystem system = new MultiFileSystem(new FileSystem[] {FileUtil.createMemoryFileSystem(), xmlFS});
105         
106         Repository repository = new Repository(system);
107         extraLookupContent = new Object JavaDoc[additionalLookupContent.length + 1];
108         
109         System.arraycopy(additionalLookupContent, 0, extraLookupContent, 1, additionalLookupContent.length);
110         
111         extraLookupContent[0] = repository;
112         
113         DEFAULT_LOOKUP.setLookup(extraLookupContent, SourceUtilsTestUtil.class.getClassLoader());
114         
115         SourceUtilsTestUtil2.disableLocks();
116     }
117     
118     static {
119         SourceUtilsTestUtil.class.getClassLoader().setDefaultAssertionStatus(true);
120         System.setProperty("org.openide.util.Lookup", SourceUtilsTestUtil.class.getName());
121         Assert.assertEquals(SourceUtilsTestUtil.class, Lookup.getDefault().getClass());
122     }
123     
124     public static void prepareTest(FileObject sourceRoot, FileObject buildRoot, FileObject cache) throws Exception JavaDoc {
125         prepareTest(sourceRoot, buildRoot, cache, new FileObject[0]);
126     }
127     
128     public static void prepareTest(FileObject sourceRoot, FileObject buildRoot, FileObject cache, FileObject[] classPathElements) throws Exception JavaDoc {
129         if (extraLookupContent == null)
130             prepareTest(new String JavaDoc[0], new Object JavaDoc[0]);
131         
132         Object JavaDoc[] lookupContent = new Object JavaDoc[extraLookupContent.length + 4];
133         
134         System.arraycopy(extraLookupContent, 0, lookupContent, 4, extraLookupContent.length);
135         
136         lookupContent[0] = new TestProxyClassPathProvider(sourceRoot, buildRoot, classPathElements);
137         lookupContent[1] = new TestSourceForBinaryQuery(sourceRoot, classPathElements);
138         lookupContent[2] = new TestSourceLevelQueryImplementation();
139         lookupContent[3] = JavaDataLoader.findObject(JavaDataLoader.class, true);
140         
141         setLookup(lookupContent, SourceUtilsTestUtil.class.getClassLoader());
142         
143         IndexUtil.setCacheFolder(FileUtil.toFile(cache));
144     }
145
146     private static Map JavaDoc<FileObject, String JavaDoc> file2SourceLevel = new WeakHashMap JavaDoc<FileObject, String JavaDoc>();
147     
148     public static void setSourceLevel(FileObject file, String JavaDoc level) {
149         file2SourceLevel.put(file, level);
150     }
151
152     /**This method assures that all java classes under sourceRoot are compiled,
153      * and the caches are created for them.
154      */

155     public static void compileRecursively(FileObject sourceRoot) throws Exception JavaDoc {
156         List JavaDoc<FileObject> queue = new LinkedList JavaDoc();
157         
158         queue.add(sourceRoot);
159         
160         while (!queue.isEmpty()) {
161             FileObject file = queue.remove(0);
162             
163             if (file.isData()) {
164                 CountDownLatch JavaDoc l = RepositoryUpdater.getDefault().scheduleCompilationAndWait(file, sourceRoot);
165                 
166                 l.await(60, TimeUnit.SECONDS);
167             } else {
168                 queue.addAll(Arrays.asList(file.getChildren()));
169             }
170         }
171     }
172
173     private static List JavaDoc<URL JavaDoc> bootClassPath;
174
175     public static synchronized List JavaDoc<URL JavaDoc> getBootClassPath() {
176         if (bootClassPath == null) {
177             try {
178                 String JavaDoc cp = System.getProperty("sun.boot.class.path");
179                 List JavaDoc<URL JavaDoc> urls = new ArrayList JavaDoc<URL JavaDoc>();
180                 String JavaDoc[] paths = cp.split(Pattern.quote(System.getProperty("path.separator")));
181                 
182                 for (String JavaDoc path : paths) {
183                     File JavaDoc f = new File JavaDoc(path);
184                     
185                     if (!f.canRead())
186                         continue;
187                     
188                     FileObject fo = FileUtil.toFileObject(f);
189                     
190                     if (FileUtil.isArchiveFile(fo)) {
191                         fo = FileUtil.getArchiveRoot(fo);
192                     }
193                     
194                     if (fo != null) {
195                         urls.add(fo.getURL());
196                     }
197                 }
198                 
199                 bootClassPath = urls;
200             } catch (FileStateInvalidException e) {
201                 ErrorManager.getDefault().notify(e);
202             }
203         }
204
205         return bootClassPath;
206     }
207
208     private static class TestSourceForBinaryQuery implements SourceForBinaryQueryImplementation {
209         
210         private FileObject sourceRoot;
211         private List JavaDoc<FileObject> classPathElements;
212         
213         public TestSourceForBinaryQuery(FileObject sourceRoot, FileObject[] classPathElements) {
214             this.sourceRoot = sourceRoot;
215             this.classPathElements = Arrays.asList(classPathElements);
216         }
217         
218         public SourceForBinaryQuery.Result findSourceRoots(URL JavaDoc binaryRoot) {
219             if (getBootClassPath().contains(binaryRoot))
220                 return null;
221
222             if (classPathElements.contains(URLMapper.findFileObject(binaryRoot)))
223                 return null;
224
225             return new SourceForBinaryQuery.Result() {
226                 public FileObject[] getRoots() {
227                     return new FileObject[] {
228                         sourceRoot,
229                     };
230                 }
231                 
232                 public void addChangeListener(ChangeListener JavaDoc l) {
233                 }
234                 
235                 public void removeChangeListener(ChangeListener JavaDoc l) {
236                 }
237             };
238         }
239         
240     }
241     
242     private static class TestProxyClassPathProvider implements ClassPathProvider {
243         
244         private FileObject sourceRoot;
245         private FileObject buildRoot;
246         private FileObject[] classPathElements;
247         
248         public TestProxyClassPathProvider(FileObject sourceRoot, FileObject buildRoot, FileObject[] classPathElements) {
249             this.sourceRoot = sourceRoot;
250             this.buildRoot = buildRoot;
251             this.classPathElements = classPathElements;
252         }
253         
254         public ClassPath findClassPath(FileObject file, String JavaDoc type) {
255             try {
256             if (ClassPath.BOOT == type) {
257                 return ClassPathSupport.createClassPath(getBootClassPath().toArray(new URL JavaDoc[0]));
258             }
259             
260             if (ClassPath.SOURCE == type) {
261                 return ClassPathSupport.createClassPath(new FileObject[] {
262                     sourceRoot
263                 });
264             }
265             
266             if (ClassPath.COMPILE == type) {
267                 return ClassPathSupport.createClassPath(classPathElements);
268             }
269             
270             if (ClassPath.EXECUTE == type) {
271                 return ClassPathSupport.createClassPath(new FileObject[] {
272                     buildRoot
273                 });
274             }
275             } catch (Exception JavaDoc e) {
276                 e.printStackTrace();
277             }
278             return null;
279         }
280         
281     }
282
283     private static class TestSourceLevelQueryImplementation implements SourceLevelQueryImplementation {
284         
285         public String JavaDoc getSourceLevel(FileObject javaFile) {
286             String JavaDoc level = file2SourceLevel.get(javaFile);
287             
288             if (level == null)
289                 return "1.5";
290             else
291                 return level;
292         }
293         
294     }
295
296     /**Copied from org.netbeans.api.project.
297      * Create a scratch directory for tests.
298      * Will be in /tmp or whatever, and will be empty.
299      * If you just need a java.io.File use clearWorkDir + getWorkDir.
300      */

301     public static FileObject makeScratchDir(NbTestCase test) throws IOException JavaDoc {
302         test.clearWorkDir();
303         File JavaDoc root = test.getWorkDir();
304         assert root.isDirectory() && root.list().length == 0;
305         FileObject fo = FileUtil.toFileObject(root);
306         if (fo != null) {
307             // Presumably using masterfs.
308
return fo;
309         } else {
310             // For the benefit of those not using masterfs.
311
LocalFileSystem lfs = new LocalFileSystem();
312             try {
313                 lfs.setRootDirectory(root);
314             } catch (PropertyVetoException JavaDoc e) {
315                 assert false : e;
316             }
317             Repository.getDefault().addFileSystem(lfs);
318             return lfs.getRoot();
319         }
320     }
321     
322     public static JavacTask getJavacTaskFor(CompilationInfo info) {
323         return info.getJavacTask();
324     }
325     
326     /** Blocking call for CompilationInfo after given phase is reached.
327      * @param phase to be reached
328      * @return CompilationInfo or null
329      * XXX: REMOVE ME!!!!!!!
330      */

331     public static CompilationInfo getCompilationInfo(JavaSource js, Phase phase ) throws IOException JavaDoc {
332         if (phase == null || phase == Phase.MODIFIED) {
333             throw new IllegalArgumentException JavaDoc (String.format("The %s is not a legal value of phase",phase)); //NOI18N
334
}
335         final DeadlockTask bt = new DeadlockTask(phase);
336         js.runUserActionTask(bt,true);
337         return bt.info;
338     }
339     
340     
341     private static class DeadlockTask implements CancellableTask<CompilationController> {
342         
343         private final Phase phase;
344         private CompilationInfo info;
345         
346         public DeadlockTask(Phase phase) {
347             assert phase != null;
348             this.phase = phase;
349         }
350         
351         public void run( CompilationController info ) {
352             try {
353                 info.toPhase(this.phase);
354                 this.info = info;
355             } catch (IOException JavaDoc ioe) {
356                 ErrorManager.getDefault().notify(ioe);
357             }
358         }
359         
360         public void cancel() {
361         }
362         
363     }
364     
365 }
366
Popular Tags