KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > modules > j2ee > ejbjarproject > test > TestUtil


1 /*
2  * The contents of this file are subject to the terms of the Common Development
3  * and Distribution License (the License). You may not use this file except in
4  * compliance with the License.
5  *
6  * You can obtain a copy of the License at http://www.netbeans.org/cddl.html
7  * or http://www.netbeans.org/cddl.txt.
8  *
9  * When distributing Covered Code, include this CDDL Header Notice in each file
10  * and include the License file at http://www.netbeans.org/cddl.txt.
11  * If applicable, add the following below the CDDL Header, with the fields
12  * enclosed by brackets [] replaced by your own identifying information:
13  * "Portions Copyrighted [year] [name of copyright owner]"
14  *
15  * The Original Software is NetBeans. The Initial Developer of the Original
16  * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
17  * Microsystems, Inc. All Rights Reserved.
18  */

19
20 package org.netbeans.modules.j2ee.ejbjarproject.test;
21
22 import java.beans.PropertyVetoException JavaDoc;
23 import java.io.File JavaDoc;
24 import java.io.IOException JavaDoc;
25 import java.io.InputStream JavaDoc;
26 import java.io.OutputStream JavaDoc;
27 import java.net.URL JavaDoc;
28 import java.util.Map JavaDoc;
29 import java.util.StringTokenizer JavaDoc;
30 import java.util.WeakHashMap JavaDoc;
31 import junit.framework.Assert;
32 import org.netbeans.api.project.Project;
33 import org.netbeans.junit.NbTestCase;
34 import org.netbeans.spi.project.ProjectFactory;
35 import org.netbeans.spi.project.ProjectState;
36 import org.openide.filesystems.FileLock;
37 import org.openide.filesystems.FileObject;
38 import org.openide.filesystems.FileUtil;
39 import org.openide.filesystems.LocalFileSystem;
40 import org.openide.filesystems.Repository;
41 import org.openide.filesystems.URLMapper;
42 import org.openide.util.Lookup;
43 import org.openide.util.lookup.Lookups;
44 import org.openide.util.lookup.ProxyLookup;
45
46 /**
47  * Help set up org.netbeans.api.project.*Test.
48  * @author Jesse Glick
49  */

