KickJava   Java API By Example, From Geeks To Geeks.

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


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 org.netbeans.modules.apisupport.project.spi.NbModuleProvider;
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.util.Enumeration JavaDoc;
28 import java.util.HashMap JavaDoc;
29 import java.util.Map JavaDoc;
30 import java.util.SortedSet JavaDoc;
31 import java.util.TreeSet JavaDoc;
32 import java.util.jar.JarEntry JavaDoc;
33 import java.util.jar.JarFile JavaDoc;
34 import org.netbeans.api.project.ProjectManager;
35 import org.netbeans.api.queries.CollocationQuery;
36 import org.netbeans.modules.apisupport.project.ui.customizer.SingleModuleProperties;
37 import org.netbeans.modules.apisupport.project.universe.LocalizedBundleInfo;
38 import org.netbeans.modules.apisupport.project.universe.ModuleList;
39 import org.netbeans.spi.project.support.ant.AntProjectHelper;
40 import org.netbeans.spi.project.support.ant.EditableProperties;
41 import org.netbeans.spi.project.support.ant.GeneratedFilesHelper;
42 import org.netbeans.spi.project.support.ant.PropertyUtils;
43 import org.openide.ErrorManager;
44 import org.openide.filesystems.FileLock;
45 import org.openide.filesystems.FileObject;
46 import org.openide.filesystems.FileUtil;
47 import org.openide.util.Mutex;
48 import org.openide.util.MutexException;
49 import org.openide.xml.XMLUtil;
50 import org.w3c.dom.Document JavaDoc;
51 import org.w3c.dom.Element JavaDoc;
52
53 /**
54  * Servers for generating new NetBeans Modules templates.
55  *
56  * @author Martin Krauskopf
57  */

