KickJava   Java API By Example, From Geeks To Geeks.

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


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.File JavaDoc;
23 import java.io.IOException JavaDoc;
24 import java.io.OutputStream JavaDoc;
25 import java.net.URL JavaDoc;
26 import java.util.ArrayList JavaDoc;
27 import java.util.Collections JavaDoc;
28 import java.util.HashMap JavaDoc;
29 import java.util.HashSet JavaDoc;
30 import java.util.Iterator JavaDoc;
31 import java.util.List JavaDoc;
32 import java.util.Map JavaDoc;
33 import java.util.Set JavaDoc;
34 import org.netbeans.api.java.classpath.ClassPath;
35 import org.netbeans.api.java.project.JavaProjectConstants;
36 import org.netbeans.api.java.queries.UnitTestForSourceQuery;
37 import org.netbeans.api.progress.ProgressHandle;
38 import org.netbeans.api.progress.ProgressHandleFactory;
39 import org.netbeans.api.project.Project;
40 import org.netbeans.api.project.ProjectUtils;
41 import org.netbeans.api.project.SourceGroup;
42 import org.netbeans.api.project.libraries.Library;
43 import org.netbeans.api.project.libraries.LibraryManager;
44 import org.netbeans.modules.j2ee.deployment.devmodules.api.Deployment;
45 import org.netbeans.modules.j2ee.deployment.devmodules.api.J2eePlatform;
46 import org.netbeans.modules.j2ee.deployment.devmodules.spi.J2eeModuleProvider;
47 import org.netbeans.modules.websvc.api.client.ClientStubDescriptor;
48 import org.netbeans.modules.websvc.api.client.WebServicesClientSupport;
49 import org.netbeans.modules.websvc.api.jaxws.client.JAXWSClientSupport;
50 import org.netbeans.modules.websvc.core.ClientWizardProperties;
51 import org.netbeans.modules.websvc.core.webservices.ui.panels.WebProxySetter;
52 import org.netbeans.modules.websvc.core.WsdlRetriever;
53 import org.netbeans.modules.websvc.core.WsdlRetriever;
54 import org.netbeans.spi.java.project.classpath.ProjectClassPathExtender;
55 import org.openide.DialogDisplayer;
56 import org.openide.ErrorManager;
57 import org.openide.NotifyDescriptor;
58 import org.openide.WizardDescriptor;
59 import org.openide.filesystems.FileAlreadyLockedException;
60 import org.openide.filesystems.FileLock;
61 import org.openide.filesystems.FileObject;
62 import org.openide.filesystems.FileUtil;
63 import org.openide.filesystems.URLMapper;
64 import org.openide.util.NbBundle;
65 import org.openide.util.RequestProcessor;
66 import org.netbeans.modules.j2ee.common.Util;
67 import org.openide.util.Task;
68
69 /**
70  *
71  * @author radko
72  */

