KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > modules > web > core > test > TestUtil


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

20
21 import java.beans.PropertyVetoException JavaDoc;
22 import java.io.BufferedInputStream JavaDoc;
23 import java.io.BufferedOutputStream JavaDoc;
24 import java.io.File JavaDoc;
25 import java.io.FileInputStream JavaDoc;
26 import java.io.FileOutputStream JavaDoc;
27 import java.io.IOException JavaDoc;
28 import java.io.InputStream JavaDoc;
29 import java.io.OutputStream JavaDoc;
30 import java.net.URL JavaDoc;
31 import java.util.ArrayList JavaDoc;
32 import java.util.List JavaDoc;
33 import java.util.Map JavaDoc;
34 import java.util.StringTokenizer JavaDoc;
35 import java.util.WeakHashMap JavaDoc;
36 import java.util.zip.ZipEntry JavaDoc;
37 import java.util.zip.ZipInputStream JavaDoc;
38 import junit.framework.Assert;
39 import org.netbeans.api.project.Project;
40 import org.netbeans.junit.NbTestCase;
41 import org.netbeans.modules.j2ee.deployment.impl.ServerRegistry;
42 import org.netbeans.modules.j2ee.deployment.plugins.api.InstanceProperties;
43 import org.netbeans.spi.project.ProjectFactory;
44 import org.netbeans.spi.project.ProjectState;
45 import org.netbeans.spi.project.support.ant.AntProjectHelper;
46 import org.netbeans.spi.project.support.ant.EditableProperties;
47 import org.openide.filesystems.FileLock;
48 import org.openide.filesystems.FileObject;
49 import org.openide.filesystems.FileSystem;
50 import org.openide.filesystems.FileUtil;
51 import org.openide.filesystems.LocalFileSystem;
52 import org.openide.filesystems.MultiFileSystem;
53 import org.openide.filesystems.Repository;
54 import org.openide.filesystems.URLMapper;
55 import org.openide.filesystems.XMLFileSystem;
56 import org.openide.modules.InstalledFileLocator;
57 import org.openide.util.Lookup;
58 import org.openide.util.lookup.Lookups;
59 import org.openide.util.lookup.ProxyLookup;
60 import org.xml.sax.SAXException JavaDoc;
61
62 /**
63  * Help set up org.netbeans.api.project.*Test.
64  * @author Jesse Glick
65  */

