KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > modules > websvc > jaxrpc > client > wizard > ClientBuilder


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.jaxrpc.client.wizard;
21
22 import java.io.*;
23 import java.net.URI JavaDoc;
24 import java.net.URISyntaxException JavaDoc;
25 import java.net.URL JavaDoc;
26 import java.util.*;
27
28 import javax.xml.parsers.SAXParser JavaDoc;
29 import javax.xml.parsers.SAXParserFactory JavaDoc;
30 import javax.xml.parsers.ParserConfigurationException JavaDoc;
31 import javax.xml.transform.*;
32
33 import javax.xml.transform.stream.StreamResult JavaDoc;
34 import javax.xml.transform.stream.StreamSource JavaDoc;
35 import org.netbeans.api.java.classpath.ClassPath;
36 import org.netbeans.api.java.project.JavaProjectConstants;
37 import org.netbeans.api.progress.ProgressHandle;
38 import org.netbeans.api.project.ProjectUtils;
39 import org.netbeans.api.project.SourceGroup;
40 import org.netbeans.modules.j2ee.deployment.devmodules.api.J2eeModule;
41 import org.netbeans.modules.websvc.api.client.ClientStubDescriptor;
42 import org.netbeans.modules.websvc.jaxrpc.PortInformation;
43 import org.netbeans.modules.websvc.jaxrpc.Utilities;
44 import org.netbeans.modules.websvc.wsdl.WsdlDataObject;
45 import org.xml.sax.Attributes JavaDoc;
46 import org.xml.sax.InputSource JavaDoc;
47 import org.xml.sax.SAXException JavaDoc;
48 import org.xml.sax.helpers.DefaultHandler JavaDoc;
49
50 import org.openide.ErrorManager;
51 import org.openide.NotifyDescriptor;
52 import org.openide.DialogDisplayer;
53 import org.openide.execution.ExecutorTask;
54 import org.openide.util.Lookup;
55 import org.openide.util.NbBundle;
56 import org.openide.filesystems.FileLock;
57 import org.openide.filesystems.FileObject;
58 import org.openide.filesystems.FileSystem;
59 import org.openide.filesystems.FileUtil;
60 import org.openide.filesystems.FileAlreadyLockedException;
61
62 import org.netbeans.api.project.Project;
63 import org.netbeans.spi.project.support.ant.GeneratedFilesHelper;
64 import org.apache.tools.ant.module.api.support.ActionUtils;
65
66 import org.netbeans.modules.j2ee.dd.api.web.DDProvider;
67 import org.netbeans.modules.j2ee.dd.api.common.ServiceRef;
68 import org.netbeans.modules.j2ee.dd.api.common.PortComponentRef;
69 import org.netbeans.modules.j2ee.dd.api.common.RootInterface;
70 import org.netbeans.modules.j2ee.dd.api.common.CommonDDBean;
71 import org.netbeans.modules.j2ee.dd.api.common.NameAlreadyUsedException;
72 import org.netbeans.modules.j2ee.deployment.devmodules.spi.J2eeModuleProvider;
73
74 import org.netbeans.modules.websvc.api.registry.WebServicesRegistryView;
75 import org.netbeans.modules.websvc.api.client.WebServicesClientSupport;
76 import org.netbeans.modules.websvc.api.webservices.StubDescriptor;
77 import org.netbeans.modules.websvc.wsdl.config.WsCompileConfigDataObject;
78 import org.netbeans.modules.websvc.wsdl.config.PortInformationHandler;
79
80
81 /**
82  *
83  * @author Peter Williams
84  */

