KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > modules > j2ee > blueprints > ui > projects > J2eeSampleProjectGenerator


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.blueprints.ui.projects;
21
22 import java.io.File JavaDoc;
23 import java.io.FileOutputStream JavaDoc;
24 import java.io.IOException JavaDoc;
25 import java.io.InputStream JavaDoc;
26 import java.io.OutputStream JavaDoc;
27 import java.util.HashMap JavaDoc;
28 import java.util.List JavaDoc;
29 import java.util.zip.ZipEntry JavaDoc;
30 import java.util.zip.ZipInputStream JavaDoc;
31 import org.netbeans.modules.j2ee.blueprints.catalog.SolutionsCatalog;
32 import org.netbeans.spi.project.support.ant.AntProjectHelper;
33 import org.netbeans.spi.project.support.ant.EditableProperties;
34 import org.openide.filesystems.FileLock;
35
36 import org.openide.filesystems.FileObject;
37 import org.openide.filesystems.FileUtil;
38 import org.openide.xml.XMLUtil;
39 import org.w3c.dom.Document JavaDoc;
40 import org.w3c.dom.Element JavaDoc;
41 import org.w3c.dom.Node JavaDoc;
42 import org.w3c.dom.NodeList JavaDoc;
43 import org.w3c.dom.Text JavaDoc;
44 import org.xml.sax.*;
45 import org.netbeans.modules.j2ee.blueprints.catalog.bpcatalogxmlparser.Nbcatalog;
46 import org.netbeans.modules.j2ee.blueprints.catalog.bpcatalogxmlparser.Nbcategory;
47 import org.netbeans.modules.j2ee.blueprints.catalog.bpcatalogxmlparser.Nbexample;
48 import org.netbeans.modules.j2ee.blueprints.catalog.bpcatalogxmlparser.Nbsolution;
49 import org.netbeans.modules.j2ee.blueprints.catalog.bpcatalogxmlparser.Nbwriteup;
50 import org.netbeans.modules.j2ee.blueprints.ui.BpcatalogLocalizedResource;
51 import org.netbeans.modules.j2ee.blueprints.ui.overview.OverviewPageTopComponent;
52 import org.openide.modules.InstalledFileLocator;
53 import org.openide.windows.TopComponent;
54 import org.openide.windows.WindowManager;
55
56 /**
57  * Create a sample J2EE project by unzipping a template into some directory
58  *
59  * @author Ludo Champenois
60  */

