KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > modules > apisupport > project > TestBase


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.apisupport.project;
21
22 import java.beans.PropertyChangeEvent JavaDoc;
23 import java.beans.PropertyChangeListener JavaDoc;
24 import java.io.ByteArrayOutputStream 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.io.OutputStreamWriter JavaDoc;
32 import java.io.Writer JavaDoc;
33 import java.util.Collections JavaDoc;
34 import java.util.HashMap JavaDoc;
35 import java.util.HashSet JavaDoc;
36 import java.util.Iterator JavaDoc;
37 import java.util.Map JavaDoc;
38 import java.util.Properties JavaDoc;
39 import java.util.Set JavaDoc;
40 import java.util.jar.JarEntry JavaDoc;
41 import java.util.jar.JarOutputStream JavaDoc;
42 import java.util.jar.Manifest JavaDoc;
43 import java.util.zip.CRC32 JavaDoc;
44 import org.netbeans.api.project.ProjectManager;
45 import org.netbeans.junit.NbTestCase;
46 import org.netbeans.modules.apisupport.project.suite.SuiteProject;
47 import org.netbeans.modules.apisupport.project.suite.SuiteProjectGenerator;
48 import org.openide.filesystems.FileObject;
49 import org.openide.filesystems.FileUtil;
50 import org.netbeans.modules.apisupport.project.universe.NbPlatform;
51 import org.openide.filesystems.FileLock;
52 import org.openide.modules.ModuleInfo;
53 import org.openide.util.Lookup;
54
55 /**
56  * Basic setup for all the tests.
57  *
58  * @author Jesse Glick, Martin Krauskopf
59  */