85 public class ClientBuilder {
86     
87     private static final String JavaDoc TEMPLATE_BASE = "/org/netbeans/modules/websvc/core/client/resources/"; //NOI18N
88

89     // User/project specified inputs
90
private Project project;
91     private WebServicesClientSupport projectSupport;
92     private FileObject wsdlSource;
93     private String JavaDoc packageName;
94     private String JavaDoc sourceUrl;
95     private ClientStubDescriptor stubDescriptor;
96
97     // Intermediate processing
98
private FileObject wsdlTarget;
99     private FileObject configFile;
100     private List /*FileObject*/ importedWsdlList;
101     
102     public ClientBuilder(Project project, WebServicesClientSupport support, FileObject wsdlSource, String JavaDoc packageName, String JavaDoc sourceUrl, ClientStubDescriptor sd) {
103         this.project = project;
104         this.projectSupport = support;
105         this.wsdlSource = wsdlSource;
106         this.packageName = packageName;
107         this.sourceUrl = sourceUrl;
108         this.stubDescriptor = sd;
109         importedWsdlList = new ArrayList();
110     }
111
112     /** If the service or port name begins with a lower case letter, the class
113      * name for the corresponding JAXRPC class will still begin with uppercase
114      * so we need to adjust the name we use accordingly.
115      *
116      * See also ...websvc.core.client.actions.InvokeOperationAction.
117      */

118     private static String JavaDoc classFromName(final String JavaDoc name) {
119         String JavaDoc result = name;
120         
121         if(name.length() > 0 && !Character.isUpperCase(name.charAt(0))) {
122             StringBuffer JavaDoc buf = new StringBuffer JavaDoc(name);
123             buf.setCharAt(0, Character.toUpperCase(name.charAt(0)));
124             result = buf.toString();
125         }
126         
127         return result;
128     }
129
130     public Set/*FileObject*/ generate(final ProgressHandle handle) {
131         Set result = Collections.EMPTY_SET;
132
133         try {
134             SourceGroup[] sourceGroups = ProjectUtils.getSources(project).getSourceGroups(
135                                     JavaProjectConstants.SOURCES_TYPE_JAVA);
136             
137             ClassPath classPath = ClassPath.getClassPath(sourceGroups[0].getRootFolder(),ClassPath.COMPILE);
138             FileObject wscompileFO = classPath.findResource("com/sun/xml/rpc/tools/ant/Wscompile.class"); //NOI18N
139
if (wscompileFO==null) return result;
140             
141             handle.progress(NbBundle.getMessage(ClientBuilder.class, "MSG_WizAddToRegistry"));
142             
143             // !PW Move step 3 to the beginning to avoid having to synchronize the
144
// web service registry with the soon-to-be-created client node.
145

146             // 3. Find services in registry (add if necessary) -- DONE
147
WebServicesRegistryView registryView = (WebServicesRegistryView) Lookup.getDefault().lookup(WebServicesRegistryView.class);
148             registryView.registerService(wsdlSource, true);
149             
150             
151             handle.progress(NbBundle.getMessage(ClientBuilder.class, "MSG_WizParsingWSDL"),20);
152             
153             PortInformationHandler handler = new PortInformationHandler();
154             try {
155                 parse (wsdlSource, handler);
156             } catch(ParserConfigurationException JavaDoc ex) {
157                 ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, ex);
158                 String JavaDoc mes = NbBundle.getMessage(ClientBuilder.class, "ERR_WsdlParseFailure", ex.getMessage()); // NOI18N
159
NotifyDescriptor desc = new NotifyDescriptor.Message(mes, NotifyDescriptor.Message.ERROR_MESSAGE);
160                 DialogDisplayer.getDefault().notify(desc);
161                 return result;
162             } catch(SAXException JavaDoc ex) {
163                 ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, ex);
164                 String JavaDoc mes = NbBundle.getMessage(ClientBuilder.class, "ERR_WsdlParseFailure", ex.getMessage()); // NOI18N
165
NotifyDescriptor desc = new NotifyDescriptor.Message(mes, NotifyDescriptor.Message.ERROR_MESSAGE);
166                 DialogDisplayer.getDefault().notify(desc);
167                 return result;
168             }
169             
170             handle.progress(NbBundle.getMessage(ClientBuilder.class, "MSG_WizCopyingWSDL"),35);
171             
172             // 1. Copy wsdl file to wsdl folder -- DONE
173
final FileObject wsdlFolder = projectSupport.getWsdlFolder(true);
174
175             // First ensure neither the target wsdl or -config.xml files exist.
176
FileObject target = wsdlFolder.getFileObject(wsdlSource.getName(), WsdlDataObject.WSDL_EXTENSION);
177             if(target != null) {
178                 target.delete();
179             }
180             target = wsdlFolder.getFileObject(wsdlSource.getName() + WsCompileConfigDataObject.WSCOMPILE_CONFIG_FILENAME_SUFFIX, "xml"); // NOI18N
181
if(target != null) {
182                 target.delete();
183             }
184             
185              // Now copy the wsdl file.
186
if (handler.isServiceNameConflict()) {
187                 wsdlTarget = generateWSDL(wsdlFolder, wsdlSource.getName() , new StreamSource JavaDoc(wsdlSource.getInputStream()));
188             } else {
189                 wsdlTarget = wsdlSource.copy(wsdlFolder, wsdlSource.getName(), WsdlDataObject.WSDL_EXTENSION);
190             }
191             
192             // Also recursively copy the imported wsdl/schema files
193
handle.progress(NbBundle.getMessage(ClientBuilder.class, "MSG_WizCopyingSchemas"),40);
194             copyImportedSchemas(wsdlSource.getParent(),wsdlFolder,wsdlTarget);
195             
196             handle.progress(NbBundle.getMessage(ClientBuilder.class, "MSG_WizProcessingWSDL"),45);
197             
198             // 2. Generate config file for WSCompile -- DONE
199
File wsdlAsFile = FileUtil.toFile(wsdlTarget);
200
201             if(wsdlAsFile != null) {
202                 final String JavaDoc wsdlConfigEntry = "\t<wsdl location=\"file:@CONFIG_ABSOLUTE_PATH@/" + wsdlAsFile.getName() + "\" packageName=\"" + packageName + "\"/>"; // NOI81N
203
FileSystem fs = wsdlFolder.getFileSystem();
204                 fs.runAtomicAction(new FileSystem.AtomicAction() {
205                     public void run() throws IOException {
206                         configFile = wsdlFolder.createData(wsdlTarget.getName() + WsCompileConfigDataObject.WSCOMPILE_CONFIG_FILENAME_SUFFIX, "xml"); // NOI18N
207
FileLock configLock = configFile.lock();
208
209                         // !PW FIXME this should come from a parameterized registered template
210
try {
211                             PrintWriter configWriter = new PrintWriter(configFile.getOutputStream(configLock));
212
213                             try {
214                                 configWriter.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); // NOI18N
215
configWriter.println("<configuration xmlns=\"http://java.sun.com/xml/ns/jax-rpc/ri/config\">"); // NOI18N
216
configWriter.println(wsdlConfigEntry);
217                                 configWriter.println("</configuration>"); // NOI18N
218
} finally {
219                                 configWriter.close();
220                             }
221                         } finally {
222                             configLock.releaseLock();
223                         }
224                     }
225                 });
226             } else {
227                 // Can't get File object for wsdl file, we're screwed.
228
String JavaDoc mes = NbBundle.getMessage(ClientBuilder.class, "ERR_CannotOpenWsdlFile", wsdlTarget.getNameExt()); // NOI18N
229
NotifyDescriptor desc = new NotifyDescriptor.Message(mes, NotifyDescriptor.Message.ERROR_MESSAGE);
230                 DialogDisplayer.getDefault().notify(desc);
231                 return result;
232             }
233
234             // WSDL/Config file objects are what we return.
235
// !PW per Jiri (HIE), we don't want any files opened when a client is added.
236
// so don't return anything from the wizard.
237
// result.add(wsdlTarget);
238
// result.add(configFile);
239