58 public class NbModuleProjectGenerator {
59     
60     public static final String JavaDoc PLATFORM_PROPERTIES_PATH =
61             "nbproject/platform.properties"; // NOI18N
62

63     /** Use static factory methods instead. */
64     private NbModuleProjectGenerator() {/* empty constructor*/}
65     
66     /** Generates standalone NetBeans Module. */
67     public static void createStandAloneModule(final File JavaDoc projectDir, final String JavaDoc cnb,
68             final String JavaDoc name, final String JavaDoc bundlePath,
69             final String JavaDoc layerPath, final String JavaDoc platformID) throws IOException JavaDoc {
70         try {
71             ProjectManager.mutex().writeAccess(new Mutex.ExceptionAction() {
72                 public Object JavaDoc run() throws IOException JavaDoc {
73                     final FileObject dirFO = FileUtil.createFolder(projectDir);
74                     if (ProjectManager.getDefault().findProject(dirFO) != null) {
75                         throw new IllegalArgumentException JavaDoc("Already a project in " + dirFO); // NOI18N
76
}
77                     createProjectXML(dirFO, cnb, NbModuleProvider.STANDALONE);
78                     createPlatformProperties(dirFO, platformID);
79                     createManifest(dirFO, cnb, bundlePath, layerPath);
80                     if (bundlePath != null) {
81                         createBundle(dirFO, bundlePath, name);
82                     }
83                     if (layerPath != null) {
84                         createLayerInSrc(dirFO, layerPath);
85                     }
86                     createEmptyTestDir(dirFO);
87                     ModuleList.refresh();
88                     ProjectManager.getDefault().clearNonProjectCache();
89                     return null;
90                 }
91             });
92         } catch (MutexException e) {
93             throw (IOException JavaDoc) e.getException();
94         }
95     }
96     
97     /** Generates suite component NetBeans Module. */
98     public static void createSuiteComponentModule(final File JavaDoc projectDir, final String JavaDoc cnb,
99             final String JavaDoc name, final String JavaDoc bundlePath,
100             final String JavaDoc layerPath, final File JavaDoc suiteDir) throws IOException JavaDoc {
101         try {
102             ProjectManager.mutex().writeAccess(new Mutex.ExceptionAction() {
103                 public Object JavaDoc run() throws IOException JavaDoc {
104                     final FileObject dirFO = FileUtil.createFolder(projectDir);
105                     if (ProjectManager.getDefault().findProject(dirFO) != null) {
106                         throw new IllegalArgumentException JavaDoc("Already a project in " + dirFO); // NOI18N
107
}
108                     createProjectXML(dirFO, cnb, NbModuleProvider.SUITE_COMPONENT);
109                     createSuiteProperties(dirFO, suiteDir);
110                     createManifest(dirFO, cnb, bundlePath, layerPath);
111                     if (bundlePath != null) {
112                         createBundle(dirFO, bundlePath, name);
113                     }
114                     if (layerPath != null) {
115                         createLayerInSrc(dirFO, layerPath);
116                     }
117                     createEmptyTestDir(dirFO);
118                     ModuleList.refresh();
119                     ProjectManager.getDefault().clearNonProjectCache();
120                     appendToSuite(cnb, dirFO, suiteDir);
121                     return null;
122                 }
123             });
124         } catch (MutexException e) {
125             throw (IOException JavaDoc) e.getException();
126         }
127     }
128     
129     /** Generates suite component Library Wrapper NetBeans Module. */
130     public static void createSuiteLibraryModule(final File JavaDoc projectDir, final String JavaDoc cnb,
131             final String JavaDoc name, final String JavaDoc bundlePath, final File JavaDoc suiteDir,
132             final File JavaDoc license, final File JavaDoc[] jars) throws IOException JavaDoc {
133         try {
134             ProjectManager.mutex().writeAccess(new Mutex.ExceptionAction() {
135                 public Object JavaDoc run() throws IOException JavaDoc {
136                     final FileObject dirFO = FileUtil.createFolder(projectDir);
137                     if (ProjectManager.getDefault().findProject(dirFO) != null) {
138                         throw new IllegalArgumentException JavaDoc("Already a project in " + dirFO); // NOI18N
139
}
140                     
141                     EditableProperties props = new EditableProperties(true);
142                     props.put(SingleModuleProperties.IS_AUTOLOAD, "true"); // NOI18N
143
SortedSet JavaDoc<String JavaDoc> packageList = new TreeSet JavaDoc();
144                     Map JavaDoc classPathExtensions = new HashMap JavaDoc();
145                     
146                     File JavaDoc releaseDir = new File JavaDoc(projectDir, "release/modules/ext"); //NOI18N
147
if (!releaseDir.mkdirs()) {
148                         //TODO report error
149
Util.err.log("cannot create release directory.");
150                     }
151                     FileObject relDirFo = FileUtil.toFileObject(releaseDir);
152                     for (int i = 0; i < jars.length; i++) {
153                         FileObject orig = FileUtil.toFileObject(FileUtil.normalizeFile(jars[i]));
154                         if (orig != null) {
155                             JarFile JavaDoc jf = null;
156                             try {
157                                 FileUtil.copyFile(orig, relDirFo, orig.getName());
158                                 jf = new JarFile JavaDoc(jars[i]);
159                                 Enumeration JavaDoc en = jf.entries();
160                                 while (en.hasMoreElements()) {
161                                     JarEntry JavaDoc entry = (JarEntry JavaDoc)en.nextElement();
162                                     if (!entry.isDirectory() && entry.getName().endsWith(".class")) { // NOI18N
163
String JavaDoc nm = entry.getName();
164                                         if (!Util.isValidJavaFQN(nm.substring(0, nm.length() - 6).replace('/', '.'))) {
165                                             continue; // #72669
166
}
167                                         int index = nm.lastIndexOf('/');
168                                         if (index > -1) {
169                                             String JavaDoc path = nm.substring(0, index);
170                                             packageList.add(path.replace('/', '.'));
171                                         }
172                                     }
173                                 }
174                                 classPathExtensions.put("ext/" + orig.getNameExt(), "release/modules/ext/" + orig.getNameExt()); // NOI18N
175
} catch (IOException JavaDoc e) {
176                                 //TODO report
177
Util.err.notify(e);
178                             } finally {
179                                 if (jf != null) {
180                                     try {
181                                         jf.close();
182                                     } catch (IOException JavaDoc e) {
183                                         Util.err.notify(ErrorManager.INFORMATIONAL, e);
184                                     }
185                                 }
186                             }
187                         }
188                     }
189                     
190                     if (license != null && license.exists()) {
191                         FileObject fo = FileUtil.toFileObject(license);
192                         try {
193                             FileUtil.copyFile(fo, dirFO, fo.getName());
194                             props.put(SingleModuleProperties.LICENSE_FILE, "${basedir}/" + fo.getNameExt()); // NOI18N
195
//TODO set the nbm.license property
196
} catch (IOException JavaDoc e) {
197                             //TODO report
198
Util.err.notify(e);
199                         }
200                         
201                     }
202                     ProjectXMLManager.generateLibraryModuleTemplate(
203                             createFileObject(dirFO, AntProjectHelper.PROJECT_XML_PATH),
204                             cnb, NbModuleProvider.SUITE_COMPONENT, packageList, classPathExtensions);
205                     createSuiteProperties(dirFO, suiteDir);
206                     createManifest(dirFO, cnb, bundlePath, null);
207                     createBundle(dirFO, bundlePath, name);
208                     
209                     // write down the nbproject/properties file
210
FileObject bundleFO = createFileObject(
211                             dirFO, "nbproject/project.properties"); // NOI18N
212
Util.storeProperties(bundleFO, props);
213                     
214                     ModuleList.refresh();
215                     ProjectManager.getDefault().clearNonProjectCache();
216                     appendToSuite(cnb, dirFO, suiteDir);
217                     return null;
218                 }
219             });
220         } catch (MutexException e) {
221             throw (IOException JavaDoc) e.getException();
222         }
223     }
224     
225     /**
226      * Generates NetBeans Module within the netbeans.org CVS tree.
227      */

228     public static void createNetBeansOrgModule(final File JavaDoc projectDir, final String JavaDoc cnb,
229             final String JavaDoc name, final String JavaDoc bundlePath, final String JavaDoc layerPath) throws IOException JavaDoc {
230         try {
231             ProjectManager.mutex().writeAccess(new Mutex.ExceptionAction() {
232                 public Object JavaDoc run() throws IOException JavaDoc {
233                     File JavaDoc nborg = ModuleList.findNetBeansOrg(projectDir);
234                     if (nborg == null) {
235                         throw new IllegalArgumentException JavaDoc(projectDir + " doesn't " + // NOI18N
236
"point to directory within the netbeans.org CVS tree"); // NOI18N
237
}
238                     final FileObject dirFO = FileUtil.createFolder(projectDir);
239                     if (ProjectManager.getDefault().findProject(dirFO) != null) {
240                         throw new IllegalArgumentException JavaDoc("Already a project in " + dirFO); // NOI18N
241
}
242                     createNetBeansOrgBuildXML(dirFO, cnb, nborg);
243                     createProjectXML(dirFO, cnb, NbModuleProvider.NETBEANS_ORG);
244                     createManifest(dirFO, cnb, bundlePath, layerPath);
245                     createBundle(dirFO, bundlePath, name);
246                     createLayerInSrc(dirFO, layerPath);
247                     createEmptyTestDir(dirFO);
248                     ModuleList.refresh();
249                     ProjectManager.getDefault().clearNonProjectCache();
250                     return null;
251                 }
252             });
253         } catch (MutexException e) {
254             throw (IOException JavaDoc) e.getException();
255         }
256     }
257     
258     /**
259      * Creates basic <em>nbbuild/project.xml</em> or whatever
260      * <code>AntProjectHelper.PROJECT_XML_PATH</code> is pointing to for
261      * <em>standalone</em> or <em>module in suite</em> module.
262      */

263     private static void createProjectXML(FileObject projectDir,
264             String JavaDoc cnb, NbModuleProvider.NbModuleType type) throws IOException JavaDoc {
265         ProjectXMLManager.generateEmptyModuleTemplate(
266                 createFileObject(projectDir, AntProjectHelper.PROJECT_XML_PATH),
267                 cnb, type);
268     }
269     
270     /**
271      * Creates basic <em>build.xml</em> or whatever
272      * <code>GeneratedFilesHelper.BUILD_XML_PATH</code> is pointing to.
273      */

274     private static void createNetBeansOrgBuildXML(FileObject projectDir, String JavaDoc cnb,
275             File JavaDoc nborg) throws IOException JavaDoc {
276         FileObject buildScript = NbModuleProjectGenerator.createFileObject(
277                 projectDir, GeneratedFilesHelper.BUILD_XML_PATH);
278         Document JavaDoc prjDoc = XMLUtil.createDocument("project", null, null, null); // NOI18N
279
Element JavaDoc prjEl = prjDoc.getDocumentElement();
280         prjEl.setAttribute("name", PropertyUtils.relativizeFile(nborg, // NOI18N
281
FileUtil.toFile(projectDir)));
282         prjEl.setAttribute("default", "netbeans"); // NOI18N
283
prjEl.setAttribute("basedir", "."); // NOI18N
284

285         Element JavaDoc el = prjDoc.createElement("description"); // NOI18N
286
el.appendChild(prjDoc.createTextNode("Builds, tests, and runs the " + // NOI18N
287
"project " + cnb)); // NOI18N
288
prjEl.appendChild(el);
289         
290         el = prjDoc.createElement("import"); // NOI18N
291
el.setAttribute("file", PropertyUtils.relativizeFile(FileUtil.toFile(projectDir), // NOI18N
292
new File JavaDoc(nborg, "nbbuild/templates/projectized.xml"))); // NOI18N
293
prjEl.appendChild(el);
294         
295         // store document to disk
296
FileLock lock = buildScript.lock();
297         try {
298             OutputStream JavaDoc os = buildScript.getOutputStream(lock);
299             try {
300                 XMLUtil.write(prjDoc, os, "UTF-8"); // NOI18N
301
} finally {
302                 os.close();
303             }
304         } finally {
305             lock.releaseLock();
306         }
307     }
308     
309     /**
310      * Detects whether <code>projectDir</code> is relative to
311      * <code>suiteDir</code> and creates <em>nbproject/suite.properties</em> or
312      * <em>nbproject/private/suite-private.properties</em> with
313      * <em>suite.dir</em> appropriately set.
314      */

315     public static void createSuiteProperties(FileObject projectDir, File JavaDoc suiteDir) throws IOException JavaDoc {
316         File JavaDoc projectDirF = FileUtil.toFile(projectDir);
317         String JavaDoc suiteLocation;
318         String JavaDoc suitePropertiesLocation;
319         if (CollocationQuery.areCollocated(projectDirF, suiteDir)) {
320             suiteLocation = "${basedir}/" + PropertyUtils.relativizeFile(projectDirF, suiteDir); // NOI18N
321
suitePropertiesLocation = "nbproject/suite.properties"; // NOI18N
322
} else {
323             suiteLocation = suiteDir.getAbsolutePath();
324             suitePropertiesLocation = "nbproject/private/suite-private.properties"; // NOI18N
325
}
326         EditableProperties props = new EditableProperties(true);
327         props.setProperty("suite.dir", suiteLocation); // NOI18N
328
FileObject suiteProperties = createFileObject(projectDir, suitePropertiesLocation);
329         Util.storeProperties(suiteProperties, props);
330     }
331     
332     /**
333      * Appends currently created project in the <code>projectDir<code> to a
334      * suite project contained in the <code>suiteDir</code>. Also intelligently
335      * decides whether an added project is relative to a destination suite or
336      * absolute and uses either <em>nbproject/project.properties</em> or
337      * <em>nbproject/private/private.properties</em> appropriately.
338      */

339     private static void appendToSuite(String JavaDoc cnb, FileObject projectDir, File JavaDoc suiteDir) throws IOException JavaDoc {
340         File JavaDoc projectDirF = FileUtil.toFile(projectDir);
341         File JavaDoc suiteGlobalPropsFile = new File JavaDoc(suiteDir, "nbproject/project.properties"); // NOI18N
342
FileObject suiteGlobalPropFO;
343         if (suiteGlobalPropsFile.exists()) {
344             suiteGlobalPropFO = FileUtil.toFileObject(suiteGlobalPropsFile);
345         } else {
346             suiteGlobalPropFO = createFileObject(suiteGlobalPropsFile);
347         }
348         EditableProperties globalProps = Util.loadProperties(suiteGlobalPropFO);
349         String JavaDoc projectPropKey = "project." + cnb; // NOI18N
350
if (CollocationQuery.areCollocated(projectDirF, suiteDir)) {
351             globalProps.setProperty(projectPropKey,
352                     PropertyUtils.relativizeFile(suiteDir, projectDirF));
353         } else {
354             File JavaDoc suitePrivPropsFile = new File JavaDoc(suiteDir, "nbproject/private/private.properties"); // NOI18N
355
FileObject suitePrivPropFO;
356             if (suitePrivPropsFile.exists()) {
357                 suitePrivPropFO = FileUtil.toFileObject(suitePrivPropsFile);
358             } else {
359                 suitePrivPropFO = createFileObject(suitePrivPropsFile);
360             }
361             EditableProperties privProps= Util.loadProperties(suitePrivPropFO);
362             privProps.setProperty(projectPropKey, projectDirF.getAbsolutePath());
363             Util.storeProperties(suitePrivPropFO, privProps);
364         }
365         String JavaDoc modulesProp = globalProps.getProperty("modules"); // NOI18N
366
if (modulesProp == null) {
367             modulesProp = "";
368         }
369         if (modulesProp.length() > 0) {
370             modulesProp += ":"; // NOI18N
371
}
372         modulesProp += "${" + projectPropKey + "}"; // NOI18N
373
globalProps.setProperty("modules", modulesProp.split("(?<=:)", -1)); // NOI18N
374
Util.storeProperties(suiteGlobalPropFO, globalProps);
375     }
376     
377     private static void createPlatformProperties(FileObject projectDir, String JavaDoc platformID) throws IOException JavaDoc {
378         FileObject plafPropsFO = createFileObject(
379                 projectDir, NbModuleProjectGenerator.PLATFORM_PROPERTIES_PATH);
380         EditableProperties props = new EditableProperties(true);
381         props.put("nbplatform.active", platformID); // NOI18N
382
Util.storeProperties(plafPropsFO, props);
383     }
384     
385     private static void createManifest(FileObject projectDir, String JavaDoc cnb,
386             String JavaDoc bundlePath, String JavaDoc layerPath) throws IOException JavaDoc {
387         FileObject manifestFO = createFileObject(
388                 projectDir, "manifest.mf"); // NOI18N
389
ManifestManager.createManifest(manifestFO, cnb, "1.0", bundlePath, layerPath); // NOI18N
390
}
391     
392     private static void createBundle(FileObject projectDir, String JavaDoc bundlePath,
393             String JavaDoc name) throws IOException JavaDoc {
394         String JavaDoc pathToBundle = "src/" + bundlePath.replace('\\','/'); // NOI18N
395
FileObject bundleFO = createFileObject(projectDir, pathToBundle);
396         EditableProperties props = new EditableProperties(true);
397         props.put(LocalizedBundleInfo.NAME, name);
398         Util.storeProperties(bundleFO, props);
399     }
400     
401     private static void createLayerInSrc(FileObject projectDir, String JavaDoc layerPath) throws IOException JavaDoc {
402         createLayer(projectDir, "src/" + layerPath); // NOI18N
403
}
404     
405     public static FileObject createLayer(FileObject projectDir, String JavaDoc layerPath) throws IOException JavaDoc {
406         FileObject layerFO = createFileObject(projectDir, layerPath); // NOI18N
407
FileLock lock = layerFO.lock();
408         try {
409             InputStream JavaDoc is = NbModuleProjectGenerator.class.getResourceAsStream("ui/resources/layer_template.xml"); // NOI18N
410
try {
411                 OutputStream JavaDoc os = layerFO.getOutputStream(lock);
412                 try {
413                     FileUtil.copy(is, os);
414                 } finally {
415                     os.close();
416                 }
417             } finally {
418                 is.close();
419             }
420         } finally {
421             lock.releaseLock();
422         }
423         return layerFO;
424     }
425     
426     private static void createEmptyTestDir(FileObject projectDir) throws IOException JavaDoc {
427         FileUtil.createFolder(projectDir, "test/unit/src"); // NOI18N
428
}
429     
430     /**
431      * Creates a new <code>FileObject</code>.
432      * Throws <code>IllegalArgumentException</code> if such an object already
433      * exists. Throws <code>IOException</code> if creation fails.
434      */

435     private static FileObject createFileObject(FileObject dir, String JavaDoc relToDir) throws IOException JavaDoc {
436         FileObject createdFO = dir.getFileObject(relToDir);
437         if (createdFO != null) {
438             throw new IllegalArgumentException JavaDoc("File " + createdFO + " already exists."); // NOI18N
439
}
440         createdFO = FileUtil.createData(dir, relToDir);
441         return createdFO;
442     }
443     
444     /**
445      * Creates a new <code>FileObject</code>.
446      * Throws <code>IllegalArgumentException</code> if such an object already
447      * exists. Throws <code>IOException</code> if creation fails.
448      */

449     private static FileObject createFileObject(File JavaDoc fileToCreate) throws IOException JavaDoc {
450         File JavaDoc parent = fileToCreate.getParentFile();
451         if (parent == null) {
452             throw new IllegalArgumentException JavaDoc("Cannot create: " + fileToCreate); // NOI18N
453
}
454         if (!parent.exists()) {
455             parent.mkdirs();
456         }
457         return createFileObject(
458                 FileUtil.toFileObject(parent), fileToCreate.getName());
459     }
460     
461 }
462
Popular Tags