KickJava   Java API By Example, From Geeks To Geeks.

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

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

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

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

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

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

169     public static ProjectFactory testProjectFactory() {
170         return new TestProjectFactory();
171     }
172     
173     /**
174      * Try to force a GC.
175      */

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

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

204     public static void setProjectSaveWillFail(Project p, Throwable JavaDoc error) {
205         ((TestProject)p).error = error;
206     }
207     
208     /**
209      * Get the number of times a test project was successfully saved with no error.
210      * @param p a test project
211      * @return the save count
212      */

213     public static int projectSaveCount(Project p) {
214         return ((TestProject)p).saveCount;
215     }
216     
217     /**
218      * Mark a test project as modified.
219      * @param p a test project
220      */

221     public static void modify(Project p) {
222         ((TestProject)p).state.markModified();
223     }
224     
225     /**
226      * Mark a test project as modified.
227      * @param p a test project
228      */

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

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

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

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

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

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

542             // get layer for the AS/GlassFish
543
addLayer(layers, "org/netbeans/modules/j2ee/sun/ide/j2ee/layer.xml");
544             addLayer(layers, "org/netbeans/modules/j2ee/earproject/ui/resources/layer.xml");
545             // needed for ejb-related tests
546
addLayer(layers, "org/netbeans/modules/j2ee/ejbjarproject/ui/resources/layer.xml");
547             // needed for appclient-related tests
548
addLayer(layers, "org/netbeans/modules/j2ee/clientproject/ui/resources/layer.xml");
549             // needed for webmodule-related tests
550
addLayer(layers, "org/netbeans/modules/web/project/ui/resources/layer.xml");
551             MultiFileSystem mfs = new MultiFileSystem((FileSystem[]) layers.toArray(new FileSystem[layers.size()]));
552             return mfs;
553         }
554         
555         private static void addLayer(List JavaDoc<FileSystem> layers, String JavaDoc layerRes) throws SAXException JavaDoc {
556             URL JavaDoc layerFile = Repo.class.getClassLoader().getResource(layerRes);
557             assert layerFile != null;
558             layers.add(new XMLFileSystem(layerFile));
559         }
560         
561     }
562     
563     /** Copied from AntLoggerTest. */
564     private static final class IFL extends InstalledFileLocator {
565         
566         public IFL() {}
567         
568         public File JavaDoc locate(String JavaDoc relativePath, String JavaDoc codeNameBase, boolean localized) {
569             if (relativePath.equals("modules/ext/appsrvbridge.jar")) {
570                 String JavaDoc path = System.getProperty("test.appsrvbridge.jar");
571                 Assert.assertNotNull("must set test.appsrvbridge.jar", path);
572                 return new File JavaDoc(path);
573             }
574             return null;
575         }
576     }
577     
578 }
579
Popular Tags