240             // 3. Find services in registry (add if necessary) -- DONE
241
// !PW FIXME do we want to notify the user if registration fails?
242
// How does the registry view communicate the difference between "already registered"
243
// and "failure during registration" (Since the former is irrelevant.)
244
// WebServicesRegistryView registryView = (WebServicesRegistryView) Lookup.getDefault().lookup(WebServicesRegistryView.class);
245
// registryView.registerService(wsdlTarget, false);
246

247             // Invoke SAX parser on the WSDL to extract list of port bindings
248
//
249
// !PW Redo this so that this information is retrieved from the WSDL node
250
// (which is possibly still in the process of being created, so be careful.
251
//
252

253             // use all imported wsdl files to get the information about WS (Port Info, Binding Info)
254
List wsdlLocationsList = handler.getImportedSchemas();
255             if (wsdlLocationsList.size()>0 && handler.getServices().size()>0 && handler.getEntirePortList().size()>0) {
256                 handler = new PortInformationHandler(handler.getTargetNamespace(),handler.getServices(),handler.getEntirePortList(),handler.getBindings(), wsdlLocationsList);
257                 Iterator it = wsdlLocationsList.iterator();
258                 while (it.hasNext()) {
259                     String JavaDoc wsdlLocation = (String JavaDoc)it.next();
260                     try {
261                         if (wsdlLocation.indexOf("/")<0) { //local
262
FileObject wsdlFo = wsdlFolder.getFileObject(wsdlLocation);
263                             if (wsdlFo!=null && importedWsdlList.contains(wsdlFo))
264                                 parse (wsdlFo, handler);
265                         } else { // remote
266
URL JavaDoc wsdlURL = new URL JavaDoc(wsdlLocation);
267                             parse (wsdlURL, handler);
268                         }
269                         
270                     } catch(ParserConfigurationException JavaDoc ex) {
271                         ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, ex);
272                         String JavaDoc mes = NbBundle.getMessage(ClientBuilder.class, "ERR_WsdlParseFailure", ex.getMessage()); // NOI18N
273
NotifyDescriptor desc = new NotifyDescriptor.Message(mes, NotifyDescriptor.Message.ERROR_MESSAGE);
274                         DialogDisplayer.getDefault().notify(desc);
275                         return result;
276                     } catch(SAXException JavaDoc ex) {
277                         ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, ex);
278                         String JavaDoc mes = NbBundle.getMessage(ClientBuilder.class, "ERR_WsdlParseFailure", ex.getMessage()); // NOI18N
279
NotifyDescriptor desc = new NotifyDescriptor.Message(mes, NotifyDescriptor.Message.ERROR_MESSAGE);
280                         DialogDisplayer.getDefault().notify(desc);
281                         return result;
282                     }
283                 }
284             }
285             
286             handle.progress(50);
287             
288             // 4. Add service-ref entry to deployment descriptor -- only performed for JSR109 client stubs
289
if (ClientStubDescriptor.JSR109_CLIENT_STUB.equals(stubDescriptor.getName())) {
290 /** JSR-109 J2EE 1.4 deployment descriptor
291  * <service-ref>
292  * <service-ref-name>service/TemperatureService</service-ref-name>
293  * "service/" + [name attribute of service field from wsdl]
294  * <service-interface>temperature.TemperatureService</service-interface>
295  * [interface package].[service classname -- name attribute of service field from wsdl]
296  * <wsdl-file>WEB-INF/wsdl/TemperatureService.wsdl</wsdl-file>
297  * [relative path from root of deployed module of wsdl file]
298  * <jaxrpc-mapping-file>WEB-INF/temperature-mapping.xml</jaxrpc-mapping-file>
299  * [relative path from root of deployed module of mapping file]
300  * <port-component-ref>
301  * <service-endpoint-interface>temperature.TemperaturePortType</service-endpoint-interface>
302  * [interface package].[service endpoint classname -- name attribute of porttype field from wsdl]
303  * </port-component-ref>
304  * </service-ref>
305  */

306                 handle.progress(NbBundle.getMessage(ClientBuilder.class, "MSG_WizUpdatingDD"));
307                 
308                 // Make sure server specific support is available.
309
J2eeModuleProvider j2eeMP = (J2eeModuleProvider) project.getLookup ().lookup(J2eeModuleProvider.class);
310                 j2eeMP.getConfigSupport().ensureConfigurationReady();
311
312                 //get correct top folder where wsdl and mapping file are stored
313
// WEB-INF for webapp, META-INF otherwise (ejb, appclient, connector(?))
314
String JavaDoc prefix = J2eeModule.WAR.equals(j2eeMP.getJ2eeModule().getModuleType())
315                     ? "WEB-INF/" //NOI18N
316
: "META-INF/"; //NOI18N
317

318                 // Get deployment descriptor (web.xml or ejbjar.xml)
319
// Create service ref
320
// FileObject ddFO = projectSupport.getDeploymentDescriptor();
321

322                 // If we get null for the deployment descriptor, ignore this step.
323
// if(ddFO != null) {
324
// RootInterface rootDD = DDProvider.getDefault().getDDRoot(ddFO);
325

326                     // Add a service ref for each service in the WSDL file.
327
String JavaDoc [] serviceNames = handler.getServiceNames();
328                     for(int si = 0; si < serviceNames.length; si++) {
329                         String JavaDoc serviceName = serviceNames[si];
330
331                         PortInformation.ServiceInfo serviceInfo = handler.getServiceInfo(serviceName);
332                         List portList = serviceInfo.getPorts();
333
334                         if (handler.isServiceNameConflict()) serviceName+="_Service"; //NOI18N
335
try {
336                             serviceName = Utilities.removeSpacesFromServiceName(serviceName);
337                             String JavaDoc ddServiceName = "service/" + serviceName; // NOI18N
338
String JavaDoc fullyQualifiedServiceName = packageName + "." + classFromName(serviceName); // NOI18N
339
String JavaDoc relativeWsdlPath = prefix + "wsdl/" + wsdlTarget.getNameExt(); // NOI18N !PW FIXME get relative path to WSDL folder from archive root
340
String JavaDoc relativeMappingPath = prefix + wsdlTarget.getName() + "-mapping.xml"; // NOI18N
341

342                             List seiList = new ArrayList();
343                             
344                             for (int pi = 0; pi < portList.size(); pi++) {
345                                 PortInformation.PortInfo portInfo = (PortInformation.PortInfo) portList.get(pi);
346                                 String JavaDoc portTypeName = portInfo.getPortType();
347                                 if (portTypeName!=null) seiList.add(packageName + "." + classFromName(portTypeName)); //NOI18N
348
}
349                             
350                             String JavaDoc[] portInfoSEI = new String JavaDoc[seiList.size()];
351                             seiList.toArray(portInfoSEI);
352                             
353                             projectSupport.addServiceClientReference(ddServiceName,
354                                                                     fullyQualifiedServiceName,
355                                                                     relativeWsdlPath,
356                                                                     relativeMappingPath,
357                                                                     portInfoSEI);
358                             
359 // ServiceRef serviceRef = (ServiceRef) rootDD.findBeanByName("ServiceRef", "ServiceRefName", ddServiceName); // NOI18N
360
// if(serviceRef == null) {
361
// serviceRef = (ServiceRef) rootDD.addBean("ServiceRef", // NOI18N
362
// new String [] { /* property list */
363
// "ServiceRefName", // NOI18N
364
// "ServiceInterface", // NOI18N
365
// "WsdlFile", // NOI18N
366
// "JaxrpcMappingFile" // NOI18N
367
// },
368
// new String [] { /* property values */
369
// // service name
370
// ddServiceName,
371
// // interface package . service name
372
// fullyQualifiedServiceName,
373
// // web doc base / wsdl folder / wsdl file name
374
// relativeWsdlPath,
375
// // web doc base / mapping file name
376
// relativeMappingPath
377
// },
378
// "ServiceRefName"); // NOI18N
379
// } else {
380
// serviceRef.setServiceInterface(fullyQualifiedServiceName);
381
// serviceRef.setWsdlFile(new URI(relativeWsdlPath));
382
// serviceRef.setJaxrpcMappingFile(relativeMappingPath);
383
// }
384
//
385
// PortComponentRef [] portRefArray = new PortComponentRef [portList.size()];
386
// for(int pi = 0; pi < portRefArray.length; pi++) {
387
// PortInformationHandler.PortInfo portInfo = (PortInformationHandler.PortInfo) portList.get(pi);
388
// portRefArray[pi] = (PortComponentRef) serviceRef.createBean("PortComponentRef"); // NOI18N
389
// portRefArray[pi].setServiceEndpointInterface(packageName + "." + classFromName(portInfo.getPortType())); // NOI18N
390
// }
391
//
392
// serviceRef.setPortComponentRef(portRefArray);
393
} catch(ClassCastException JavaDoc ex) {
394                             // Programmer error - mistyped object name.
395
ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, ex);
396                         }
397                     }
398
399                     // This also saves server specific configuration, if necessary.
400
// rootDD.write(ddFO);
401
// } else {
402
// // !PW FIXME JSR-109 stub type, but no deployment descriptor returned.
403
// // We should issue an error about this.
404
// }
405
}
406             
407             // Final steps are performed by the project support object.
408
// 5. Add interface source directory to code completion path
409
// 6. Add properties to drive new entry in build script -- DONE
410
// 7. Add WS libraries to project build path -- DONE
411
// 8. Force build script regeneration -- DONE
412