60   public abstract class TestBase extends NbTestCase {
61
62     public static final String JavaDoc CLUSTER_IDE = "ide8";
63     public static final String JavaDoc CLUSTER_PLATFORM = "platform7";
64     public static final String JavaDoc CLUSTER_ENTERPRISE = "enterprise4";
65     
66     protected TestBase(String JavaDoc name) {
67         super(name);
68     }
69     
70     private static String JavaDoc EEP = "example-external-projects";
71     
72     /**
73      * Tells whether NB CVS tree is available (which is not the case with e.g.
74      * within binary distribution).
75      */

76     private boolean cvsAvailable;
77     
78     /** Represents netbeans.org CVS tree this test is run in if {@link #cvsAvailable}. */
79     private File JavaDoc nbcvsrootF;
80     
81     /** Represents netbeans.org CVS tree this test is run in if {@link #cvsAvailable}. */
82     private FileObject nbcvsroot;
83     
84     /** Represents destination directory with NetBeans (always available). */
85     protected File JavaDoc destDirF;
86     
87     protected File JavaDoc apisZip;
88     
89     /** sample projects doesn't have datadir
90      */

91     protected static boolean noDataDir = false;
92     
93     protected void setUp() throws Exception JavaDoc {
94         super.setUp();
95         Lookup.getDefault().lookup(ModuleInfo.class);
96         cvsAvailable = isCVSAvailable();
97         if (cvsAvailable) {
98             nbcvsrootF = FileUtil.normalizeFile(getTestNBRoot());
99             nbcvsroot = FileUtil.toFileObject(nbcvsrootF);
100             assertNotNull("have a file object for nbcvsroot when using " + System.getProperty("java.class.path"), nbcvsroot);
101             destDirF = file(nbcvsrootF, "nbbuild/netbeans").getAbsoluteFile();
102             File JavaDoc extexamplesF = file(getDataDir(), EEP);
103             if (!noDataDir) {
104                 assertTrue("there is a dir " + extexamplesF, extexamplesF.isDirectory());
105                 assertNotNull("have a file object for extexamples", FileUtil.toFileObject(extexamplesF));
106             }
107         } else {
108             destDirF = getXTestNBDestDir();
109         }
110
111         assertTrue("Directory really exists: " + destDirF, destDirF.isDirectory());
112         
113         // Need to set up private locations in extexamples, as if they were opened in the IDE.
114
clearWorkDir();
115         
116         ErrorManagerImpl.registerCase(this);
117         
118         // Nonexistent path, just for JavadocForBuiltModuleTest:
119
apisZip = new File JavaDoc(getWorkDir(), "apis.zip");
120         File JavaDoc userPropertiesFile = initializeBuildProperties(getWorkDir(), getDataDir(), apisZip,noDataDir);
121         String JavaDoc[] suites = {
122             // Suite projects:
123
"suite1",
124             "suite2",
125             "suite4",
126             // Standalone module projects:
127
"suite3/dummy-project",
128         };
129         if (!noDataDir) {
130             for (int i = 0; i < suites.length; i++) {
131                 File JavaDoc platformPrivate = resolveEEPFile(suites[i] + "/nbproject/private/platform-private.properties");
132                 Properties JavaDoc p = new Properties JavaDoc();
133                 p.setProperty("user.properties.file", userPropertiesFile.getAbsolutePath());
134                 platformPrivate.getParentFile().mkdirs();
135                 OutputStream JavaDoc os = new FileOutputStream JavaDoc(platformPrivate);
136                 try {
137                     p.store(os, null);
138                 } finally {
139                     os.close();
140                 }
141             }
142         }
143         NbPlatform.reset();
144     }
145     
146     protected void tearDown() throws Exception JavaDoc {
147         super.tearDown();
148         ErrorManagerImpl.registerCase(null);
149     }
150     
151     /**
152      * Sets up global build.properties for the default platform.
153      * For {@link PropertyUtils#userBuildProperties()}.
154      * Called automatically by {@link #setUp}.
155      * @param workDir use getWorkDir()
156      * @return resulting properties file
157      */

158     public static File JavaDoc initializeBuildProperties(File JavaDoc workDir, File JavaDoc dataDir) throws Exception JavaDoc {
159         return initializeBuildProperties(workDir, dataDir, null,noDataDir);
160     }
161     
162     private static File JavaDoc initializeBuildProperties(File JavaDoc workDir, File JavaDoc dataDir, File JavaDoc apisZip,boolean noDataDir) throws Exception JavaDoc {
163         File JavaDoc nbcvsrootF = getTestNBRoot();
164         boolean cvsAvailable = isCVSAvailable();
165         System.setProperty("netbeans.user", workDir.getAbsolutePath());
166         File JavaDoc userPropertiesFile = new File JavaDoc(workDir, "build.properties");
167         Properties JavaDoc p = new Properties JavaDoc();
168         File JavaDoc defaultPlatform = cvsAvailable ? file(nbcvsrootF, "nbbuild/netbeans") : getXTestNBDestDir();
169         assertTrue("default platform available (" + defaultPlatform + ')', defaultPlatform.isDirectory());
170         p.setProperty("nbplatform.default.netbeans.dest.dir", defaultPlatform.getAbsolutePath());
171         p.setProperty("nbplatform.default.harness.dir", "${nbplatform.default.netbeans.dest.dir}/harness");
172         if (!noDataDir) {
173             File JavaDoc customPlatform = file(file(dataDir, EEP), "/suite3/nbplatform");
174             assertTrue("custom platform available (" + customPlatform + ')', customPlatform.isDirectory());
175             p.setProperty("nbplatform.custom.netbeans.dest.dir", customPlatform.getAbsolutePath());
176             if (apisZip != null) {
177                 p.setProperty("nbplatform.default.javadoc", apisZip.getAbsolutePath());
178             }
179             if (cvsAvailable) {
180                 // Make source association work to find misc-project from its binary:
181
p.setProperty("nbplatform.default.sources", nbcvsrootF.getAbsolutePath() + ":" + file(file(dataDir, EEP), "/suite2").getAbsolutePath());
182             }
183         }
184         OutputStream JavaDoc os = new FileOutputStream JavaDoc(userPropertiesFile);
185         try {
186             p.store(os, null);
187         } finally {
188             os.close();
189         }
190         
191         return userPropertiesFile;
192     }
193     
194     /**
195      * Just calls <code>File(root, path.replace('/', File.separatorChar));</code>
196      */

197     protected static File JavaDoc file(File JavaDoc root, String JavaDoc path) {
198         return new File JavaDoc(root, path.replace('/', File.separatorChar));
199     }
200     
201     private static boolean isCVSAvailable() {
202         return new File JavaDoc(getTestNBRoot(), "nbbuild/netbeans/" + CLUSTER_IDE
203                 + "/modules/org-netbeans-modules-apisupport-project.jar").isFile();
204     }
205     
206     protected File JavaDoc nbCVSRootFile() {
207         assertTrue("NB CVS tree is available", cvsAvailable);
208         return nbcvsrootF;
209     }
210     
211     protected FileObject nbCVSRoot() {
212         assertTrue("NB CVS tree is available", cvsAvailable);
213         return nbcvsroot;
214     }
215     
216     protected File JavaDoc resolveEEPFile(final String JavaDoc relativePath) {
217         File JavaDoc eepF = FileUtil.normalizeFile(new File JavaDoc(getDataDir(), EEP));
218         assertTrue("has EEP directory (" + eepF + ')', eepF.isDirectory());
219         File JavaDoc eepRelF = new File JavaDoc(eepF, relativePath);
220 // assertTrue("resolved file exists (" + eepRelF + ')', eepRelF.exists());
221
return eepRelF;
222     }
223     
224     protected String JavaDoc resolveEEPPath(final String JavaDoc relativePath) {
225         return resolveEEPFile(relativePath).getAbsolutePath();
226     }
227     
228     protected FileObject resolveEEP(final String JavaDoc relativePath) {
229         return FileUtil.toFileObject(resolveEEPFile(relativePath));
230     }
231     
232     /**
233      * Calls in turn {@link #file(File, String)} with {@link #nbcvsrootF} as the
234      * first parameter. So the returned path will be actually relative to the
235      * netbeans.org CVS tree this test is run in.
236      */

237     protected File JavaDoc file(String JavaDoc path) {
238         return file(nbcvsrootF, path);
239     }
240     
241     /**
242      * Make a temporary copy of a whole folder into some new dir in the scratch area.
243      * Stolen from ant/freeform.
244      */

245     protected File JavaDoc copyFolder(File JavaDoc d) throws IOException JavaDoc {
246         assert d.isDirectory();
247         File JavaDoc workdir = getWorkDir();
248         String JavaDoc name = d.getName();
249         while (name.length() < 3) {
250             name = name + "x";
251         }
252         File JavaDoc todir = workdir.createTempFile(name, null, workdir);
253         todir.delete();
254         doCopy(d, todir);
255         return todir;
256     }
257     
258     private static void doCopy(File JavaDoc from, File JavaDoc to) throws IOException JavaDoc {
259         if (from.isDirectory()) {
260             if (from.getName().equals("CVS")) {
261                 return;
262             }
263             to.mkdir();
264             String JavaDoc[] kids = from.list();
265             for (int i = 0; i < kids.length; i++) {
266                 doCopy(new File JavaDoc(from, kids[i]), new File JavaDoc(to, kids[i]));
267             }
268         } else {
269             assert from.isFile();
270             InputStream JavaDoc is = new FileInputStream JavaDoc(from);
271             try {
272                 OutputStream JavaDoc os = new FileOutputStream JavaDoc(to);
273                 try {
274                     FileUtil.copy(is, os);
275                 } finally {
276                     os.close();
277                 }
278             } finally {
279                 is.close();
280             }
281         }
282     }
283     
284     public static String JavaDoc slurp(FileObject fileObject) throws IOException JavaDoc {
285         InputStream JavaDoc is = fileObject.getInputStream();
286         try {
287             ByteArrayOutputStream JavaDoc baos = new ByteArrayOutputStream JavaDoc();
288             FileUtil.copy(is, baos);
289             return baos.toString("UTF-8");
290         } finally {
291             is.close();
292         }
293     }
294     public static void dump(FileObject f, String JavaDoc contents) throws IOException JavaDoc {
295         FileLock lock = f.lock();
296         try {
297             OutputStream JavaDoc os = f.getOutputStream(lock);
298             try {
299                 Writer JavaDoc w = new OutputStreamWriter JavaDoc(os, "UTF-8");
300                 w.write(contents);
301                 w.flush();
302             } finally {
303                 os.close();
304             }
305         } finally {
306             lock.releaseLock();
307         }
308     }
309     public static String JavaDoc slurp(File JavaDoc file) throws IOException JavaDoc {
310         InputStream JavaDoc is = new FileInputStream JavaDoc(file);
311         try {
312             ByteArrayOutputStream JavaDoc baos = new ByteArrayOutputStream JavaDoc();
313             FileUtil.copy(is, baos);
314             return baos.toString("UTF-8");
315         } finally {
316             is.close();
317         }
318     }
319     public static void dump(File JavaDoc f, String JavaDoc contents) throws IOException JavaDoc {
320         f.getParentFile().mkdirs();
321         OutputStream JavaDoc os = new FileOutputStream JavaDoc(f);
322         try {
323             Writer JavaDoc w = new OutputStreamWriter JavaDoc(os, "UTF-8");
324             w.write(contents);
325             w.flush();
326         } finally {
327             os.close();
328         }
329     }
330     
331     // XXX copied from TestBase in ant/freeform
332
public static final class TestPCL implements PropertyChangeListener JavaDoc {
333         
334         public final Set JavaDoc/*<String>*/ changed = new HashSet JavaDoc();
335         public final Map JavaDoc/*<String,String>*/ newvals = new HashMap JavaDoc();
336         public final Map JavaDoc/*<String,String>*/ oldvals = new HashMap JavaDoc();
337         
338         public TestPCL() {}
339         
340         public void reset() {
341             changed.clear();
342             newvals.clear();
343             oldvals.clear();
344         }
345         
346         public void propertyChange(PropertyChangeEvent JavaDoc evt) {
347             String JavaDoc prop = evt.getPropertyName();
348             String JavaDoc nue = (String JavaDoc)evt.getNewValue();
349             String JavaDoc old = (String JavaDoc)evt.getOldValue();
350             changed.add(prop);
351             if (prop != null) {
352                 newvals.put(prop, nue);
353                 oldvals.put(prop, old);
354             } else {
355                 assert nue == null : "null prop name -> null new value";
356                 assert old == null : "null prop name -> null old value";
357             }
358         }
359         
360     }
361     
362     /**
363      * Calls in turn {@link TestBase#generateStandaloneModule(File, String)}
364      * with the {@link #getWorkDir()} as a first parameter.
365      */

366     public NbModuleProject generateStandaloneModule(String JavaDoc prjDir) throws IOException JavaDoc {
367         return generateStandaloneModule(getWorkDir(), prjDir);
368     }
369     
370     /**
371      * Returns {@link NbModuleProject} created in the {@link
372      * #getWorkDir()}/prjDir with code name base default to <em>org.example +
373      * dotted prjDir</em> which is also used as the <em>default</em> package so
374      * the layer and bundle are generated accordingly. Default module's display
375      * name is set to <em>Testing Module</em>. So final set of generated files
376      * for <em>module1</em> as the parameter may look like:
377      *
378      * <ul>
379      * <li>module1/manifest.mf
380      * <li>module1/nbproject/platform.properties
381      * <li>module1/nbproject/project.xml
382      * <li>module1/src/org/example/module1/resources/Bundle.properties
383      * <li>module1/src/org/example/module1/resources/layer.xml
384      * </ul>
385      *
386      * Do not forget to first call {@link #initializeBuildProperties} if you are not a TestBase subclass!
387      */

388     public static NbModuleProject generateStandaloneModule(File JavaDoc workDir, String JavaDoc prjDir) throws IOException JavaDoc {
389         FileObject prjDirFO = generateStandaloneModuleDirectory(workDir, prjDir);
390         return (NbModuleProject) ProjectManager.getDefault().findProject(prjDirFO);
391     }
392     
393     /**
394      * The same as {@link #generateStandaloneModule(File, String)} but without
395      * <em>opening</em> a generated project.
396      */

397     public static FileObject generateStandaloneModuleDirectory(File JavaDoc workDir, String JavaDoc prjDir) throws IOException JavaDoc {
398         String JavaDoc prjDirDotted = prjDir.replace('/', '.');
399         File JavaDoc prjDirF = file(workDir, prjDir);
400         NbModuleProjectGenerator.createStandAloneModule(
401                 prjDirF,
402                 "org.example." + prjDirDotted, // cnb
403
"Testing Module", // display name
404
"org/example/" + prjDir + "/resources/Bundle.properties",
405                 "org/example/" + prjDir + "/resources/layer.xml",
406                 NbPlatform.PLATFORM_ID_DEFAULT); // platform id
407
return FileUtil.toFileObject(prjDirF);
408     }
409     
410     /**
411      * Calls in turn {@link TestBase#generateSuite(File, String)} with the
412      * {@link #getWorkDir()} as a first parameter.
413      */

414     public SuiteProject generateSuite(String JavaDoc prjDir) throws IOException JavaDoc {
415         return generateSuite(getWorkDir(), prjDir);
416     }
417     
418     /** Generates an empty suite which has the default platform set. */
419     public static SuiteProject generateSuite(File JavaDoc workDir, String JavaDoc prjDir) throws IOException JavaDoc {
420         return generateSuite(workDir, prjDir, NbPlatform.PLATFORM_ID_DEFAULT);
421     }
422     
423     /** Generates an empty suite. */
424     public static SuiteProject generateSuite(File JavaDoc workDir, String JavaDoc prjDir, String JavaDoc platformID) throws IOException JavaDoc {
425         File JavaDoc prjDirF = file(workDir, prjDir);
426         SuiteProjectGenerator.createSuiteProject(prjDirF, platformID);
427         return (SuiteProject) ProjectManager.getDefault().findProject(
428                 FileUtil.toFileObject(prjDirF));
429     }
430     
431     /**
432      * Generates a suite component module which becomes a part of the given
433      * <code>suiteProject</code>. Module will be generated inside of the
434      * suite's project directory. <p>
435      * See {@link #generateStandaloneModule(File, String)} for details about
436      * what is generated.
437      */

438     public static NbModuleProject generateSuiteComponent(SuiteProject suiteProject, String JavaDoc prjDir) throws Exception JavaDoc {
439         File JavaDoc suiteDir = suiteProject.getProjectDirectoryFile();
440         return generateSuiteComponent(suiteProject, suiteDir, prjDir);
441     }
442     
443     /**
444      * Generates a suite component module which becomes a part of the given
445      * <code>suiteProject</code>.
446      * <p>
447      * See {@link #generateStandaloneModule(File, String)} for details about
448      * what is generated.
449      */

450     public static NbModuleProject generateSuiteComponent(SuiteProject suiteProject, File JavaDoc parentDir, String JavaDoc prjDir) throws Exception JavaDoc {
451         String JavaDoc prjDirDotted = prjDir.replace('/', '.');
452         File JavaDoc suiteDir = suiteProject.getProjectDirectoryFile();
453         File JavaDoc prjDirF = file(parentDir, prjDir);
454         NbModuleProjectGenerator.createSuiteComponentModule(
455                 prjDirF,
456                 "org.example." + prjDirDotted, // cnb
457
"Testing Module", // display name
458
"org/example/" + prjDir + "/resources/Bundle.properties",
459                 "org/example/" + prjDir + "/resources/layer.xml",
460                 suiteDir); // suite directory
461
return (NbModuleProject) ProjectManager.getDefault().findProject(
462                 FileUtil.toFileObject(prjDirF));
463     }
464     
465     /**
466      * Create a fresh JAR file.
467      * @param jar the file to create
468      * @param contents keys are JAR entry paths, values are text contents (will be written in UTF-8)
469      * @param manifest a manifest to store (or null for none)
470      */

471     public static void createJar(File JavaDoc jar, Map JavaDoc/*<String,String>*/ contents, Manifest JavaDoc manifest) throws IOException JavaDoc {
472         if (manifest != null) {
473             manifest.getMainAttributes().putValue("Manifest-Version", "1.0"); // workaround for JDK bug
474
}
475         jar.getParentFile().mkdirs();
476         OutputStream JavaDoc os = new FileOutputStream JavaDoc(jar);
477         try {
478             JarOutputStream JavaDoc jos = manifest != null ? new JarOutputStream JavaDoc(os, manifest) : new JarOutputStream JavaDoc(os);
479             Iterator JavaDoc it = contents.entrySet().iterator();
480             while (it.hasNext()) {
481                 Map.Entry JavaDoc entry = (Map.Entry JavaDoc) it.next();
482                 String JavaDoc path = (String JavaDoc) entry.getKey();
483                 byte[] data = ((String JavaDoc) entry.getValue()).getBytes("UTF-8");
484                 JarEntry JavaDoc je = new JarEntry JavaDoc(path);
485                 je.setSize(data.length);
486                 CRC32 JavaDoc crc = new CRC32 JavaDoc();
487                 crc.update(data);
488                 je.setCrc(crc.getValue());
489                 jos.putNextEntry(je);
490                 jos.write(data);
491             }
492             jos.close();
493         } finally {
494             os.close();
495         }
496     }
497     
498     public static void makePlatform(File JavaDoc d) throws IOException JavaDoc {
499         // To satisfy NbPlatform.defaultPlatformLocation and NbPlatform.isValid, and make at least one module:
500
Manifest JavaDoc mani = new Manifest JavaDoc();
501         mani.getMainAttributes().putValue("OpenIDE-Module", "core");
502         TestBase.createJar(new File JavaDoc(new File JavaDoc(new File JavaDoc(d, "platform"), "core"), "core.jar"), Collections.EMPTY_MAP, mani);
503         mani = new Manifest JavaDoc();
504         mani.getMainAttributes().putValue("OpenIDE-Module", "org.netbeans.modules.apisupport.harness");
505         mani.getMainAttributes().putValue("OpenIDE-Module-Specification-Version", "1.6.1"); // like 5.0
506
TestBase.createJar(new File JavaDoc(new File JavaDoc(new File JavaDoc(d, "harness"), "modules"), "org-netbeans-modules-apisupport-harness.jar"), Collections.EMPTY_MAP, mani);
507     }
508     
509     public static void delete(File JavaDoc f) throws IOException JavaDoc {
510         if (f.isDirectory()) {
511             File JavaDoc[] kids = f.listFiles();
512             for (int i = 0; i < kids.length; i++) {
513                 delete(kids[i]);
514             }
515         }
516         if (!f.delete()) {
517             throw new IOException JavaDoc("Could not delete " + f);
518         }
519     }
520     
521     private static File JavaDoc getTestNBRoot() {
522         String JavaDoc nbcvsroot = System.getProperty("test.nbcvsroot");
523         assertNotNull("test.nbcvsroot property has to be set", nbcvsroot);
524         return new File JavaDoc(nbcvsroot);
525     }
526     
527     private static File JavaDoc getXTestNBDestDir() {
528         String JavaDoc destDir = System.getProperty("xtest.netbeans.dest.dir");
529         assertNotNull("xtest.netbeans.dest.dir property has to be set when running within binary distribution", destDir);
530         return new File JavaDoc(destDir);
531     }
532     
533   }
534
Popular Tags