61 public class J2eeSampleProjectGenerator {
62     
63     private J2eeSampleProjectGenerator() {}
64
65     public static final String JavaDoc PROJECT_CONFIGURATION_NAMESPACE = "http://www.netbeans.org/ns/web-project/3"; //NOI18N
66
public static final String JavaDoc PROJECT_CONFIGURATION_NS_FREE = "http://www.netbeans.org/ns/freeform-project/1";
67     public static final String JavaDoc EJBJAR_NAMESPACE = "http://www.netbeans.org/ns/j2ee-ejbjarproject/3";
68     public static final String JavaDoc PROJECT_CONFIGURATION_J2SE = "http://www.netbeans.org/ns/j2se-project/2";
69     public static final String JavaDoc SUNWEBDD_XMLLOC = "web/WEB-INF/sun-web.xml";
70
71     public static FileObject createProjectFromTemplate(final FileObject template, File JavaDoc projectLocation, final String JavaDoc name) throws IOException JavaDoc {
72         FileObject prjLoc = null;
73         String JavaDoc slashname = "/"+name;
74         if (template.getExt().endsWith("zip")) { //NOI18N
75
unzip(template.getInputStream(), projectLocation);
76                 String JavaDoc extra = (String JavaDoc)template.getAttribute("extrazip");
77                 if (extra!=null){
78                     FileObject p = template.getParent().getFileObject(extra+".zip");
79                     
80                     if (p!=null){
81                         unzip(p.getInputStream(), new File JavaDoc( projectLocation.getParentFile(),extra));
82                     }
83                 }
84                 
85             try {
86                 prjLoc = FileUtil.toFileObject(projectLocation);
87                 
88                 NodeList JavaDoc nlist = null;
89                 //update project.xml
90
File JavaDoc projXml = FileUtil.toFile(prjLoc.getFileObject(AntProjectHelper.PROJECT_XML_PATH));
91                 Document JavaDoc doc = XMLUtil.parse(new InputSource(projXml.toURI().toString()), false, true, null, null);
92                 nlist = doc.getElementsByTagNameNS(PROJECT_CONFIGURATION_NAMESPACE, "name"); //NOI18N
93
// if web is not found, try ejb
94
// need to check the length too as it gets a node list contains no "name"
95
// with this name space.
96
if (nlist==null || nlist.getLength()==0){
97                     nlist = doc.getElementsByTagNameNS(EJBJAR_NAMESPACE, "name"); //NOI18N
98

99                 }
100                 if (nlist == null || nlist.getLength() == 0) {
101                     nlist = doc.getElementsByTagNameNS(PROJECT_CONFIGURATION_J2SE, "name");
102                 }
103                 if (nlist != null) {
104                     for (int i=0; i < nlist.getLength(); i++) {
105                         Node JavaDoc n = nlist.item(i);
106                         if (n.getNodeType() != Node.ELEMENT_NODE) {
107                             continue;
108                         }
109                         Element JavaDoc e = (Element JavaDoc)n;
110                         
111                         replaceText(e, name);
112                         saveXml(doc, prjLoc, AntProjectHelper.PROJECT_XML_PATH);
113                     }
114                 }
115                 
116                 // update sun-web.xml
117

118                 FileObject sunwebfile = prjLoc.getFileObject(SUNWEBDD_XMLLOC);
119                 // WebTier entry must have web/WEB-INF/sun-web.xml.
120
// If there isn't, assuming it's in other categories like SOA.
121
if (sunwebfile!=null) {
122                     File JavaDoc sunwebXml = FileUtil.toFile(sunwebfile);
123                     // XMLUtil.parse seems to try to connect the internet even validation is false.
124
// Creating entityResolver privately
125
Document JavaDoc swdoc = XMLUtil.parse(new InputSource(sunwebXml.toURI().toString()), false, true, null, SunWebDDResolver.getInstance());
126                     NodeList JavaDoc swnlist = swdoc.getElementsByTagName("context-root"); //NOI18N
127
// NodeList should contain only one, but just incase
128
if (swnlist != null) {
129                         for (int i=0; i < swnlist.getLength(); i++) {
130                             Node JavaDoc n = swnlist.item(i);
131                             if (n.getNodeType() != Node.ELEMENT_NODE) {
132                                 continue;
133                             }
134                             Element JavaDoc e = (Element JavaDoc)n;
135                             replaceText(e, slashname);
136                             saveXml(swdoc, prjLoc, SUNWEBDD_XMLLOC);
137                         }
138                     }
139                 }
140                 
141                 // Change props in project.properties
142
replaceProperties(prjLoc, name);
143                 
144             } catch (Exception JavaDoc e) {
145                 throw new IOException JavaDoc(e.toString());
146             }
147                    
148             prjLoc.refresh(false);
149         }
150         return prjLoc;
151     }
152     
153     private static void replaceProperties(FileObject dir, String JavaDoc prjName) throws IOException JavaDoc {
154         
155         // heuristic hack process for each project type.
156
// should use AntProjectHelper, if possible.
157
final String JavaDoc DIST_JAR = "dist.jar"; // NOI18N
158
final String JavaDoc DIST_DIR = "${dist.dir}/"; // NOI18N
159
final String JavaDoc DIST_EAR_JAR = "dist.ear.jar"; // NOI18N
160
final String JavaDoc WAR_NAME = "war.name"; // NOI18N
161
final String JavaDoc WAR_EAR_NAME = "war.ear.name"; // NOI18N
162

163         String JavaDoc BP_LIB_DIR = "bp-lib.dir"; //NOI18N
164
String JavaDoc BP_UI5_JAR = "file.reference.bp-ui-5.jar"; //NOI18N
165

166         String JavaDoc currentProp;
167         String JavaDoc suffix;
168         
169         EditableProperties props = new EditableProperties(true);
170         FileObject prjProp = FileUtil.createData(dir, AntProjectHelper.PROJECT_PROPERTIES_PATH);
171         
172         try {
173             InputStream JavaDoc in = prjProp.getInputStream();
174             props.load(in);
175             in.close();
176         } catch (Exception JavaDoc e) {
177             throw new IOException JavaDoc(e.toString());
178         }
179         
180         String JavaDoc distJar = props.getProperty(DIST_JAR);
181         // 1. for J2SE/EAR type : should be "dist.jar=${dist.dir}/PROJECT.[jar, ear]"
182
if (distJar != null) {
183             props.setProperty(DIST_JAR, DIST_DIR + prjName +
184                     distJar.substring(distJar.lastIndexOf('.'))); // NOI18N
185
//2. for EJB type : should be "dist.ear.jar=${dist.dir}/PROJECT.[jar, ear]"
186
currentProp = props.getProperty(DIST_EAR_JAR);
187             if (currentProp != null) {
188                 props.setProperty(DIST_EAR_JAR,
189                         DIST_DIR + prjName + currentProp.substring(currentProp.indexOf("."))); // NOI18N
190
}
191         // 3. for Web app : should be "war.name=PROJECT.war"
192
} else if (props.getProperty(WAR_NAME) != null) {
193             props.setProperty(WAR_NAME, prjName + ".war"); // NOI18N
194
// Web app should have this as well. Just in case...
195
// this should be "war.ear.name=PROJECT.[war, ear]"
196
currentProp = props.getProperty(WAR_EAR_NAME);
197             if (currentProp != null) {
198                 props.setProperty(WAR_EAR_NAME,
199                         prjName + currentProp.substring(currentProp.indexOf("."))); // NOI18N
200
}
201         }
202         
203         //Replace library location
204
String JavaDoc bpLibsLocation = getBlueprintsLibsLocation();
205         props.setProperty(BP_LIB_DIR, bpLibsLocation);
206         if(props.getProperty(BP_UI5_JAR) != null){
207             props.setProperty(BP_UI5_JAR, bpLibsLocation + File.separator + "bp-ui-5.jar"); //NOI18N
208
}
209         
210         //helper.putProperties(AntProjectHelper.PROJECT_PROPERTIES_PATH, props);
211
FileLock lock = prjProp.lock();
212         try {
213             OutputStream JavaDoc os = prjProp.getOutputStream(lock);
214             try {
215                 props.store(os);
216             } finally {
217                 os.close();
218             }
219         } finally {
220             lock.releaseLock();
221         }
222     }
223     
224     private static void unzip(InputStream JavaDoc source, File JavaDoc targetFolder) throws IOException JavaDoc {
225         //installation
226
ZipInputStream JavaDoc zip=new ZipInputStream JavaDoc(source);
227         try {
228             ZipEntry JavaDoc ent;
229             while ((ent = zip.getNextEntry()) != null) {
230                 File JavaDoc f = new File JavaDoc(targetFolder, ent.getName());
231                 if (ent.isDirectory()) {
232                     f.mkdirs();
233                 } else {
234                     f.getParentFile().mkdirs();
235                     FileOutputStream JavaDoc out = new FileOutputStream JavaDoc(f);
236                     try {
237                         FileUtil.copy(zip, out);
238                     } finally {
239                         out.close();
240                     }
241                 }
242             }
243         } finally {
244             zip.close();
245         }
246     }
247
248     /**
249      * Extract nested text from an element.
250      * Currently does not handle coalescing text nodes, CDATA sections, etc.
251      * @param parent a parent element
252      * @return the nested text, or null if none was found
253      */

254     private static void replaceText(Element JavaDoc parent, String JavaDoc name) {
255         NodeList JavaDoc l = parent.getChildNodes();
256         for (int i = 0; i < l.getLength(); i++) {
257             if (l.item(i).getNodeType() == Node.TEXT_NODE) {
258                 Text JavaDoc text = (Text JavaDoc)l.item(i);
259                 text.setNodeValue(name);
260                 return;
261             }
262         }
263     }
264     
265     /**
266      * Save an XML config file to a named path.
267      * If the file does not yet exist, it is created.
268      */

269     private static void saveXml(Document JavaDoc doc, FileObject dir, String JavaDoc path) throws IOException JavaDoc {
270         FileObject xml = FileUtil.createData(dir, path);
271         FileLock lock = xml.lock();
272         try {
273             OutputStream JavaDoc os = xml.getOutputStream(lock);
274             try {
275                 XMLUtil.write(doc, os, "UTF-8"); // NOI18N
276
} finally {
277                 os.close();
278             }
279         } finally {
280             lock.releaseLock();
281         }
282     }
283     
284         private static class SunWebDDResolver implements EntityResolver {
285         static SunWebDDResolver resolver;
286         static synchronized SunWebDDResolver getInstance() {
287             if (resolver==null) {
288                 resolver=new SunWebDDResolver();
289             }
290             return resolver;
291         }
292         public InputSource resolveEntity (String JavaDoc publicId, String JavaDoc systemId) {
293             String JavaDoc resource=null;
294             // return a proper input source
295
resource = "/org/netbeans/modules/j2ee/blueprints/ui/resources/sun-web-app_2_4-1.dtd"; //NOI18N
296
/***
297             if ("-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN".equals(publicId)) { //NOI18N
298                 resource="/org/netbeans/modules/j2ee/dd/impl/resources/web-app_2_3.dtd"; //NOI18N
299             } else if ("-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN".equals(publicId)) { //NOI18N
300                 resource="/org/netbeans/modules/j2ee/dd/impl/resources/web-app_2_2.dtd"; //NOI18N
301             } else if ("http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd".equals(systemId)) {
302                 resource="/org/netbeans/modules/j2ee/dd/impl/resources/web-app_2_4.xsd"; //NOI18N
303             }
304             if (resource==null) return null;
305  ****/

306             java.net.URL JavaDoc url = this.getClass().getResource(resource);
307             return new InputSource(url.toString());
308         }
309     }
310         
311     private static String JavaDoc getBlueprintsLibsLocation(){
312         String JavaDoc location = "";
313         File JavaDoc f = InstalledFileLocator.getDefault().locate("modules/ext/blueprints/bp-ui-14.jar", null, true);
314         if(f != null)
315             location = f.getParentFile().getAbsolutePath();
316         return location;
317     }
318     
319     public static void getOverviewPage(org.openide.loaders.TemplateWizard templateWizard){
320         TopComponent tc = WindowManager.getDefault().findTopComponent("BluePrints");
321         if(tc.isOpened()){
322             return;
323         }
324         
325         FileObject template = templateWizard.getTemplate().getPrimaryFile();
326         String JavaDoc currentModName = template.getName();
327         SolutionsCatalog solutionsCatalog = SolutionsCatalog.getInstance();
328         
329         Nbcatalog nbcatalog = solutionsCatalog.getCatalogXml();
330         HashMap JavaDoc overviewFiles = populateEntries(nbcatalog);
331         String JavaDoc pagePath = (String JavaDoc)overviewFiles.get(currentModName);
332         String JavaDoc overviewPage = getLocalizedPath(pagePath);
333
334         TopComponent win = OverviewPageTopComponent.findInstance();
335         OverviewPageTopComponent comp = (OverviewPageTopComponent)win;
336         if(comp.isOpened())
337             comp.close();
338         comp.setOverviewFile(overviewPage);
339         comp.open();
340         comp.requestActive();
341     }
342        
343     private static HashMap JavaDoc populateEntries(Nbcatalog nbcatalog){
344         HashMap JavaDoc overviewFiles = new HashMap JavaDoc();
345         List JavaDoc cats = nbcatalog.fetchNbcategoryList();
346         for(int catNum=0; catNum<cats.size(); catNum++){
347             Nbcategory category = (Nbcategory)cats.get(catNum);
348             List JavaDoc sols = category.fetchNbsolutionList();
349             for(int solNum=0; solNum<sols.size(); solNum++){
350                 Nbsolution sol = (Nbsolution)sols.get(solNum);
351                 Nbwriteup write = sol.getNbwriteup();
352                 String JavaDoc categoryID = category.getId();
353                 String JavaDoc articlePath = write.getArticlePath();
354                 if(categoryID.equals("Ajax")) { //NOI18N
355
articlePath = "docs/ajax/overview-Ajax.html";
356                 }else if(categoryID.equals("JavaPersistence")) { //NOI18N
357
articlePath = "docs/persistence/overview-JavaPersistence.html";
358                 }
359                 overviewFiles.put(sol.getExampleId(), articlePath);
360             }
361         }
362         return overviewFiles;
363     }
364     
365     private static String JavaDoc getLocalizedPath(String JavaDoc articlePath){
366         String JavaDoc CATALOG_RESOURCES_URL = "/org/netbeans/modules/j2ee/blueprints/catalog/resources"; // NOI18N
367
String JavaDoc path = CATALOG_RESOURCES_URL + "/" + articlePath; // NOI18N
368
BpcatalogLocalizedResource htmlrsc =
369                     new BpcatalogLocalizedResource(path, "html"); // NOI18N
370
String JavaDoc localizedPath = htmlrsc.getResourcePath();
371         return localizedPath;
372     }
373 }
374
Popular Tags