413             handle.progress(NbBundle.getMessage(ClientBuilder.class, "MSG_WizUpdatingBuildScript"),65);
414             Set features = handler.getWscompileFeatures();
415             String JavaDoc[] wscompileFeatures = new String JavaDoc[features.size()];
416             features.toArray(wscompileFeatures);
417             projectSupport.addServiceClient(wsdlTarget.getName(), packageName, sourceUrl, configFile, stubDescriptor, wscompileFeatures);
418             
419             // 9. Execute wscompile script for the new client (mostly to populate for code completion.
420
handle.progress(NbBundle.getMessage(ClientBuilder.class, "MSG_WizGenerateClient"),80);
421             
422             String JavaDoc targetName = wsdlTarget.getName() + "-client-wscompile"; // NOI18N
423
FileObject buildFO = findBuildXml();
424             if(buildFO != null) {
425                 ExecutorTask task = ActionUtils.runTarget(buildFO, new String JavaDoc [] { targetName }, null);
426                 task.waitFinished();
427                 if(task.result() != 0){
428                     String JavaDoc mes = NbBundle.getMessage(ClientBuilder.class, "ERR_WsCompileFailed"); // NOI18N
429
NotifyDescriptor desc = new NotifyDescriptor.Message(mes, NotifyDescriptor.Message.ERROR_MESSAGE);
430                     DialogDisplayer.getDefault().notify(desc);
431                 }
432             } else {
433                 String JavaDoc mes = NbBundle.getMessage(ClientBuilder.class, "ERR_NoBuildScript"); // NOI18N
434
NotifyDescriptor desc = new NotifyDescriptor.Message(mes, NotifyDescriptor.Message.ERROR_MESSAGE);
435                 DialogDisplayer.getDefault().notify(desc);
436             }
437
438             project.getProjectDirectory().refresh();
439         } catch(FileAlreadyLockedException ex) {
440             // !PW This should not happen, but if it does...
441
ErrorManager.getDefault().notify(ErrorManager.EXCEPTION, ex);
442         } catch(IOException ex) {
443             ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, ex);
444             String JavaDoc mes = NbBundle.getMessage(ClientBuilder.class, "ERR_ClientIOError", wsdlSource.getNameExt(), ex.getMessage()); // NOI18N
445
NotifyDescriptor desc = new NotifyDescriptor.Message(mes, NotifyDescriptor.Message.ERROR_MESSAGE);
446             DialogDisplayer.getDefault().notify(desc);
447         } finally {
448             handle.progress(95);
449         }
450
451         return result;
452     }
453
454     private FileObject findBuildXml() {
455         return project.getProjectDirectory().getFileObject(GeneratedFilesHelper.BUILD_XML_PATH);
456     }
457     
458     
459     /** Static method to identify wsdl/schema files to import
460     */

