KickJava   Java API By Example, From Geeks To Geeks.

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


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.awt.Component JavaDoc;
23 import java.io.*;
24 import java.util.*;
25 import javax.swing.JComponent JavaDoc;
26 import org.netbeans.api.progress.ProgressHandle;
27 import org.netbeans.api.progress.ProgressHandleFactory;
28 import org.netbeans.api.project.Project;
29 import org.netbeans.api.project.SourceGroup;
30 import org.netbeans.spi.java.project.support.ui.templates.JavaTemplates;
31 import org.netbeans.spi.project.ui.templates.support.Templates;
32 import org.openide.WizardDescriptor;
33 import javax.swing.event.ChangeListener JavaDoc;
34 import org.openide.util.NbBundle;
35 import org.openide.filesystems.FileObject;
36 import org.openide.nodes.Node;
37 import java.net.URI JavaDoc;
38 import org.netbeans.modules.websvc.api.webservices.WebServicesSupport;
39 import org.netbeans.modules.j2ee.common.Util;
40 import java.lang.reflect.Constructor JavaDoc;
41 import org.openide.ErrorManager;
42 import org.openide.DialogDisplayer;
43 import org.openide.NotifyDescriptor;
44 import org.openide.filesystems.FileUtil;
45 import javax.xml.transform.stream.StreamSource JavaDoc;
46 import org.openide.filesystems.FileLock;
47 import org.netbeans.spi.project.support.ant.GeneratedFilesHelper;
48 import org.apache.tools.ant.module.api.support.ActionUtils;
49 import org.openide.execution.ExecutorTask;
50 import org.openide.cookies.EditorCookie;
51 import org.openide.loaders.DataObject;
52 import java.net.MalformedURLException JavaDoc;
53 import java.net.URL JavaDoc;
54 import org.openide.util.RequestProcessor;
55 import org.openide.windows.WindowManager;
56 import java.text.DateFormat JavaDoc;
57 import java.util.Date JavaDoc;
58
59 public class WebServiceWizard implements WizardDescriptor.InstantiatingIterator {
60     public int currentPanel = 0;
61     private WizardDescriptor.Panel firstPanel; //special case: use Java Chooser
62
private WebServiceWizardDescriptor wsPanel;
63     private WizardDescriptor wiz;
64     private Project project;
65     private String JavaDoc wsName;
66     private WebServiceWizardHelper helper;
67     private FileObject wsdlFO;
68
69     // steps are referred to by these indexes into array "stepClassNames" and "steps"
70
private static final int STEP_ENTER_NAME = 0;
71     private static final int STEP_SELECT_EXISTING_CODE = 1;
72
73     // each row in stepPaths gives the path (sequence of panel numbers) of a wizard branch.
74
private static int[][] stepPaths = new int[][]{
75         {STEP_ENTER_NAME},
76         {STEP_ENTER_NAME, STEP_SELECT_EXISTING_CODE},
77         {STEP_ENTER_NAME},
78         {STEP_ENTER_NAME }
79     };
80
81     private static final String JavaDoc STEPNAME_ENTER_NAME=NbBundle.getMessage(WebServiceWizard.class, "LBL_SpecifyWSInfo");
82     private static final String JavaDoc STEPNAME_SELECT_EXISTING_CODE = NbBundle.getMessage(WebServiceWizard.class, "LBL_SelectExistingCode");
83     
84     /*
85     private static final String [] CREATE_WS_STEPS = new String[]{
86         NbBundle.getMessage(WebServiceWizard.class, "LBL_SpecifyWSInfo"),
87         NbBundle.getMessage(WebServiceWizard.class, "LBL_SelectExistingCode")
88     };
89      */

90
91     // step names that correspond to each path above
92
private static final String JavaDoc[][] stepPathNames = new String JavaDoc[][]{
93         {STEPNAME_ENTER_NAME},
94         {STEPNAME_ENTER_NAME, STEPNAME_SELECT_EXISTING_CODE},
95         {STEPNAME_ENTER_NAME},
96         {STEPNAME_ENTER_NAME}
97     };
98
99     //Indexes of each wizard branch stored in stepPaths
100
public static final int PATH_CREATE_FROM_SCRATCH = 0;
101     public static final int PATH_CREATE_FROM_EXISTING_CODE = 1;
102     public static final int PATH_CREATE_FROM_WSDL_FILE = 2;
103     public static final int PATH_CREATE_FROM_WSDL_URL = 3;
104
105     private static int currentWizardBranch = PATH_CREATE_FROM_SCRATCH;
106
107     //Class name of each wizard step panel (use for lazy instantiation)
108
private static final String JavaDoc[] stepClassNames = new String JavaDoc[] {
109         "dummy",
110         "org.netbeans.modules.websvc.dev.wizard.CreateWebServiceFromExistingCodePanel",
111         "dummy",
112         "dummy"
113     };
114
115     // When above Classes are dynamically instantiated, we store them in array "steps"
116
// (this array mirrors array stepClassNames)
117
private static WizardDescriptor.Panel[] steps = new WizardDescriptor.Panel[] { null, null, null, null};
118
119     //Properties stored in the WizardDescriptor
120
public static final String JavaDoc WSDL_FILE_PATH = "wsdlfilepath";
121     public static final String JavaDoc WSDL_FILE_URL = "wsdlfileurl";
122
123
124     public static WebServiceWizard create() {
125         return new WebServiceWizard();
126     }
127
128     public void initialize(WizardDescriptor wizard) {
129
130         currentWizardBranch= PATH_CREATE_FROM_SCRATCH;
131         helper = new WebServiceWizardHelper();
132         helper.setWizard(this);
133
134         wiz = wizard;
135         project = Templates.getProject(wiz);
136
137         //create the Java Project chooser
138
SourceGroup[] sourceGroups = Util.getJavaSourceGroups(project);
139         wsPanel = new WebServiceWizardDescriptor(wiz, helper);
140         if (sourceGroups.length==0) {
141             firstPanel = Templates.createSimpleTargetChooser(project,sourceGroups, wsPanel);
142         } else {
143             firstPanel = JavaTemplates.createPackageChooser(project,sourceGroups, wsPanel, true);
144         }
145         
146         wsPanel.setTargetChooserPanel(firstPanel);
147         
148         JComponent JavaDoc c = (JComponent JavaDoc)firstPanel.getComponent();
149         Util.changeLabelInComponent(c, NbBundle.getMessage(Util.class, "LBL_JavaTargetChooserPanelGUI_ClassName_Label"),
150         NbBundle.getMessage(WebServiceWizard.class, "LBL_Webservice_Name") );
151         Util.hideLabelAndLabelFor(c, NbBundle.getMessage(Util.class, "LBL_JavaTargetChooserPanelGUI_CreatedFile_Label"));
152     }
153
154     // return a step panel, and instantiate it if necessary.
155
private WizardDescriptor.Panel getStep(int step) {
156         if(step == 0) return firstPanel;
157
158         if (steps[step] != null) {
159             return steps[step];
160         }
161
162         WizardDescriptor.Panel p = createWizardPanel(stepClassNames[step]);
163         ((WebServiceWizard.HasWizardHelper)p).setWizardHelper(helper);
164         steps[step] = p;
165
166         return p;
167     }
168
169     public void uninitialize(WizardDescriptor wizard)
170     {}
171
172     public Set instantiate() throws IOException {
173         Component JavaDoc c = WindowManager.getDefault().getMainWindow();
174         // Use Progress API to display generator messages.
175

176         final ProgressHandle handle = ProgressHandleFactory.createHandle(
177                 NbBundle.getMessage(WebServiceWizard.class, "TXT_WebServiceGeneration"));
178         handle.start(100);
179
180         Runnable JavaDoc r = new Runnable JavaDoc() {
181             public void run() {
182                 try {
183                     generateWebService(handle);
184                 } catch (Exception JavaDoc e) {
185                     //finish progress bar
186
handle.finish();
187                     String JavaDoc message = e.getLocalizedMessage();
188                     if(message != null) {
189                         ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, e);
190                         NotifyDescriptor nd = new NotifyDescriptor.Message(message, NotifyDescriptor.ERROR_MESSAGE);
191                         DialogDisplayer.getDefault().notify(nd);
192                     } else {
193                         ErrorManager.getDefault().notify(ErrorManager.EXCEPTION, e);
194                     }
195                 }
196             }
197         };
198         RequestProcessor.getDefault().post(r);
199         return Collections.EMPTY_SET;
200     }
201
202     private void generateWebService(ProgressHandle handle) throws Exception JavaDoc {
203         FileObject pkg = Templates.getTargetFolder(wiz);
204         wsName = Templates.getTargetName(wiz);
205         Project project = Templates.getProject(wiz);
206         WebServicesSupport wsSupport = WebServicesSupport.getWebServicesSupport(pkg);
207         assert wsSupport != null;
208         WebServiceGenerator generator = new WebServiceGenerator(wsSupport, wsName, pkg, project);
209         if(helper.getCreateFrom() == WebServiceWizardHelper.CREATE_FROM_SCRATCH) {
210             handle.progress(NbBundle.getMessage(WebServiceWizard.class, "MSG_GEN_SEI_AND_IMPL"), 50);
211             generator.generateWebService();
212         }
213         else if (helper.getCreateFrom() == WebServiceWizardHelper.CREATE_FROM_EXISTING_CODE) {
214             handle.progress(NbBundle.getMessage(WebServiceWizard.class, "MSG_GEN_SEI_AND_IMPL"), 50);
215             Node[] nodes = helper.getExistingCodeNodes();
216             generator.generateWebService(nodes);
217         }
218         else //coming from wsdl
219
{
220             FileObject wsDDFolder = wsSupport.getWsDDFolder();
221             //get wsdl folder, if none, create it
222
FileObject wsdlFolder = wsDDFolder.getFileObject("wsdl");
223             if(wsdlFolder == null) {
224                 wsdlFolder = wsDDFolder.createFolder("wsdl");
225             }
226             if (helper.getCreateFrom() == WebServiceWizardHelper.CREATE_FROM_WSDL_FILE) {
227                 handle.progress(NbBundle.getMessage(WebServiceWizard.class, "MSG_PARSING_WSDL"), 30);
228                 String JavaDoc wsdlFilePath = (String JavaDoc)wiz.getProperty(WSDL_FILE_PATH);
229                 File normalizedWsdlFilePath = FileUtil.normalizeFile(new File(wsdlFilePath));
230                 final FileObject sourceWsdlFile = FileUtil.toFileObject(normalizedWsdlFilePath);
231                 if(sourceWsdlFile == null) {
232                     String JavaDoc mes = NbBundle.getMessage(WebServiceWizard.class, "MSG_CANNOT_GET_FILE_OBJECT", normalizedWsdlFilePath.getAbsolutePath());
233                     throw new IOException(mes);
234                 }
235                 List schemaFiles = WSGenerationUtil.getSchemaNames(sourceWsdlFile,true);
236                 String JavaDoc changedWsName = null;
237                 try {
238                     changedWsName = generator.parseWSDL(sourceWsdlFile.getInputStream());
239                 } catch (NoWSPortDefinedException exc) {
240                     ErrorManager.getDefault().log(ErrorManager.INFORMATIONAL, "WSDL does not contain any defined ports"); //NOI18N
241
String JavaDoc mes = NbBundle.getMessage(WebServiceGenerator.class, "ERR_WsdlNoPortDefined"); // NOI18N
242
NotifyDescriptor desc = new NotifyDescriptor.Message(mes, NotifyDescriptor.Message.ERROR_MESSAGE);
243                     DialogDisplayer.getDefault().notify(desc);
244                     handle.finish();
245                     return;
246                 }
247                 if (changedWsName==null) changedWsName = wsName;
248                 handle.progress(NbBundle.getMessage(WebServiceWizard.class, "MSG_CREATING_NEW_WSDL"), 50);
249                 wsdlFO = generator.generateWSDL(WebServiceGenerator.WSDL_TEMPLATE, changedWsName, generator.getSoapBinding(),
250                 generator.getPortTypeName(), wsdlFolder, sourceWsdlFile.getParent(), wsName, new StreamSource JavaDoc(sourceWsdlFile.getInputStream()));
251             }
252             else if (helper.getCreateFrom() == WebServiceWizardHelper.CREATE_FROM_WSDL_URL) {
253                 handle.progress(NbBundle.getMessage(WebServiceWizard.class, "MSG_PARSING_WSDL"), 30);
254                 String JavaDoc wsdlUrl = (String JavaDoc) wiz.getProperty(WSDL_FILE_URL);
255                 URL JavaDoc url = null;
256                 InputStream in = null;
257                 try {
258                     url = new URL JavaDoc(wsdlUrl);
259                     in = url.openStream();
260                 }
261                 catch(MalformedURLException JavaDoc e) {
262                     String JavaDoc mes = NbBundle.getMessage(WebServiceWizard.class, "MSG_CANNOT_LOCATE_URL", wsdlUrl);
263                     throw new Exception JavaDoc(mes);
264                 }
265                 catch(IOException e) {
266                     String JavaDoc mes = NbBundle.getMessage(WebServiceWizard.class, "MSG_UNABLE_ACCESS_URL", wsdlUrl);
267                     throw new Exception JavaDoc(mes);
268                 }
269                 String JavaDoc changedWsName = null;
270                 try {
271                     changedWsName = generator.parseWSDL(in);
272                 } catch (NoWSPortDefinedException exc) {
273                     ErrorManager.getDefault().log(ErrorManager.INFORMATIONAL, "WSDL does not contain any defined ports"); //NOI18N
274
String JavaDoc mes = NbBundle.getMessage(WebServiceGenerator.class, "ERR_WsdlNoPortDefined"); // NOI18N
275
NotifyDescriptor desc = new NotifyDescriptor.Message(mes, NotifyDescriptor.Message.ERROR_MESSAGE);
276                     DialogDisplayer.getDefault().notify(desc);
277                     handle.finish();
278                     return;
279                 }
280                 if (changedWsName==null) changedWsName = wsName;
281                 handle.progress(NbBundle.getMessage(WebServiceWizard.class, "MSG_CREATING_NEW_WSDL"), 50);
282                 wsdlFO = generator.generateWSDL(WebServiceGenerator.WSDL_TEMPLATE, changedWsName, generator.getSoapBinding(),
283                 generator.getPortTypeName(), wsdlFolder, wsName, new StreamSource JavaDoc(url.openStream()));
284             }
285         }
286
287         URI JavaDoc targetNS = null;
288         URI JavaDoc typeNS = null;
289         try{
290             targetNS = generator.getTargetNS();
291             typeNS = generator.getDefaultTypeNS(wsName); //Need to get from user
292
}catch(java.net.URISyntaxException JavaDoc e){
293             String JavaDoc mes = NbBundle.getMessage(WebServiceWizard.class, "MSG_INVALID_URL_SYNTAX");
294             throw new Exception JavaDoc(mes);
295         }
296         //Create config file
297
handle.progress(NbBundle.getMessage(WebServiceWizard.class, "MSG_CREATING_WSCOMPILE_ARTIFACTS"));
298         String JavaDoc servantClassName = generator.getServantClassName();
299         String JavaDoc seiClassName = generator.getSEIClassName();
300         FileObject configFile = null;
301         if (helper.getCreateFrom() == WebServiceWizardHelper.CREATE_FROM_WSDL_FILE ||
302         helper.getCreateFrom() == WebServiceWizardHelper.CREATE_FROM_WSDL_URL) {
303             File wsdlFile = FileUtil.toFile(wsdlFO);
304             URI JavaDoc wsdlURI = wsdlFile.toURI();
305             configFile = generator.generateConfigFile(wsdlURI);
306         }
307         else {
308             configFile = generator.generateConfigFile(seiClassName, servantClassName, targetNS, typeNS);
309         }
310         handle.progress(70);
311
312         //Add web service entries to the project's property file, project file
313
if (helper.getCreateFrom() == WebServiceWizardHelper.CREATE_FROM_WSDL_FILE ||
314         helper.getCreateFrom() == WebServiceWizardHelper.CREATE_FROM_WSDL_URL ) {
315             wsSupport.addServiceImpl(wsName, configFile, true, generator.getWscompileFeatures());
316             //run the wscompile ant target
317
handle.progress(NbBundle.getMessage(WebServiceWizard.class, "MSG_RUNNING_WSCOMPILE_TARGET"));
318             String JavaDoc targetName = wsName + "_wscompile";
319             ExecutorTask task = ActionUtils.runTarget(findBuildXml(), new String JavaDoc[]{targetName}, null);
320             task.waitFinished();
321             if(task.result() != 0){
322                 String JavaDoc mes = NbBundle.getMessage(WebServiceWizard.class, "MSG_WSCOMPILE_UNSUCCESSFUL");
323                 wsSupport.removeProjectEntries(wsName);
324                 try {
325                     deleteFile(configFile);
326                     deleteFile(wsdlFO);
327                 }
328                 catch(IOException e) {
329                     String JavaDoc message = NbBundle.getMessage(WebServiceWizard.class, "MSG_UNABLE_DELETE_FILES");
330                     NotifyDescriptor nd =
331                     new NotifyDescriptor.Message(message,
332                     NotifyDescriptor.ERROR_MESSAGE);
333                     DialogDisplayer.getDefault().notify(nd);
334                     //let this through
335
}
336                 throw new Exception JavaDoc(mes);
337             }
338             handle.progress(90);
339             addHeaderComments(wsName, servantClassName, pkg);
340             wsSupport.addInfrastructure(servantClassName, pkg);
341
342             //open the class in the editor
343
String JavaDoc implClassName = servantClassName.substring(servantClassName.lastIndexOf(".") + 1);
344             FileObject clz = pkg.getFileObject(implClassName, "java");
345             DataObject dobj = DataObject.find(clz);
346             EditorCookie ec = (EditorCookie) dobj.getCookie(EditorCookie.class);
347             ec.open();
348         }
349         else {
350             wsSupport.addServiceImpl(wsName, configFile, false);
351             handle.progress(90);
352         }
353
354         //Add web service entries to the module's DD
355
wsSupport.addServiceEntriesToDD(wsName, seiClassName, servantClassName);
356         
357         //Add webservice entry in webservices.xml
358
handle.progress(NbBundle.getMessage(WebServiceWizard.class, "MSG_ADDING_DD_ENTRIES"));
359         String JavaDoc portTypeName = null;
360         if(helper.getCreateFrom() == WebServiceWizardHelper.CREATE_FROM_WSDL_FILE ||
361            helper.getCreateFrom() == WebServiceWizardHelper.CREATE_FROM_WSDL_URL) {
362             portTypeName = generator.getPortTypeName();
363         }
364         generator.addWebServiceEntry(seiClassName, portTypeName, targetNS);
365
366         if (helper.getCreateFrom() == WebServiceWizardHelper.CREATE_FROM_EXISTING_CODE) {
367             generator.addReferences(servantClassName, helper.getExistingCodeNodes());
368         }
369         handle.finish();
370     }
371
372     private void addHeaderComments(String JavaDoc wsName, String JavaDoc servantClassName, FileObject pkg) {
373         String JavaDoc comment = NbBundle.getMessage(WebServiceWizard.class, "MSG_WS_CLASS_COMMENT", wsName);
374         StringBuffer JavaDoc buffer = new StringBuffer JavaDoc(comment + "\n");
375         buffer.append(NbBundle.getMessage(WebServiceWizard.class, "MSG_CREATED_COMMENT")+ " " + DateFormat.getDateTimeInstance().format(new Date JavaDoc()) + "\n" );
376         buffer.append("@author " + System.getProperty("user.name") );
377 // Retouche
378
// JavaMetamodel.getManager().waitScanFinished();
379
// JavaClass clazz = JMIUtils.findClass(servantClassName);
380
// if (clazz!=null) {
381
// String javadoc = clazz.getJavadocText();
382
// clazz.setJavadocText(buffer.toString());
383
// }
384
}
385
386     private void deleteFile(FileObject file)throws IOException{
387         FileLock lock = null;
388         try{
389             lock = file.lock();
390             file.delete(lock);
391         }
392         finally{
393             if(lock != null){
394                 lock.releaseLock();
395             }
396         }
397     }
398
399     private FileObject findBuildXml() {
400         return project.getProjectDirectory().getFileObject(GeneratedFilesHelper.BUILD_XML_PATH);
401     }
402
403     public void addChangeListener(ChangeListener JavaDoc l) {
404         WizardDescriptor.Panel p = null;
405         for(int i = 0; i < stepPathNames[currentWizardBranch].length; i++){
406             //special case: if first panel add listener to wsPanel
407
if(currentWizardBranch == 0) {
408                 p = wsPanel;
409             }
410             else {
411                 p = getStep(stepPaths[currentWizardBranch][i]);
412             }
413             if(p != null)
414                 p.addChangeListener(l);
415         }
416     }
417
418     public WizardDescriptor.Panel current() {
419         WizardDescriptor.Panel pnl = getStep(stepPaths[currentWizardBranch][currentPanel]);
420         JComponent JavaDoc c = (JComponent JavaDoc) pnl.getComponent();
421         if(currentPanel != 0) {
422             ((WebServiceWizard.HasWizardHelper)pnl).setWizardHelper(helper);
423         }
424         c.putClientProperty("WizardPanel_contentData", stepPathNames[currentWizardBranch]); // NOI18N
425
c.putClientProperty("WizardPanel_contentSelectedIndex", new Integer JavaDoc(currentPanel)); // NOI18N
426

427         return getStep(stepPaths[currentWizardBranch][currentPanel]);
428     }
429
430     public boolean hasNext() {
431         return ((currentPanel + 1) < stepPaths[currentWizardBranch].length);
432     }
433
434     public boolean hasPrevious() {
435         return currentPanel > 0;
436     }
437
438     public String JavaDoc name() {
439         return NbBundle.getMessage(WebServiceWizard.class, "LBL_Create_WS_Title");
440     }
441
442     public void nextPanel() {
443         if(!hasNext()){
444             throw new NoSuchElementException();
445         }
446         currentPanel++;
447     }
448
449     public void previousPanel() {
450         if(!hasPrevious()){
451             throw new NoSuchElementException();
452         }
453         currentPanel--;
454     }
455
456     public void removeChangeListener(ChangeListener JavaDoc l) {
457         WizardDescriptor.Panel p = null;
458         for (int i = 0; i < stepPathNames[currentWizardBranch].length; i++) {
459             if(currentWizardBranch == 0) {
460                 p = wsPanel;
461             }
462             else {
463                 p = getStep(stepPaths[currentWizardBranch][i]);
464             }
465             if (p != null)
466                 p.removeChangeListener(l);
467         }
468     }
469
470     // This is called by panel frames to tell the wizard that something the user
471
// has done has caused a branch to occur. Panel frame then calls fireStateChanged()
472
// after calling this method.
473
public void setPanelsAndSteps(int branch) {
474         currentWizardBranch = branch;
475     }
476
477     protected int getCurrentPanelIndex() {
478         return currentPanel;
479     }
480
481     protected WizardDescriptor.Panel createWizardPanel(String JavaDoc panelName) {
482         try {
483             Class JavaDoc newClass = Class.forName(panelName);
484             Constructor JavaDoc cons = newClass.getDeclaredConstructor(new Class JavaDoc[]{WebServiceWizardHelper.class});
485             return (WizardDescriptor.Panel) cons.newInstance(new Object JavaDoc[]{helper});
486         }
487         catch(Exception JavaDoc e) {
488             throw new RuntimeException JavaDoc(e.getMessage());
489         }
490     }
491
492     // ----------------- Inner Classes ----------------------
493

494     // this wizard's step panels must implememt this interface.
495
public static interface HasWizardHelper {
496         public void setWizardHelper(WebServiceWizardHelper h);
497     }
498     
499 }
500
Popular Tags