50 public final class TestUtil extends ProxyLookup {
51     
52     static {
53         TestUtil.class.getClassLoader().setDefaultAssertionStatus(true);
54         System.setProperty("org.openide.util.Lookup", TestUtil.class.getName());
55         Assert.assertEquals(TestUtil.class, Lookup.getDefault().getClass());
56     }
57     
58     private static TestUtil DEFAULT;
59     /** Do not call directly */
60     public TestUtil() {
61         Assert.assertNull(DEFAULT);
62         DEFAULT = this;
63         setLookup(new Object JavaDoc[0]);
64     }
65     
66     /**
67      * Set the global default lookup.
68      * Caution: if you don't include Lookups.metaInfServices, you may have trouble,
69      * e.g. {@link #makeScratchDir} will not work.
70      */

71     public static void setLookup(Lookup l) {
72         DEFAULT.setLookups(new Lookup[] {l});
73     }
74     
75     /**
76      * Set the global default lookup with some fixed instances including META-INF/services/*.
77      */

78     public static void setLookup(Object JavaDoc[] instances) {
79         ClassLoader JavaDoc l = TestUtil.class.getClassLoader();
80         DEFAULT.setLookups(new Lookup[] {
81             Lookups.fixed(instances),
82             Lookups.metaInfServices(l),
83             Lookups.singleton(l),
84         });
85     }
86     
87     private static boolean warned = false;
88     /**
89      * Create a scratch directory for tests.
90      * Will be in /tmp or whatever, and will be empty.
91      * If you just need a java.io.File use clearWorkDir + getWorkDir.
92      */

93     public static FileObject makeScratchDir(NbTestCase test) throws IOException JavaDoc {
94         test.clearWorkDir();
95         File JavaDoc root = test.getWorkDir();
96         assert root.isDirectory() && root.list().length == 0;
97         FileObject fo = FileUtil.toFileObject(root);
98         if (fo != null) {
99             return fo;
100         } else {
101             if (!warned) {
102                 warned = true;
103                 System.err.println("No FileObject for " + root + " found.\n" +
104                                     "Maybe you need ${openide/masterfs.dir}/modules/org-netbeans-modules-masterfs.jar\n" +
105                                     "in test.unit.run.cp.extra, or make sure Lookups.metaInfServices is included in Lookup.default, so that\n" +
106                                     "Lookup.default<URLMapper>=" + Lookup.getDefault().lookup(new Lookup.Template(URLMapper.class)).allInstances() + " includes MasterURLMapper\n" +
107                                     "e.g. by using TestUtil.setLookup(Object[]) rather than TestUtil.setLookup(Lookup).");
108             }
109             // For the benefit of those not using masterfs.
110
LocalFileSystem lfs = new LocalFileSystem();
111             try {
112                 lfs.setRootDirectory(root);
113             } catch (PropertyVetoException JavaDoc e) {
114                 assert false : e;
115             }
116             Repository.getDefault().addFileSystem(lfs);
117             return lfs.getRoot();
118         }
119     }
120     
121     /**
122      * Delete a file and all subfiles.
123      */

124     public static void deleteRec(File JavaDoc f) throws IOException JavaDoc {
125         if (f.isDirectory()) {
126             File JavaDoc[] kids = f.listFiles();
127             if (kids == null) {
128                 throw new IOException JavaDoc("List " + f);
129             }
130             for (int i = 0; i < kids.length; i++) {
131                 deleteRec(kids[i]);
132             }
133         }
134         if (!f.delete()) {
135             throw new IOException JavaDoc("Delete " + f);
136         }
137     }
138     
139     /**
140      * Create a testing project factory which recognizes directories containing
141      * a subdirectory called "testproject".
142      * If that subdirectory contains a file named "broken" then loading the project
143      * will fail with an IOException.
144      */

145     public static ProjectFactory testProjectFactory() {
146         return new TestProjectFactory();
147     }
148     
149     /**
150      * Try to force a GC.
151      */

152     public static void gc() {
153         System.gc();
154         System.runFinalization();
155         System.gc();
156     }
157     
158     private static final Map JavaDoc/*<FileObject,int>*/ loadCount = new WeakHashMap JavaDoc();
159     
160     /**
161      * Check how many times {@link ProjectFactory#loadProject} has been called
162      * (with any outcome) on a given project directory.
163      */

164     public static int projectLoadCount(FileObject dir) {
165         Integer JavaDoc i = (Integer JavaDoc)loadCount.get(dir);
166         if (i != null) {
167             return i.intValue();
168         } else {
169             return 0;
170         }
171     }
172     
173     /**
174      * Mark a test project to fail with a given error when it is next saved.
175      * The error only applies to the next save, not subsequent ones.
176      * @param p a test project
177      * @param error an error to throw (IOException or Error or RuntimeException),
178      * or null if it should succeed
179      */

180     public static void setProjectSaveWillFail(Project p, Throwable JavaDoc error) {
181         ((TestProject)p).error = error;
182     }
183     
184     /**
185      * Get the number of times a test project was successfully saved with no error.
186      * @param p a test project
187      * @return the save count
188      */

189     public static int projectSaveCount(Project p) {
190         return ((TestProject)p).saveCount;
191     }
192     
193     /**
194      * Mark a test project as modified.
195      * @param p a test project
196      */

197     public static void modify(Project p) {
198         ((TestProject)p).state.markModified();
199     }
200     
201     /**
202      * Mark a test project as modified.
203      * @param p a test project
204      */

205     public static void notifyDeleted(Project p) {
206         ((TestProject)p).state.notifyDeleted();
207     }
208     
209     /**
210      * If set to something non-null, loading a broken project will wait for
211      * notification on this monitor before throwing an exception.
212      * @see ProjectManagerTest#testLoadExceptionWithConcurrentLoad
213      */

214     public static Object JavaDoc BROKEN_PROJECT_LOAD_LOCK = null;
215     
216     private static final class TestProjectFactory implements ProjectFactory {
217         
218         TestProjectFactory() {}
219         
220         public Project loadProject(FileObject projectDirectory, ProjectState state) throws IOException JavaDoc {
221             Integer JavaDoc i = (Integer JavaDoc)loadCount.get(projectDirectory);
222             if (i == null) {
223                 i = new Integer JavaDoc(1);
224             } else {
225                 i = new Integer JavaDoc(i.intValue() + 1);
226             }
227             loadCount.put(projectDirectory, i);
228             FileObject testproject = projectDirectory.getFileObject("testproject");
229             if (testproject != null && testproject.isFolder()) {
230                 if (testproject.getFileObject("broken") != null) {
231                     if (BROKEN_PROJECT_LOAD_LOCK != null) {
232                         synchronized (BROKEN_PROJECT_LOAD_LOCK) {
233                             try {
234                                 BROKEN_PROJECT_LOAD_LOCK.wait();
235                             } catch (InterruptedException JavaDoc e) {
236                                 assert false : e;
237                             }
238                         }
239                     }
240                     throw new IOException JavaDoc("Load failed of " + projectDirectory);
241                 } else {
242                     return new TestProject(projectDirectory, state);
243                 }
244             } else {
245                 return null;
246             }
247         }
248         
249         public void saveProject(Project project) throws IOException JavaDoc, ClassCastException JavaDoc {
250             TestProject p = (TestProject)project;
251             Throwable JavaDoc t = p.error;
252             if (t != null) {
253                 p.error = null;
254                 if (t instanceof IOException JavaDoc) {
255                     throw (IOException JavaDoc)t;
256                 } else if (t instanceof Error JavaDoc) {
257                     throw (Error JavaDoc)t;
258                 } else {
259                     throw (RuntimeException JavaDoc)t;
260                 }
261             }
262             p.saveCount++;
263         }
264         
265         public boolean isProject(FileObject dir) {
266             FileObject testproject = dir.getFileObject("testproject");
267             return testproject != null && testproject.isFolder();
268         }
269         
270     }
271     
272     private static final class TestProject implements Project {
273         
274         private final FileObject dir;
275         final ProjectState state;
276         Throwable JavaDoc error;
277         int saveCount = 0;
278         
279         public TestProject(FileObject dir, ProjectState state) {
280             this.dir = dir;
281             this.state = state;
282         }
283         
284         public Lookup getLookup() {
285             return Lookup.EMPTY;
286         }
287         
288         public FileObject getProjectDirectory() {
289             return dir;
290         }
291         
292         public String JavaDoc toString() {
293             return "testproject:" + getProjectDirectory().getNameExt();
294         }
295
296         /* Probably unnecessary to have a ProjectInformation here:
297         public String getName() {
298             return "testproject:" + getProjectDirectory().getNameExt();
299         }
300         
301         public String getDisplayName() {
302             return "Test Project in " + getProjectDirectory().getNameExt();
303         }
304         
305         public Image getIcon() {
306             return null;
307         }
308         
309         public void addPropertyChangeListener(PropertyChangeListener listener) {}
310         public void removePropertyChangeListener(PropertyChangeListener listener) {}
311          */

312         
313     }
314     
315     /**
316      * Open a URL of content (for example from {@link Class#getResource}) and copy it to a named file.
317      * The new file can be given as a parent directory plus a relative (slash-separated) path.
318      * The file may not already exist, but intermediate directories may or may not.
319      * If the content URL is null, the file is just created, no more; if it already existed
320      * it is touched (timestamp updated) and its contents are cleared.
321      * @return the file object
322      */

323     public static FileObject createFileFromContent(URL JavaDoc content, FileObject parent, String JavaDoc path) throws IOException JavaDoc {
324         if (parent == null) {
325             throw new IllegalArgumentException JavaDoc("null parent");
326         }
327         Assert.assertTrue("folder", parent.isFolder());
328         FileObject fo = parent;
329         StringTokenizer JavaDoc tok = new StringTokenizer JavaDoc(path, "/");
330         boolean touch = false;
331         while (tok.hasMoreTokens()) {
332             Assert.assertNotNull("fo is null (parent=" + parent + " path=" + path + ")", fo);
333             String JavaDoc name = tok.nextToken();
334             if (tok.hasMoreTokens()) {
335                 FileObject sub = fo.getFileObject(name);
336                 if (sub == null) {
337                     FileObject fo2 = fo.createFolder(name);
338                     Assert.assertNotNull("createFolder(" + fo + ", " + name + ") -> null", fo2);
339                     fo = fo2;
340                 } else {
341                     Assert.assertTrue("folder", sub.isFolder());
342                     fo = sub;
343                 }
344             } else {
345                 FileObject sub = fo.getFileObject(name);
346                 if (sub == null) {
347                     FileObject fo2 = fo.createData(name);
348                     Assert.assertNotNull("createData(" + fo + ", " + name + ") -> null", fo2);
349                     fo = fo2;
350                 } else {
351                     fo = sub;
352                     touch = true;
353                 }
354             }
355         }
356         assert fo.isData();
357         if (content != null || touch) {
358             FileLock lock = fo.lock();
359             try {
360                 OutputStream JavaDoc os = fo.getOutputStream(lock);
361                 try {
362                     if (content != null) {
363                         InputStream JavaDoc is = content.openStream();
364                         try {
365                             FileUtil.copy(is, os);
366                         } finally {
367                             is.close();
368                         }
369                     }
370                 } finally {
371                     os.close();
372                 }
373             } finally {
374                 lock.releaseLock();
375             }
376         }
377         return fo;
378     }
379     
380 }
381
Popular Tags