461     static List /*String*/ getSchemaNames(FileObject fo, boolean fromWsdl) {
462             List result = null;
463             try {
464                     SAXParserFactory JavaDoc factory = SAXParserFactory.newInstance();
465                     factory.setNamespaceAware(true);
466                     SAXParser JavaDoc saxParser = factory.newSAXParser();
467                     ImportsHandler handler= (fromWsdl?(ImportsHandler)new WsdlImportsHandler():(ImportsHandler)new SchemaImportsHandler());
468                     saxParser.parse(new InputSource JavaDoc(fo.getInputStream()), (DefaultHandler JavaDoc)handler);
469                     result = handler.getSchemaNames();
470             } catch(ParserConfigurationException JavaDoc ex) {
471                     // Bogus WSDL, return null.
472
} catch(SAXException JavaDoc ex) {
473                     // Bogus WSDL, return null.
474
} catch(IOException ex) {
475                     // Bogus WSDL, return null.
476
}
477
478             return result;
479     }
480     
481     private static interface ImportsHandler {
482         public List getSchemaNames();
483     }
484     
485     private static class WsdlImportsHandler extends DefaultHandler JavaDoc implements ImportsHandler {
486         
487         private static final String JavaDoc W3C_WSDL_SCHEMA = "http://schemas.xmlsoap.org/wsdl"; // NOI18N
488
private static final String JavaDoc W3C_WSDL_SCHEMA_SLASH = "http://schemas.xmlsoap.org/wsdl/"; // NOI18N
489

490         private List schemaNames;
491         
492         private boolean insideSchema;
493         
494         WsdlImportsHandler() {
495             schemaNames = new ArrayList();
496         }
497         
498         public void startElement(String JavaDoc uri, String JavaDoc localname, String JavaDoc qname, Attributes JavaDoc attributes) throws SAXException JavaDoc {
499             if(W3C_WSDL_SCHEMA.equals(uri) || W3C_WSDL_SCHEMA_SLASH.equals(uri)) {
500                 if("types".equals(localname)) { // NOI18N
501
insideSchema=true;
502                 }
503                 if("import".equals(localname)) { // NOI18N
504
String JavaDoc wsdlLocation = attributes.getValue("location"); //NOI18N
505
if (wsdlLocation!=null && wsdlLocation.indexOf("/")<0 && wsdlLocation.endsWith(".wsdl")) { //NOI18N
506
schemaNames.add(wsdlLocation);
507                     }
508                 }
509             }
510             if(insideSchema && "import".equals(localname)) { // NOI18N
511
String JavaDoc schemaLocation = attributes.getValue("schemaLocation"); //NOI18N
512
if (schemaLocation!=null && schemaLocation.indexOf("/")<0 && schemaLocation.endsWith(".xsd")) { //NOI18N
513
schemaNames.add(schemaLocation);
514                 }
515             }
516         }
517         
518         public void endElement(String JavaDoc uri, String JavaDoc localname, String JavaDoc qname) throws SAXException JavaDoc {
519             if(W3C_WSDL_SCHEMA.equals(uri) || W3C_WSDL_SCHEMA_SLASH.equals(uri)) {
520                 if("types".equals(localname)) { // NOI18N
521
insideSchema=false;
522                 }
523             }
524         }
525         
526         public List/*String*/ getSchemaNames() {
527             return schemaNames;
528         }
529     }
530     
531     private static class SchemaImportsHandler extends DefaultHandler JavaDoc implements ImportsHandler {
532         
533         private List schemaNames;
534      
535         SchemaImportsHandler() {
536             schemaNames = new ArrayList();
537         }
538         
539         public void startElement(String JavaDoc uri, String JavaDoc localname, String JavaDoc qname, Attributes JavaDoc attributes) throws SAXException JavaDoc {
540             if("import".equals(localname)) { // NOI18N
541
String JavaDoc schemaLocation = attributes.getValue("schemaLocation"); //NOI18N
542
if (schemaLocation!=null && schemaLocation.indexOf("/")<0 && schemaLocation.endsWith(".xsd")) { //NOI18N
543
schemaNames.add(schemaLocation);
544                 }
545             }
546         }
547         
548         public List/*String*/ getSchemaNames() {
549             return schemaNames;
550         }
551     }
552     
553     /* Recursive method that copies all necessary wsdl/schema files imported by FileObject to target folder
554      */

