KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > modules > websvc > dev > wizard > WSGenerationUtil


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.websvc.dev.wizard;
21
22 import java.io.BufferedInputStream JavaDoc;
23 import java.io.BufferedOutputStream JavaDoc;
24 import java.io.ByteArrayInputStream JavaDoc;
25 import java.io.ByteArrayOutputStream JavaDoc;
26 import java.io.IOException JavaDoc;
27 import java.io.InputStream JavaDoc;
28 import java.io.OutputStream JavaDoc;
29 import java.io.OutputStreamWriter JavaDoc;
30 import java.io.StringReader JavaDoc;
31 import java.io.StringWriter JavaDoc;
32 import java.io.Writer JavaDoc;
33 import java.text.DateFormat JavaDoc;
34 import java.util.*;
35 import javax.swing.text.BadLocationException JavaDoc;
36 import javax.swing.text.Document JavaDoc;
37 import javax.xml.parsers.ParserConfigurationException JavaDoc;
38 import javax.xml.parsers.SAXParser JavaDoc;
39 import javax.xml.parsers.SAXParserFactory JavaDoc;
40 import javax.xml.transform.Source JavaDoc;
41 import javax.xml.transform.Templates JavaDoc;
42 import javax.xml.transform.Transformer JavaDoc;
43 import javax.xml.transform.TransformerConfigurationException JavaDoc;
44 import javax.xml.transform.TransformerException JavaDoc;
45 import javax.xml.transform.TransformerFactory JavaDoc;
46 import javax.xml.transform.URIResolver JavaDoc;
47 import javax.xml.transform.stream.StreamResult JavaDoc;
48 import javax.xml.transform.stream.StreamSource JavaDoc;
49 import org.netbeans.api.java.project.JavaProjectConstants;
50 import org.netbeans.api.project.Project;
51 import org.netbeans.api.project.ProjectUtils;
52 import org.netbeans.api.project.SourceGroup;
53 import org.netbeans.api.project.Sources;
54 import org.netbeans.modules.websvc.dev.dd.gen.wscreation.Bean;
55 import org.openide.ErrorManager;
56 import org.openide.cookies.EditorCookie;
57 import org.openide.filesystems.FileLock;
58 import org.openide.filesystems.FileObject;
59 import org.openide.filesystems.FileUtil;
60 import org.openide.loaders.DataObject;
61 import org.openide.text.IndentEngine;
62 import org.openide.util.RequestProcessor;
63 import org.xml.sax.Attributes JavaDoc;
64 import org.xml.sax.InputSource JavaDoc;
65 import org.xml.sax.SAXException JavaDoc;
66 import org.xml.sax.helpers.DefaultHandler JavaDoc;
67
68 public class WSGenerationUtil {
69     public static final String JavaDoc TEMPLATE_BASE = "/org/netbeans/modules/websvc/dev/wizard/xsl/"; //NOI18N
70
private String JavaDoc genDate;
71     private String JavaDoc genAuthor;
72     private Map templateCache = new HashMap();
73     
74     public static String JavaDoc getSelectedPackageName(FileObject targetFolder, Project p) {
75         Sources sources = ProjectUtils.getSources(p);
76         SourceGroup[] groups = sources.getSourceGroups(JavaProjectConstants.SOURCES_TYPE_JAVA);
77         String JavaDoc packageName = null;
78         for (int i = 0; i < groups.length && packageName == null; i++) {
79             packageName = FileUtil.getRelativePath(groups [i].getRootFolder(), targetFolder);
80         }
81         if (packageName != null) {
82             packageName = packageName.replaceAll("/", ".");
83         }
84         return packageName+"";
85     }
86     
87     public String JavaDoc getBeanClassName(String JavaDoc wsName) {
88         //TO-DO: We should get this from the module
89
//Naming convention for web module is: servicename + Impl
90
//Naming convention for ejb module is: servicename + Bean
91
return wsName + "Impl"; //NOI18N
92
}
93     
94     public String JavaDoc getSEIName(String JavaDoc wsName) {
95         return wsName + "SEI"; //NOI18N
96
}
97     
98     public Bean getDefaultBean() {
99         Bean b = new Bean();
100         b.setCommentData(true);
101         if (genDate == null) {
102             genDate = DateFormat.getDateTimeInstance().format(new Date());
103             genAuthor = System.getProperty("user.name");
104         }
105         b.setCommentDataAuthor(genAuthor); //NOI18N
106
b.setCommentDataDate(genDate);
107         return b;
108     }
109     
110     public String JavaDoc getFullClassName(String JavaDoc pkg, String JavaDoc className) {
111         return (pkg==null||pkg.length()==0)?className:pkg+"."+className; //NOI18N
112
}
113     
114     public String JavaDoc generateClass(String JavaDoc template, Bean genData, FileObject pkg, boolean open) throws IOException JavaDoc {
115         String JavaDoc clsName = genData.getClassnameName();
116         clsName = FileUtil.findFreeFileName(pkg, clsName, "java"); //NOI18N
117
genData.setClassnameName(clsName);
118         generateClass(template, pkg, clsName, getStreamSource(genData), open);
119         return clsName;
120     }
121     
122     public String JavaDoc generateClass(String JavaDoc template, FileObject pkg, String JavaDoc clsName, String JavaDoc inputXml, boolean open)
123     throws IOException JavaDoc {
124         clsName = FileUtil.findFreeFileName(pkg, clsName, "java"); //NOI18N
125
generateClass(template, pkg, clsName, getStreamSource(inputXml), open);
126         return clsName;
127     }
128     
129     public FileObject generateWSDL(String JavaDoc template, String JavaDoc wsName, String JavaDoc soapBinding, String JavaDoc portTypeName, FileObject folder, String JavaDoc wsdlName, StreamSource JavaDoc source) throws IOException JavaDoc {
130         return generateWSDL(template, wsName, soapBinding, portTypeName, folder, null, wsdlName, source);
131     }
132     
133     public FileObject generateWSDL(String JavaDoc template, String JavaDoc wsName, String JavaDoc soapBinding, String JavaDoc portTypeName, FileObject folder, FileObject originalFolder, String JavaDoc wsdlName, StreamSource JavaDoc source) throws IOException JavaDoc
134     {
135         FileObject wsdlFile = folder.createData(FileUtil.findFreeFileName(folder, wsdlName, "wsdl"), "wsdl"); //NOI18N
136
FileLock fl = null;
137         OutputStream JavaDoc os = null;
138         try {
139             fl = wsdlFile.lock();
140             os = new BufferedOutputStream JavaDoc(wsdlFile.getOutputStream(fl));
141             Transformer JavaDoc transformer = getTransformer(template);
142             transformer.setParameter("WSNAME", wsName);
143             transformer.setParameter("SOAPBINDING", soapBinding);
144             if (portTypeName != null) {
145                 transformer.setParameter("PORTTYPENAME", portTypeName);
146             } else {
147                 return wsdlFile;
148             }
149             transformer.transform(source, new StreamResult JavaDoc(os));
150             os.close();
151         }
152         catch(TransformerConfigurationException JavaDoc tce) {
153             IOException JavaDoc ioe = new IOException JavaDoc();
154             ioe.initCause(tce);
155             throw ioe;
156         }
157         catch(TransformerException JavaDoc te) {
158             IOException JavaDoc ioe = new IOException JavaDoc();
159             ioe.initCause(te);
160             throw ioe;
161         }
162         finally {
163             if(os != null) {
164                 os.close();
165             }
166             if(fl != null) {
167                 fl.releaseLock();
168             }
169         }
170         // Also copy the importing wsdl/schema files
171
copyImportedSchemas(originalFolder,folder,wsdlFile);
172         return wsdlFile;
173     }
174     
175     public void generateClass(String JavaDoc template, FileObject pkg, String JavaDoc clsName, StreamSource JavaDoc source, boolean open) throws IOException JavaDoc {
176         FileObject cFile = pkg.createData(clsName,"java"); //NOI18N
177
FileLock fl = null;
178         OutputStream JavaDoc os = null;
179         Writer JavaDoc w = null;
180         try {
181             fl = cFile.lock();
182             os = new BufferedOutputStream JavaDoc(cFile.getOutputStream(fl));
183             getTransformer(template).transform(source, new StreamResult JavaDoc(new OutputStreamWriter JavaDoc(os)));
184             os.close();
185             fl.releaseLock();
186             DataObject dobj = DataObject.find(cFile);
187             final EditorCookie ec = (EditorCookie) dobj.getCookie(EditorCookie.class);
188             Document JavaDoc d = ec.openDocument();
189             try {
190                 String JavaDoc fullText = d.getText(0,d.getLength());
191                 IndentEngine javaIndent = IndentEngine.find(d);
192                 StringWriter JavaDoc writer = new StringWriter JavaDoc(d.getLength());
193                 w = javaIndent.createWriter(d, 0, writer);
194                 w.write(fullText);
195                 w.close();
196                 d.remove(0, d.getLength());
197                 d.insertString(0, writer.getBuffer().toString(), null);
198                 ec.saveDocument();
199             } catch (BadLocationException JavaDoc ble) {
200                 ErrorManager.getDefault().notify(ble);
201             }
202             if (open) {
203                 RequestProcessor.getDefault().post(new Runnable JavaDoc() {
204                     public void run() {
205                         ec.open();
206                     }
207                 },1000);
208             }
209         } catch (TransformerConfigurationException JavaDoc tce) {
210             IOException JavaDoc ioe = new IOException JavaDoc();
211             ioe.initCause(tce);
212             throw ioe;
213         } catch (TransformerException JavaDoc te) {
214             IOException JavaDoc ioe = new IOException JavaDoc();
215             ioe.initCause(te);
216             throw ioe;
217         } finally {
218             if (os != null) {
219                 os.close();
220             }
221             if (w != null) {
222                 w.close();
223             }
224             if(fl != null) {
225                 fl.releaseLock();
226             }
227         }
228     }
229     
230     public String JavaDoc getBaseName(String JavaDoc fullClassName) {
231         return fullClassName.substring(fullClassName.lastIndexOf('.')+1); //NOI18N
232
}
233     
234     private Transformer JavaDoc getTransformer(String JavaDoc template) throws TransformerConfigurationException JavaDoc {
235         Templates JavaDoc t = (Templates JavaDoc) templateCache.get(template);
236         if (t != null) {
237             return t.newTransformer();
238         }
239         InputStream JavaDoc is = new BufferedInputStream JavaDoc(getClass().getResourceAsStream(template));
240         TransformerFactory JavaDoc transFactory = TransformerFactory.newInstance();
241         transFactory.setURIResolver(new URIResolver JavaDoc() {
242             public Source JavaDoc resolve(String JavaDoc href, String JavaDoc base)
243             throws TransformerException JavaDoc {
244                 InputStream JavaDoc is = getClass().getResourceAsStream(
245                 TEMPLATE_BASE + href.substring(href.lastIndexOf('/')+1));
246                 if (is == null) {
247                     return null;
248                 }
249                 
250                 return new StreamSource JavaDoc(is);
251             }
252         });
253         t = transFactory.newTemplates(new StreamSource JavaDoc(is));
254         templateCache.put(template, t);
255         return t.newTransformer();
256     }
257     
258     private StreamSource JavaDoc getStreamSource(Bean genData) throws IOException JavaDoc {
259         ByteArrayOutputStream JavaDoc bos = new ByteArrayOutputStream JavaDoc();
260         try {
261             genData.write(bos);
262         } finally {
263             bos.close();
264         }
265         return new StreamSource JavaDoc(new ByteArrayInputStream JavaDoc(bos.toByteArray()));
266     }
267     
268     private StreamSource JavaDoc getStreamSource(String JavaDoc xml) throws IOException JavaDoc {
269         StringReader JavaDoc sr = new StringReader JavaDoc(xml);
270         return new StreamSource JavaDoc(sr);
271     }
272     
273     /** Static method to identify wsdl/schema files to import
274     */

275     static List /*String*/ getSchemaNames(FileObject fo, boolean fromWsdl) {
276             List result = null;
277             try {
278                     SAXParserFactory JavaDoc factory = SAXParserFactory.newInstance();
279                     factory.setNamespaceAware(true);
280                     SAXParser JavaDoc saxParser = factory.newSAXParser();
281                     ImportsHandler handler= (fromWsdl?(ImportsHandler)new WsdlImportsHandler():(ImportsHandler)new SchemaImportsHandler());
282                     saxParser.parse(new InputSource JavaDoc(fo.getInputStream()), (DefaultHandler JavaDoc)handler);
283                     result = handler.getSchemaNames();
284             } catch(ParserConfigurationException JavaDoc ex) {
285                     // Bogus WSDL, return null.
286
} catch(SAXException JavaDoc ex) {
287                     // Bogus WSDL, return null.
288
} catch(IOException JavaDoc ex) {
289                     // Bogus WSDL, return null.
290
}
291
292             return result;
293     }
294     
295     private static interface ImportsHandler {
296         public List getSchemaNames();
297     }
298     
299     private static class WsdlImportsHandler extends DefaultHandler JavaDoc implements ImportsHandler {
300         
301         private static final String JavaDoc W3C_WSDL_SCHEMA = "http://schemas.xmlsoap.org/wsdl"; // NOI18N
302
private static final String JavaDoc W3C_WSDL_SCHEMA_SLASH = "http://schemas.xmlsoap.org/wsdl/"; // NOI18N
303

304         private List schemaNames;
305         
306         private boolean insideSchema;
307         
308         WsdlImportsHandler() {
309             schemaNames = new ArrayList();
310         }
311         
312         public void startElement(String JavaDoc uri, String JavaDoc localname, String JavaDoc qname, Attributes JavaDoc attributes) throws SAXException JavaDoc {
313             if(W3C_WSDL_SCHEMA.equals(uri) || W3C_WSDL_SCHEMA_SLASH.equals(uri)) {
314                 if("types".equals(localname)) { // NOI18N
315
insideSchema=true;
316                 }
317                 if("import".equals(localname)) { // NOI18N
318
String JavaDoc wsdlLocation = attributes.getValue("location"); //NOI18N
319
if (wsdlLocation!=null && wsdlLocation.indexOf("/")<0 && wsdlLocation.endsWith(".wsdl")) { //NOI18N
320
schemaNames.add(wsdlLocation);
321                     }
322                 }
323             }
324             if(insideSchema && "import".equals(localname)) { // NOI18N
325
String JavaDoc schemaLocation = attributes.getValue("schemaLocation"); //NOI18N
326
if (schemaLocation!=null && schemaLocation.indexOf("/")<0 && schemaLocation.endsWith(".xsd")) { //NOI18N
327
schemaNames.add(schemaLocation);
328                 }
329             }
330         }
331         
332         public void endElement(String JavaDoc uri, String JavaDoc localname, String JavaDoc qname) throws SAXException JavaDoc {
333             if(W3C_WSDL_SCHEMA.equals(uri) || W3C_WSDL_SCHEMA_SLASH.equals(uri)) {
334                 if("types".equals(localname)) { // NOI18N
335
insideSchema=false;
336                 }
337             }
338         }
339         
340         public List/*String*/ getSchemaNames() {
341             return schemaNames;
342         }
343     }
344     
345     private static class SchemaImportsHandler extends DefaultHandler JavaDoc implements ImportsHandler {
346         
347         private List schemaNames;
348      
349         SchemaImportsHandler() {
350             schemaNames = new ArrayList();
351         }
352         
353         public void startElement(String JavaDoc uri, String JavaDoc localname, String JavaDoc qname, Attributes JavaDoc attributes) throws SAXException JavaDoc {
354             if("import".equals(localname)) { // NOI18N
355
String JavaDoc schemaLocation = attributes.getValue("schemaLocation"); //NOI18N
356
if (schemaLocation!=null && schemaLocation.indexOf("/")<0 && schemaLocation.endsWith(".xsd")) { //NOI18N
357
schemaNames.add(schemaLocation);
358                 }
359             }
360         }
361         
362         public List/*String*/ getSchemaNames() {
363             return schemaNames;
364         }
365     }
366     
367     /* Recursive method that copies all necessary wsdl/schema files imported by FileObject to target folder
368      */

369     private synchronized void copyImportedSchemas(FileObject resourceFolder, FileObject targetFolder, FileObject fo) throws IOException JavaDoc {
370         List schemaNames = getSchemaNames(fo,"wsdl".equals(fo.getExt())); //NOI18N
371
Iterator it = schemaNames.iterator();
372         while (it.hasNext()) {
373             String JavaDoc schemaName = (String JavaDoc)it.next();
374             FileObject schemaFile = resourceFolder.getFileObject(schemaName);
375             if (schemaFile!=null) {
376                 FileObject target = targetFolder.getFileObject(schemaFile.getName(),schemaFile.getExt());
377                 if(target != null) {
378                     target.delete();
379                 }
380                 //copy the schema file
381
FileObject copy = schemaFile.copy(targetFolder,schemaFile.getName(),schemaFile.getExt());
382                 copyImportedSchemas(resourceFolder, targetFolder, copy);
383             }
384         }
385     }
386     
387 }
388
389
Popular Tags