73 public class WebServiceClientCreator {
74     
75     private static WebServiceClientCreator instance;
76     private Project project;
77     private WizardDescriptor wiz;
78     
79     private static final boolean DEBUG = false;
80     private static final int JSE_PROJECT_TYPE = 0;
81     private static final int WEB_PROJECT_TYPE = 1;
82     private static final int EJB_PROJECT_TYPE = 2;
83     private static final int CAR_PROJECT_TYPE = 3;
84     
85     /**
86      * Creates a new instance of WebServiceClientCreator
87      */

88     public WebServiceClientCreator(Project project, WizardDescriptor wiz) {
89         this.project = project;
90         this.wiz = wiz;
91     }
92         
93     public Set JavaDoc create() throws IOException JavaDoc {
94         
95         final boolean isJsr109Supported = isJsr109Supported();
96         final boolean isJsr109OldSupported = isJsr109OldSupported();
97         final boolean isJWSDPSupported = isJWSDPSupported();
98         
99         // Use Progress API to display generator messages.
100
final ProgressHandle handle = ProgressHandleFactory.createHandle(NbBundle.getMessage(WebServiceClientCreator.class, "MSG_WizCreateClient")); //NOI18N
101

102         task = new Task(new Runnable JavaDoc() {
103             public void run() {
104                 try {
105                     String JavaDoc jaxVersion = (String JavaDoc) wiz.getProperty(ClientWizardProperties.JAX_VERSION);
106                     if (jaxVersion.equals(ClientWizardProperties.JAX_WS)) {
107                         handle.start();
108                         generate15Client((isJsr109Supported || isJWSDPSupported), handle);
109                     } else {
110                         handle.start(100);
111                         generate14Client(handle);
112                     }
113                 } catch (IOException JavaDoc exc) {
114                     //finish progress bar
115
handle.finish();
116                     
117                     ErrorManager.getDefault().notify(ErrorManager.EXCEPTION, exc);
118                 }
119             }
120         });
121         RequestProcessor.getDefault().post(task);
122         
123         return Collections.EMPTY_SET;
124     }
125     
126     private void generate15Client(boolean isJsr109Platform, ProgressHandle handle) throws IOException JavaDoc {
127         
128         // !PW Get client support from project (from first page of wizard)
129
JAXWSClientSupport jaxWsClientSupport=null;
130         if(project != null) {
131             jaxWsClientSupport = JAXWSClientSupport.getJaxWsClientSupport(project.getProjectDirectory());
132         }
133         if(jaxWsClientSupport == null) {
134             // notify no client support
135
// String mes = MessageFormat.format (
136
// NbBundle.getMessage (WebServiceClientWizardIterator.class, "ERR_WebServiceClientSupportNotFound"),
137
// new Object [] {"Servlet Listener"}); //NOI18N
138
String JavaDoc mes = NbBundle.getMessage(WebServiceClientCreator.class, "ERR_NoWebServiceClientSupport"); // NOI18N
139
NotifyDescriptor desc = new NotifyDescriptor.Message(mes, NotifyDescriptor.Message.ERROR_MESSAGE);
140             DialogDisplayer.getDefault().notify(desc);
141         }
142         
143         String JavaDoc wsdlUrl = (String JavaDoc)wiz.getProperty(ClientWizardProperties.WSDL_DOWNLOAD_URL);
144         String JavaDoc filePath = (String JavaDoc)wiz.getProperty(ClientWizardProperties.WSDL_FILE_PATH);
145         //if (wsdlUrl==null) wsdlUrl = "file:"+(filePath.startsWith("/")?filePath:"/"+filePath); //NOI18N
146
if(wsdlUrl == null){
147             wsdlUrl = FileUtil.toFileObject(new File JavaDoc(filePath)).getURL().toExternalForm();
148         }
149         String JavaDoc packageName = (String JavaDoc)wiz.getProperty(ClientWizardProperties.WSDL_PACKAGE_NAME);
150         if (packageName!=null && packageName.length()==0) packageName=null;
151         jaxWsClientSupport.addServiceClient(getWsdlName(wsdlUrl),wsdlUrl,packageName, isJsr109Platform);
152         
153         handle.finish();
154     }
155     
156     private String JavaDoc getWsdlName(String JavaDoc wsdlUrl) {
157         int ind = wsdlUrl.lastIndexOf("/"); //NOI18N
158
String JavaDoc wsdlName = ind>=0?wsdlUrl.substring(ind+1):wsdlUrl;
159         if (wsdlName.toUpperCase().endsWith("?WSDL")) wsdlName = wsdlName.substring(0,wsdlName.length()-5); //NOI18N
160
ind = wsdlName.lastIndexOf(".wsdl"); //NOI18N
161
if (ind>0) wsdlName = wsdlName.substring(0,ind);
162         // replace special characters with '_'
163
return convertAllSpecialChars(wsdlName);
164     }
165     
166     private String JavaDoc convertAllSpecialChars(String JavaDoc resultStr){
167         StringBuffer JavaDoc sb = new StringBuffer JavaDoc(resultStr);
168         for(int i = 0; i < sb.length(); i++){
169             char c = sb.charAt(i);
170             if( Character.isLetterOrDigit(c) ||
171                     (c == '/') ||
172                     (c == '.') ||
173                     (c == '_') ||
174                     (c == ' ') ||
175                     (c == '-')){
176                 continue;
177             }else{
178                 sb.setCharAt(i, '_');
179             }
180         }
181         return sb.toString();
182     }
183     
184     private void generate14Client(final ProgressHandle handle) throws IOException JavaDoc {
185         // Steps:
186
// 1. invoke wizard to select which service to add a reference to.
187
// How to interpret node input set --
188
// + empty: wizard forces project selection, then service selection
189
// + client node: determine project and start on service page
190
// + wsdl node: would select project, but not service. would also
191
// have to verify that WSDL is fully formed.
192

193         WebServicesClientSupport clientSupport = null;
194         
195         // !PW Get client support from project (from first page of wizard)
196
if(project != null) {
197             clientSupport = WebServicesClientSupport.getWebServicesClientSupport(project.getProjectDirectory());
198         }
199         
200         if(clientSupport == null) {
201             // notify no client support
202
// String mes = MessageFormat.format (
203
// NbBundle.getMessage (WebServiceClientWizardIterator.class, "ERR_WebServiceClientSupportNotFound"),
204
// new Object [] {"Servlet Listener"}); //NOI18N
205
String JavaDoc mes = NbBundle.getMessage(WebServiceClientCreator.class, "ERR_NoWebServiceClientSupport"); // NOI18N
206
NotifyDescriptor desc = new NotifyDescriptor.Message(mes, NotifyDescriptor.Message.ERROR_MESSAGE);
207             DialogDisplayer.getDefault().notify(desc);
208             return;
209         }
210         
211         final byte [] sourceWsdlDownload = (byte []) wiz.getProperty(ClientWizardProperties.WSDL_DOWNLOAD_FILE);
212         final List JavaDoc /*WsdlRetriever.SchemaInfo */ downloadedSchemas = (List JavaDoc) wiz.getProperty(ClientWizardProperties.WSDL_DOWNLOAD_SCHEMAS);
213         String JavaDoc wsdlFilePath = (String JavaDoc) wiz.getProperty(ClientWizardProperties.WSDL_FILE_PATH);
214         String JavaDoc packageName = (String JavaDoc) wiz.getProperty(ClientWizardProperties.WSDL_PACKAGE_NAME);
215         ClientStubDescriptor stubDescriptor = (ClientStubDescriptor) wiz.getProperty(ClientWizardProperties.CLIENT_STUB_TYPE);
216         
217         String JavaDoc sourceUrl;
218         FileObject sourceWsdlFile = null;
219         
220         if(sourceWsdlDownload == null) {
221             // Verify the existence of the source WSDL file and that we can get a file object for it.
222
File JavaDoc normalizedWsdlFilePath = FileUtil.normalizeFile(new File JavaDoc(wsdlFilePath));
223             sourceUrl = normalizedWsdlFilePath.toString();
224             sourceWsdlFile = FileUtil.toFileObject(normalizedWsdlFilePath);
225             
226             if(sourceWsdlFile == null) {
227                 String JavaDoc mes = NbBundle.getMessage(WebServiceClientCreator.class, "ERR_WsdlFileNotFound", normalizedWsdlFilePath); // NOI18N
228
NotifyDescriptor desc = new NotifyDescriptor.Message(mes, NotifyDescriptor.Message.ERROR_MESSAGE);
229                 DialogDisplayer.getDefault().notify(desc);
230                 return;
231             }
232         } else {
233             // create a temporary WSDL file
234
File JavaDoc wsdlFile = new File JavaDoc(System.getProperty("java.io.tmpdir"), wsdlFilePath);
235             if(!wsdlFile.exists()) {
236                 try {
237                     wsdlFile.createNewFile();
238                 } catch(IOException JavaDoc ex) {
239                     String JavaDoc mes = NbBundle.getMessage(WebServiceClientCreator.class, "ERR_UnableToCreateTempFile", wsdlFile.getPath()); // NOI18N
240
NotifyDescriptor desc = new NotifyDescriptor.Message(mes, NotifyDescriptor.Message.ERROR_MESSAGE);
241                     DialogDisplayer.getDefault().notify(desc);
242                     return;
243                 }
244             }
245             
246             sourceUrl = (String JavaDoc) wiz.getProperty(ClientWizardProperties.WSDL_DOWNLOAD_URL);
247             sourceWsdlFile = FileUtil.toFileObject(FileUtil.normalizeFile(wsdlFile));
248             
249             if(sourceWsdlFile != null) {
250                 FileLock wsdlLock = sourceWsdlFile.lock();
251                 
252                 try {
253                     OutputStream JavaDoc out = sourceWsdlFile.getOutputStream(wsdlLock);
254                     try {
255                         out.write(sourceWsdlDownload);
256                         out.flush();
257                     } finally {
258                         if(out != null) {
259                             out.close();
260                         }
261                     }
262                 } finally {
263                     wsdlLock.releaseLock();
264                 }
265             } else {
266                 String JavaDoc mes = NbBundle.getMessage(WebServiceClientCreator.class, "ERR_UnableToCreateTempFile", wsdlFile.getPath()); // NOI18N
267
NotifyDescriptor desc = new NotifyDescriptor.Message(mes, NotifyDescriptor.Message.ERROR_MESSAGE);
268                 DialogDisplayer.getDefault().notify(desc);
269                 return;
270             }
271             
272             // create temporary Schema Files
273
if (downloadedSchemas!=null) {
274                 Iterator JavaDoc it = downloadedSchemas.iterator();
275                 while (it.hasNext()) {
276                     WsdlRetriever.SchemaInfo schemaInfo = (WsdlRetriever.SchemaInfo)it.next();
277                     File JavaDoc schemalFile = new File JavaDoc(System.getProperty("java.io.tmpdir"), schemaInfo.getSchemaName());
278                     try {
279                         schemalFile.createNewFile();
280                     } catch(IOException JavaDoc ex) {
281                         String JavaDoc mes = NbBundle.getMessage(WebServiceClientCreator.class, "ERR_UnableToCreateTempFile", schemalFile.getPath()); // NOI18N
282
NotifyDescriptor desc = new NotifyDescriptor.Message(mes, NotifyDescriptor.Message.ERROR_MESSAGE);
283                         DialogDisplayer.getDefault().notify(desc);
284                         return;
285                     }
286                     FileObject schemaFo = FileUtil.toFileObject(FileUtil.normalizeFile(schemalFile));
287                     if(schemaFo != null) {
288                         FileLock lock = schemaFo.lock();
289                         
290                         try {
291                             OutputStream JavaDoc out = schemaFo.getOutputStream(lock);
292                             try {
293                                 out.write(schemaInfo.getSchemaContent());
294                                 out.flush();
295                             } finally {
296                                 if(out != null) {
297                                     out.close();
298                                 }
299                             }
300                         } finally {
301                             lock.releaseLock();
302                         }
303                     } else {
304                         String JavaDoc mes = NbBundle.getMessage(WebServiceClientCreator.class, "ERR_UnableToCreateTempFile", schemalFile.getPath()); // NOI18N
305
NotifyDescriptor desc = new NotifyDescriptor.Message(mes, NotifyDescriptor.Message.ERROR_MESSAGE);
306                         DialogDisplayer.getDefault().notify(desc);
307                         return;
308                     }
309                 } //end while
310
} // end if
311
} //end else
312

313         // 2. add jax-rpc library if wscompile isnt present
314
SourceGroup[] sgs = getJavaSourceGroups(project);
315         ClassPath classPath = ClassPath.getClassPath(sgs[0].getRootFolder(),ClassPath.COMPILE);
316         
317         FileObject wscompileFO = classPath.findResource("com/sun/xml/rpc/tools/ant/Wscompile.class");
318         if (wscompileFO==null) {
319             // add jax-rpc16 if webservice is not on classpath
320
ProjectClassPathExtender pce = (ProjectClassPathExtender)project.getLookup().lookup(ProjectClassPathExtender.class);
321             Library jaxrpclib = LibraryManager.getDefault().getLibrary("jaxrpc16"); //NOI18N
322
if ((pce!=null) && (jaxrpclib != null)) {
323                 pce.addLibrary(jaxrpclib);
324             }
325         }
326         
327         // sets JVM Proxy Options
328
clientSupport.setProxyJVMOptions(WebProxySetter.getInstance().getProxyHost(),WebProxySetter.getInstance().getProxyPort());
329         
330         // 3. add the service client to the project.
331
// Use Progress API to display generator messages.
332
final ClientBuilder builder = new ClientBuilder(project, clientSupport, sourceWsdlFile, packageName, sourceUrl, stubDescriptor);
333         final FileObject sourceWsdlFileTmp = sourceWsdlFile;
334         
335         org.openide.util.RequestProcessor.getDefault().post(new Runnable JavaDoc() {
336             public void run() {
337                 try {
338                     builder.generate(handle);
339                     
340                     if(sourceWsdlDownload != null) {
341                         // we used a temp file, delete it now.
342
try {
343                             sourceWsdlFileTmp.delete();
344                         } catch(FileAlreadyLockedException ex) {
345                             String JavaDoc mes = NbBundle.getMessage(WebServiceClientCreator.class, "ERR_TempFileLocked", sourceWsdlFileTmp.getNameExt()); // NOI18N
346
NotifyDescriptor desc = new NotifyDescriptor.Message(mes, NotifyDescriptor.Message.ERROR_MESSAGE);
347                             DialogDisplayer.getDefault().notify(desc);
348                         } catch(IOException JavaDoc ex) {
349                             String JavaDoc mes = NbBundle.getMessage(WebServiceClientCreator.class, "ERR_TempFileNotDeleted", sourceWsdlFileTmp.getNameExt()); // NOI18N
350
NotifyDescriptor desc = new NotifyDescriptor.Message(mes, NotifyDescriptor.Message.ERROR_MESSAGE);
351                             DialogDisplayer.getDefault().notify(desc);
352                         }
353                     }
354                     
355                     handle.progress(NbBundle.getMessage(WebServiceClientCreator.class, "MSG_WizDone"),99);
356                 } finally {
357                     handle.finish();
358                 }
359             }
360         });
361     }
362     
363     /**
364      * Returns Java source groups for all source packages in given project.<br>
365      * Doesn't include test packages.
366      *
367      * @param project Project to search
368      * @return Array of SourceGroup. It is empty if any probelm occurs.
369      */

370     static SourceGroup[] getJavaSourceGroups(Project project) {
371         SourceGroup[] sourceGroups = ProjectUtils.getSources(project).getSourceGroups(
372                 JavaProjectConstants.SOURCES_TYPE_JAVA);
373         Set JavaDoc testGroups = getTestSourceGroups(project, sourceGroups);
374         List JavaDoc result = new ArrayList JavaDoc();
375         for (int i = 0; i < sourceGroups.length; i++) {
376             if (!testGroups.contains(sourceGroups[i])) {
377                 result.add(sourceGroups[i]);
378             }
379         }
380         return (SourceGroup[]) result.toArray(new SourceGroup[result.size()]);
381     }
382     
383     private static Set JavaDoc/*<SourceGroup>*/ getTestSourceGroups(Project project, SourceGroup[] sourceGroups) {
384         Map JavaDoc foldersToSourceGroupsMap = createFoldersToSourceGroupsMap(sourceGroups);
385         Set JavaDoc testGroups = new HashSet JavaDoc();
386         for (int i = 0; i < sourceGroups.length; i++) {
387             testGroups.addAll(getTestTargets(sourceGroups[i], foldersToSourceGroupsMap));
388         }
389         return testGroups;
390     }
391     
392     private static List JavaDoc/*<SourceGroup>*/ getTestTargets(SourceGroup sourceGroup, Map JavaDoc foldersToSourceGroupsMap) {
393         final URL JavaDoc[] rootURLs = UnitTestForSourceQuery.findUnitTests(sourceGroup.getRootFolder());
394         if (rootURLs.length == 0) {
395             return new ArrayList JavaDoc();
396         }
397         List JavaDoc result = new ArrayList JavaDoc();
398         List JavaDoc sourceRoots = getFileObjects(rootURLs);
399         for (int i = 0; i < sourceRoots.size(); i++) {
400             FileObject sourceRoot = (FileObject) sourceRoots.get(i);
401             SourceGroup srcGroup = (SourceGroup) foldersToSourceGroupsMap.get(sourceRoot);
402             if (srcGroup != null) {
403                 result.add(srcGroup);
404             }
405         }
406         return result;
407     }
408     
409     private static Map JavaDoc createFoldersToSourceGroupsMap(final SourceGroup[] sourceGroups) {
410         Map JavaDoc result;
411         if (sourceGroups.length == 0) {
412             result = Collections.EMPTY_MAP;
413         } else {
414             result = new HashMap JavaDoc(2 * sourceGroups.length, .5f);
415             for (int i = 0; i < sourceGroups.length; i++) {
416                 SourceGroup sourceGroup = sourceGroups[i];
417                 result.put(sourceGroup.getRootFolder(), sourceGroup);
418             }
419         }
420         return result;
421     }
422     
423     private static List JavaDoc/*<FileObject>*/ getFileObjects(URL JavaDoc[] urls) {
424         List JavaDoc result = new ArrayList JavaDoc();
425         for (int i = 0; i < urls.length; i++) {
426             FileObject sourceRoot = URLMapper.findFileObject(urls[i]);
427             if (sourceRoot != null) {
428                 result.add(sourceRoot);
429             } else {
430                 int severity = ErrorManager.INFORMATIONAL;
431                 if (ErrorManager.getDefault().isNotifiable(severity)) {
432                     ErrorManager.getDefault().notify(severity, new IllegalStateException JavaDoc(
433                             "No FileObject found for the following URL: " + urls[i])); //NOI18N
434
}
435             }
436         }
437         return result;
438     }
439     
440     private J2eePlatform getJ2eePlatform(){
441         J2eeModuleProvider provider = (J2eeModuleProvider) project.getLookup().lookup(J2eeModuleProvider.class);
442         if(provider != null){
443             String JavaDoc serverInstanceID = provider.getServerInstanceID();
444             if(serverInstanceID != null && serverInstanceID.length() > 0) {
445                 return Deployment.getDefault().getJ2eePlatform(serverInstanceID);
446             }
447         }
448         return null;
449     }
450     
451     private boolean isJWSDPSupported(){
452         J2eePlatform j2eePlatform = getJ2eePlatform();
453         if(j2eePlatform != null){
454             return j2eePlatform.isToolSupported(J2eePlatform.TOOL_JWSDP);
455         }
456         return false;
457     }
458     
459     private boolean isJsr109Supported(){
460         J2eePlatform j2eePlatform = getJ2eePlatform();
461         if(j2eePlatform != null){
462             return j2eePlatform.isToolSupported(J2eePlatform.TOOL_JSR109);
463         }
464         return false;
465     }
466     
467     private boolean isJsr109OldSupported(){
468         J2eePlatform j2eePlatform = getJ2eePlatform();
469         if(j2eePlatform != null){
470             return j2eePlatform.isToolSupported(J2eePlatform.TOOL_WSCOMPILE);
471         }
472         return false;
473     }
474
475     /**
476       *
477       * <b>DON'T USE</b>, for tests only
478       */

479     Task task;
480 }
481
Popular Tags