555     private synchronized void copyImportedSchemas(FileObject resourceFolder, FileObject targetFolder, FileObject fo) throws IOException {
556         List schemaNames = getSchemaNames(fo,"wsdl".equals(fo.getExt())); //NOI18N
557
Iterator it = schemaNames.iterator();
558         while (it.hasNext()) {
559             String JavaDoc schemaName = (String JavaDoc)it.next();
560             FileObject schemaFile = resourceFolder.getFileObject(schemaName);
561             if (schemaFile!=null) {
562                 FileObject target = targetFolder.getFileObject(schemaFile.getName(),schemaFile.getExt());
563                 if(target != null) {
564                     FileLock lock = target.lock();
565                     if (lock!=null)
566                         try {
567                             target.delete(lock);
568                         } finally {
569                             lock.releaseLock();
570                         }
571                 }
572                 //copy the schema file
573
FileObject copy = schemaFile.copy(targetFolder,schemaFile.getName(),schemaFile.getExt());
574                 if ("wsdl".equals(schemaFile.getExt())) { //WSDL imports another WSDL
575
importedWsdlList.add(copy);
576                 }
577                 copyImportedSchemas(resourceFolder, targetFolder, copy);
578             } else {
579                 DialogDisplayer.getDefault().notify(
580                         new NotifyDescriptor.Message(NbBundle.getMessage(ClientBuilder.class,"ERR_FileNotFound",schemaName,resourceFolder.getPath()),
581                                                         NotifyDescriptor.ERROR_MESSAGE));
582                 break;
583             }
584         }
585     }
586     
587     private void parse(FileObject fo, PortInformationHandler handler) throws ParserConfigurationException JavaDoc, SAXException JavaDoc, IOException {
588         SAXParserFactory JavaDoc factory = SAXParserFactory.newInstance();
589         factory.setNamespaceAware(true);
590         SAXParser JavaDoc saxParser = factory.newSAXParser();
591         saxParser.parse(fo.getInputStream(), handler);
592     }
593     
594     private void parse(URL JavaDoc url, PortInformationHandler handler) throws ParserConfigurationException JavaDoc, SAXException JavaDoc, IOException {
595         SAXParserFactory JavaDoc factory = SAXParserFactory.newInstance();
596         factory.setNamespaceAware(true);
597         SAXParser JavaDoc saxParser = factory.newSAXParser();
598         try {
599             saxParser.parse(url.openConnection().getInputStream(), handler);
600         } catch (java.net.UnknownHostException JavaDoc ex) {
601             ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, ex);
602             String JavaDoc mes = NbBundle.getMessage(ClientBuilder.class, "ERR_UnknownHost", ex.getMessage()); // NOI18N
603
NotifyDescriptor desc = new NotifyDescriptor.Message(mes, NotifyDescriptor.Message.ERROR_MESSAGE);
604             DialogDisplayer.getDefault().notify(desc);
605         }
606     }
607     
608     private FileObject generateWSDL(FileObject folder, String JavaDoc wsdlName, StreamSource JavaDoc source) throws IOException
609     {
610         FileObject wsdlFile = folder.createData(wsdlName, "wsdl"); //NOI18N
611
FileLock fl = null;
612         OutputStream os = null;
613         try {
614             fl = wsdlFile.lock();
615             os = new BufferedOutputStream(wsdlFile.getOutputStream(fl));
616             Transformer transformer = getTransformer();
617             transformer.transform(source, new StreamResult JavaDoc(os));
618             os.close();
619         }
620         catch(TransformerConfigurationException tce) {
621             IOException ioe = new IOException();
622             ioe.initCause(tce);
623             throw ioe;
624         }
625         catch(TransformerException te) {
626             IOException ioe = new IOException();
627             ioe.initCause(te);
628             throw ioe;
629         }
630         finally {
631             if(os != null) {
632                 os.close();
633             }
634             if(fl != null) {
635                 fl.releaseLock();
636             }
637         }
638         return wsdlFile;
639     }
640     
641     private Transformer getTransformer() throws TransformerConfigurationException {
642         InputStream is = new BufferedInputStream(getClass().getResourceAsStream(TEMPLATE_BASE+"WSDL.xml")); //NOI18N
643
TransformerFactory transFactory = TransformerFactory.newInstance();
644         transFactory.setURIResolver(new URIResolver() {
645             public Source JavaDoc resolve(String JavaDoc href, String JavaDoc base)
646             throws TransformerException {
647                 InputStream is = getClass().getResourceAsStream(
648                 TEMPLATE_BASE + href.substring(href.lastIndexOf('/')+1));
649                 if (is == null) {
650                     return null;
651                 }
652                 
653                 return new StreamSource JavaDoc(is);
654             }
655         });
656         Templates t = transFactory.newTemplates(new StreamSource JavaDoc(is));
657         return t.newTransformer();
658     }
659
660 }
661
Popular Tags