66 public final class TestUtil extends ProxyLookup {
67     
68     static {
69         TestUtil.class.getClassLoader().setDefaultAssertionStatus(true);
70         System.setProperty("org.openide.util.Lookup", TestUtil.class.getName());
71         Assert.assertEquals(TestUtil.class, Lookup.getDefault().getClass());
72     }
73     
74     private static TestUtil DEFAULT;
75     private static final int BUFFER = 2048;
76     
77     /** Do not call directly */
78     public TestUtil() {
79         Assert.assertNull(DEFAULT);
80         DEFAULT = this;
81         setLookup(new Object JavaDoc[0]);
82     }
83     
84     /**
85      * Set the global default lookup.
86      * Caution: if you don't include Lookups.metaInfServices, you may have trouble,
87      * e.g. {@link #makeScratchDir} will not work.
88      */

89     public static void setLookup(Lookup l) {
90         DEFAULT.setLookups(new Lookup[] {l});
91     }
92     
93     /**
94      * Set the global default lookup with some fixed instances including META-INF/services/*.
95      */

96     public static void setLookup(Object JavaDoc[] instances) {
97         ClassLoader JavaDoc l = TestUtil.class.getClassLoader();
98         DEFAULT.setLookups(new Lookup[] {
99             Lookups.fixed(instances),
100             Lookups.metaInfServices(l),
101             Lookups.singleton(l),
102         });
103     }
104     
105     private static boolean warned = false;
106     /**
107      * Create a scratch directory for tests.
108      * Will be in /tmp or whatever, and will be empty.
109      * If you just need a java.io.File use clearWorkDir + getWorkDir.
110      */

111     public static FileObject makeScratchDir(NbTestCase test) throws IOException JavaDoc {
112         test.clearWorkDir();
113         File JavaDoc root = test.getWorkDir();
114         assert root.isDirectory() && root.list().length == 0;
115         FileObject fo = FileUtil.toFileObject(root);
116         if (fo != null) {
117             return fo;
118         } else {
119             if (!warned) {
120                 warned = true;
121                 System.err.println("No FileObject for " + root + " found.\n" +
122                                     "Maybe you need ${openide/masterfs.dir}/modules/org-netbeans-modules-masterfs.jar\n" +
123                                     "in test.unit.run.cp.extra, or make sure Lookups.metaInfServices is included in Lookup.default, so that\n" +
124                                     "Lookup.default<URLMapper>=" + Lookup.getDefault().lookup(new Lookup.Template(URLMapper.class)).allInstances() + " includes MasterURLMapper\n" +
125                                     "e.g. by using TestUtil.setLookup(Object[]) rather than TestUtil.setLookup(Lookup).");
126             }
127             // For the benefit of those not using masterfs.
128
LocalFileSystem lfs = new LocalFileSystem();
129             try {
130                 lfs.setRootDirectory(root);
131             } catch (PropertyVetoException JavaDoc e) {
132                 assert false : e;
133             }
134             Repository.getDefault().addFileSystem(lfs);
135             return lfs.getRoot();
136         }
137     }
138     
139     /**
140      * Delete a file and all subfiles.
141      */

142     public static void deleteRec(File JavaDoc f) throws IOException JavaDoc {
143         if (f.isDirectory()) {
144             File JavaDoc[] kids = f.listFiles();
145             if (kids == null) {
146                 throw new IOException JavaDoc("List " + f);
147             }
148             for (int i = 0; i < kids.length; i++) {
149                 deleteRec(kids[i]);
150             }
151         }
152         if (!f.delete()) {
153             throw new IOException JavaDoc("Delete " + f);
154         }
155     }
156     
157     /**
158      * Create a testing project factory which recognizes directories containing
159      * a subdirectory called "testproject".
160      * If that subdirectory contains a file named "broken" then loading the project
161      * will fail with an IOException.
162      */

163     public static ProjectFactory testProjectFactory() {
164         return new TestProjectFactory();
165     }
166     
167     /**
168      * Try to force a GC.
169      */

170     public static void gc() {
171         System.gc();
172         System.runFinalization();
173         System.gc();
174     }
175     
176     private static final Map JavaDoc<FileObject,Integer JavaDoc> loadCount = new WeakHashMap JavaDoc();
177     
178     /**
179      * Check how many times {@link ProjectFactory#loadProject} has been called
180      * (with any outcome) on a given project directory.
181      */

182     public static int projectLoadCount(FileObject dir) {
183         Integer JavaDoc i = (Integer JavaDoc)loadCount.get(dir);
184         if (i != null) {
185             return i.intValue();
186         } else {
187             return 0;
188         }
189     }
190     
191     /**
192      * Mark a test project to fail with a given error when it is next saved.
193      * The error only applies to the next save, not subsequent ones.
194      * @param p a test project
195      * @param error an error to throw (IOException or Error or RuntimeException),
196      * or null if it should succeed
197      */

198     public static void setProjectSaveWillFail(Project p, Throwable JavaDoc error) {
199         ((TestProject)p).error = error;
200     }
201     
202     /**
203      * Get the number of times a test project was successfully saved with no error.
204      * @param p a test project
205      * @return the save count
206      */

207     public static int projectSaveCount(Project p) {
208         return ((TestProject)p).saveCount;
209     }
210     
211     /**
212      * Mark a test project as modified.
213      * @param p a test project
214      */

215     public static void modify(Project p) {
216         ((TestProject)p).state.markModified();
217     }
218     
219     /**
220      * Mark a test project as modified.
221      * @param p a test project
222      */

223     public static void notifyDeleted(Project p) {
224         ((TestProject)p).state.notifyDeleted();
225     }
226     
227     /**
228      * Register Sun Application Server in the "IDE" to be used by unit test.
229      * This method creates dummy userdir as well as dummy NetBeans home
230      * in test's working directory. Both properties - <code>netbeans.home</code>
231      * and <code>netbeans.user</code> - will be set by this method if they are
232      * not already defined.
233      *
234      * @param test a test which requires SunAppServer
235      * @return id of registered server
236      */

237     public static String JavaDoc registerSunAppServer(NbTestCase test) throws Exception JavaDoc {
238         return registerSunAppServer(test, new Object JavaDoc[0]);
239 }
240     
241     public static String JavaDoc registerSunAppServer(NbTestCase test, Object JavaDoc[] additionalLookupItems) throws Exception JavaDoc {
242         String JavaDoc oldNbHome = System.getProperty("netbeans.home"); // NOI18N
243
String JavaDoc oldNbUser = System.getProperty("netbeans.user"); // NOI18N
244
File JavaDoc root = test.getWorkDir();
245         File JavaDoc systemDir = new File JavaDoc(root, "ud/system"); // NOI18N
246
new File JavaDoc(systemDir, "J2EE/InstalledServers").mkdirs(); // NOI18N
247
new File JavaDoc(systemDir, "J2EE/DeploymentPlugins").mkdirs(); // NOI18N
248
new File JavaDoc(root, "nb").mkdirs(); // NOI18N
249
System.setProperty("netbeans.home", new File JavaDoc(test.getWorkDir(), "nb").getAbsolutePath()); // NOI18N
250
System.setProperty("netbeans.user", new File JavaDoc(test.getWorkDir(), "ud").getAbsolutePath()); // NOI18N
251

252         // lookup content
253
Object JavaDoc[] appServerNeed = new Object JavaDoc[] { new Repo(test), new IFL() };
254         Object JavaDoc[] instances = new Object JavaDoc[additionalLookupItems.length + appServerNeed.length];
255         System.arraycopy(additionalLookupItems, 0, instances, 0, additionalLookupItems.length);
256         System.arraycopy(appServerNeed, 0, instances, additionalLookupItems.length, appServerNeed.length);
257         TestUtil.setLookup(instances);
258         
259         File JavaDoc asRoot = null;
260         if (System.getProperty("appserv.home") != null) { // NOI18N
261
asRoot = new File JavaDoc(System.getProperty("appserv.home")); // NOI18N
262
} else {
263             asRoot = extractAppSrv(test.getWorkDir(), new File JavaDoc(test.getDataDir(), "SunAppServer.zip")); // NOI18N
264
}
265         FileObject dir = Repository.getDefault().getDefaultFileSystem().findResource("/J2EE/InstalledServers"); // NOI18N
266
String JavaDoc name = FileUtil.findFreeFileName(dir, "instance", null); // NOI18N
267
FileObject instanceFO = dir.createData(name);
268         String JavaDoc serverID = "[" + asRoot.getAbsolutePath() + "]deployer:Sun:AppServer::localhost:4848"; // NOI18N
269
instanceFO.setAttribute(InstanceProperties.URL_ATTR, serverID);
270         instanceFO.setAttribute(InstanceProperties.USERNAME_ATTR, "admin"); // NOI18N
271
instanceFO.setAttribute(InstanceProperties.PASSWORD_ATTR, "adminadmin"); // NOI18N
272
instanceFO.setAttribute(InstanceProperties.DISPLAY_NAME_ATTR, "testdname"); // NOI18N
273
instanceFO.setAttribute(InstanceProperties.HTTP_PORT_NUMBER, "4848"); // NOI18N
274
instanceFO.setAttribute("DOMAIN", "testdomain1"); // NOI18N
275
instanceFO.setAttribute("LOCATION", new File JavaDoc(asRoot, "domains").getAbsolutePath()); // NOI18N
276
ServerRegistry sr = ServerRegistry.getInstance();
277         sr.addInstance(instanceFO);
278         if (oldNbHome != null) {
279             System.setProperty("netbeans.home", oldNbHome); // NOI18N
280
}
281         if (oldNbUser != null) {
282             System.setProperty("netbeans.user", oldNbUser); // NOI18N
283
}
284         return serverID;
285     }
286
287     private static File JavaDoc extractAppSrv(File JavaDoc destDir, File JavaDoc archiveFile) throws IOException JavaDoc {
288         ZipInputStream JavaDoc zis = null;
289         BufferedOutputStream JavaDoc dest = null;
290         try {
291             FileInputStream JavaDoc fis = new FileInputStream JavaDoc(archiveFile);
292             zis = new ZipInputStream JavaDoc(new BufferedInputStream JavaDoc(fis));
293             ZipEntry JavaDoc entry;
294             while((entry = zis.getNextEntry()) != null) {
295                 byte data[] = new byte[BUFFER];
296                 File JavaDoc entryFile = new File JavaDoc(destDir, entry.getName());
297                 if (entry.isDirectory()) {
298                     entryFile.mkdirs();
299                 } else {
300                     entryFile.getParentFile().mkdirs();
301                     FileOutputStream JavaDoc fos = new FileOutputStream JavaDoc(entryFile);
302                     dest = new BufferedOutputStream JavaDoc(fos, BUFFER);
303                     int count;
304                     while ((count = zis.read(data, 0, BUFFER)) != -1) {
305                         dest.write(data, 0, count);
306                     }
307                     dest.flush();
308                 }
309             }
310         } finally {
311             if (zis != null) { zis.close(); }
312             if (dest != null) { dest.close(); }
313         }
314         return new File JavaDoc(destDir, archiveFile.getName().substring(0, archiveFile.getName().length() - 4));
315     }
316
317     public static EditableProperties loadProjectProperties(
318             final FileObject projectDir) throws IOException JavaDoc {
319         FileObject propsFO = projectDir.getFileObject(AntProjectHelper.PROJECT_PROPERTIES_PATH);
320         InputStream JavaDoc propsIS = propsFO.getInputStream();
321         EditableProperties props = new EditableProperties(true);
322         try {
323             props.load(propsIS);
324         } finally {
325             propsIS.close();
326         }
327         return props;
328     }
329     
330     public static void storeProjectProperties(FileObject projectDir, EditableProperties props) throws IOException JavaDoc {
331         FileObject propsFO = projectDir.getFileObject(AntProjectHelper.PROJECT_PROPERTIES_PATH);
332         FileLock lock = propsFO.lock();
333         try {
334             OutputStream JavaDoc os = propsFO.getOutputStream(lock);
335             try {
336                 props.store(os);
337             } finally {
338                 os.close();
339             }
340         } finally {
341             lock.releaseLock();
342         }
343     }
344     
345     /**
346      * If set to something non-null, loading a broken project will wait for
347      * notification on this monitor before throwing an exception.
348      * @see ProjectManagerTest#testLoadExceptionWithConcurrentLoad
349      */

350     public static Object JavaDoc BROKEN_PROJECT_LOAD_LOCK = null;
351     
352     private static final class TestProjectFactory implements ProjectFactory {
353         
354         TestProjectFactory() {}
355         
356         public Project loadProject(FileObject projectDirectory, ProjectState state) throws IOException JavaDoc {
357             Integer JavaDoc i = loadCount.get(projectDirectory);
358             if (i == null) {
359                 i = 1;
360             } else {
361                 i++;
362             }
363             loadCount.put(projectDirectory, i);
364             FileObject testproject = projectDirectory.getFileObject("testproject");
365             if (testproject != null && testproject.isFolder()) {
366                 if (testproject.getFileObject("broken") != null) {
367                     if (BROKEN_PROJECT_LOAD_LOCK != null) {
368                         synchronized (BROKEN_PROJECT_LOAD_LOCK) {
369                             try {
370                                 BROKEN_PROJECT_LOAD_LOCK.wait();
371                             } catch (InterruptedException JavaDoc e) {
372                                 assert false : e;
373                             }
374                         }
375                     }
376                     throw new IOException JavaDoc("Load failed of " + projectDirectory);
377                 } else {
378                     return new TestProject(projectDirectory, state);
379                 }
380             } else {
381                 return null;
382             }
383         }
384         
385         public void saveProject(Project project) throws IOException JavaDoc, ClassCastException JavaDoc {
386             TestProject p = (TestProject)project;
387             Throwable JavaDoc t = p.error;
388             if (t != null) {
389                 p.error = null;
390                 if (t instanceof IOException JavaDoc) {
391                     throw (IOException JavaDoc)t;
392                 } else if (t instanceof Error JavaDoc) {
393                     throw (Error JavaDoc)t;
394                 } else {
395                     throw (RuntimeException JavaDoc)t;
396                 }
397             }
398             p.saveCount++;
399         }
400         
401         public boolean isProject(FileObject dir) {
402             FileObject testproject = dir.getFileObject("testproject");
403             return testproject != null && testproject.isFolder();
404         }
405         
406     }
407     
408     private static final class TestProject implements Project {
409         
410         private final FileObject dir;
411         final ProjectState state;
412         Throwable JavaDoc error;
413         int saveCount = 0;
414         
415         public TestProject(FileObject dir, ProjectState state) {
416             this.dir = dir;
417             this.state = state;
418         }
419         
420         public Lookup getLookup() {
421             return Lookup.EMPTY;
422         }
423         
424         public FileObject getProjectDirectory() {
425             return dir;
426         }
427         
428         public String JavaDoc toString() {
429             return "testproject:" + getProjectDirectory().getNameExt();
430         }
431
432         /* Probably unnecessary to have a ProjectInformation here:
433         public String getName() {
434             return "testproject:" + getProjectDirectory().getNameExt();
435         }
436         
437         public String getDisplayName() {
438             return "Test Project in " + getProjectDirectory().getNameExt();
439         }
440         
441         public Image getIcon() {
442             return null;
443         }
444         
445         public void addPropertyChangeListener(PropertyChangeListener listener) {}
446         public void removePropertyChangeListener(PropertyChangeListener listener) {}
447          */

448         
449     }
450     
451     /**
452      * Open a URL of content (for example from {@link Class#getResource}) and copy it to a named file.
453      * The new file can be given as a parent directory plus a relative (slash-separated) path.
454      * The file may not already exist, but intermediate directories may or may not.
455      * If the content URL is null, the file is just created, no more; if it already existed
456      * it is touched (timestamp updated) and its contents are cleared.
457      * @return the file object
458      */

459     public static FileObject createFileFromContent(URL JavaDoc content, FileObject parent, String JavaDoc path) throws IOException JavaDoc {
460         if (parent == null) {
461             throw new IllegalArgumentException JavaDoc("null parent");
462         }
463         Assert.assertTrue("folder", parent.isFolder());
464         FileObject fo = parent;
465         StringTokenizer JavaDoc tok = new StringTokenizer JavaDoc(path, "/");
466         boolean touch = false;
467         while (tok.hasMoreTokens()) {
468             Assert.assertNotNull("fo is null (parent=" + parent + " path=" + path + ")", fo);
469             String JavaDoc name = tok.nextToken();
470             if (tok.hasMoreTokens()) {
471                 FileObject sub = fo.getFileObject(name);
472                 if (sub == null) {
473                     FileObject fo2 = fo.createFolder(name);
474                     Assert.assertNotNull("createFolder(" + fo + ", " + name + ") -> null", fo2);
475                     fo = fo2;
476                 } else {
477                     Assert.assertTrue("folder", sub.isFolder());
478                     fo = sub;
479                 }
480             } else {
481                 FileObject sub = fo.getFileObject(name);
482                 if (sub == null) {
483                     FileObject fo2 = fo.createData(name);
484                     Assert.assertNotNull("createData(" + fo + ", " + name + ") -> null", fo2);
485                     fo = fo2;
486                 } else {
487                     fo = sub;
488                     touch = true;
489                 }
490             }
491         }
492         assert fo.isData();
493         if (content != null || touch) {
494             FileLock lock = fo.lock();
495             try {
496                 OutputStream JavaDoc os = fo.getOutputStream(lock);
497                 try {
498                     if (content != null) {
499                         InputStream JavaDoc is = content.openStream();
500                         try {
501                             FileUtil.copy(is, os);
502                         } finally {
503                             is.close();
504                         }
505                     }
506                 } finally {
507                     os.close();
508                 }
509             } finally {
510                 lock.releaseLock();
511             }
512         }
513         return fo;
514     }
515     
516     private static final class Repo extends Repository {
517         
518         public Repo(NbTestCase t) throws Exception JavaDoc {
519             super(mksystem(t));
520         }
521         
522         private static FileSystem mksystem(NbTestCase t) throws Exception JavaDoc {
523             LocalFileSystem lfs = new LocalFileSystem();
524             File JavaDoc systemDir = new File JavaDoc(t.getWorkDir(), "ud/system");
525             systemDir.mkdirs();
526             lfs.setRootDirectory(systemDir);
527             lfs.setReadOnly(false);
528             List JavaDoc<FileSystem> layers = new ArrayList JavaDoc<FileSystem>();
529             layers.add(lfs);
530             /*
531             //get layer for the generic server
532             java.net.URL layerFile = Repo.class.getClassLoader().getResource("org/netbeans/modules/j2ee/genericserver/resources/layer.xml");
533             assert layerFile != null;
534             layers.add(new XMLFileSystem(layerFile));
535              */

536             
537             // get layer for the AS/GlassFish
538
// addLayer(layers, "org/netbeans/modules/j2ee/sun/ide/j2ee/layer.xml");
539
// addLayer(layers, "org/netbeans/modules/tomcat5/resources/layer.xml");
540
MultiFileSystem mfs = new MultiFileSystem((FileSystem[]) layers.toArray(new FileSystem[layers.size()]));
541             return mfs;
542         }
543         
544         private static void addLayer(List JavaDoc<FileSystem> layers, String JavaDoc layerRes) throws SAXException JavaDoc {
545             URL JavaDoc layerFile = Repo.class.getClassLoader().getResource(layerRes);
546             assert layerFile != null;
547             layers.add(new XMLFileSystem(layerFile));
548         }
549         
550     }
551     
552     /** Copied from AntLoggerTest. */
553     private static final class IFL extends InstalledFileLocator {
554         
555         public IFL() {}
556         
557         public File JavaDoc locate(String JavaDoc relativePath, String JavaDoc codeNameBase, boolean localized) {
558             if (relativePath.equals("modules/ext/appsrvbridge.jar")) {
559                 String JavaDoc path = System.getProperty("test.appsrvbridge.jar");
560                 Assert.assertNotNull("must set test.appsrvbridge.jar", path);
561                 return new File JavaDoc(path);
562             }
563             return null;
564         }
565     }
566     
567 }
568
Popular Tags