KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > modules > xml > wsdl > ui > wizard > NewWSDLWizardIterator


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-2007 Sun
17  * Microsystems, Inc. All Rights Reserved.
18  */

19
20 package org.netbeans.modules.xml.wsdl.ui.wizard;
21
22 import java.awt.Component JavaDoc;
23 import java.awt.Container JavaDoc;
24 import java.io.File JavaDoc;
25 import java.io.FileOutputStream JavaDoc;
26 import java.io.FileReader JavaDoc;
27 import java.io.FileWriter JavaDoc;
28 import java.io.IOException JavaDoc;
29 import java.io.OutputStreamWriter JavaDoc;
30 import java.io.StringReader JavaDoc;
31 import java.net.URI JavaDoc;
32 import java.net.URISyntaxException JavaDoc;
33 import java.util.ArrayList JavaDoc;
34 import java.util.Collection JavaDoc;
35 import java.util.Collections JavaDoc;
36 import java.util.HashMap JavaDoc;
37 import java.util.Iterator JavaDoc;
38 import java.util.List JavaDoc;
39 import java.util.Map JavaDoc;
40 import java.util.NoSuchElementException JavaDoc;
41 import java.util.Set JavaDoc;
42
43 import javax.swing.JComponent JavaDoc;
44 import javax.swing.JTextField JavaDoc;
45 import javax.swing.event.ChangeListener JavaDoc;
46 import javax.swing.text.BadLocationException JavaDoc;
47
48 import org.netbeans.api.project.Project;
49 import org.netbeans.api.project.SourceGroup;
50 import org.netbeans.api.project.Sources;
51 import org.netbeans.modules.xml.catalogsupport.DefaultProjectCatalogSupport;
52 import org.netbeans.modules.xml.schema.model.Import;
53 import org.netbeans.modules.xml.schema.model.Schema;
54 import org.netbeans.modules.xml.schema.model.SchemaModel;
55 import org.netbeans.modules.xml.wsdl.model.Definitions;
56 import org.netbeans.modules.xml.wsdl.model.Types;
57 import org.netbeans.modules.xml.wsdl.model.WSDLModel;
58 import org.netbeans.modules.xml.wsdl.model.WSDLModelFactory;
59 import org.netbeans.modules.xml.wsdl.model.extensions.xsd.WSDLSchema;
60 import org.netbeans.modules.xml.wsdl.ui.netbeans.module.WSDLDataObject;
61 import org.netbeans.modules.xml.wsdl.ui.view.PartAndElementOrTypeTableModel;
62 import org.netbeans.modules.xml.xam.ModelSource;
63 import org.netbeans.modules.xml.xam.dom.AbstractDocumentComponent;
64 import org.netbeans.modules.xml.xam.locator.CatalogModelException;
65 import org.netbeans.spi.project.ui.templates.support.Templates;
66 import org.openide.ErrorManager;
67 import org.openide.WizardDescriptor;
68 import org.openide.WizardDescriptor.Panel;
69 import org.openide.cookies.EditCookie;
70 import org.openide.cookies.EditorCookie;
71 import org.openide.cookies.SaveCookie;
72 import org.openide.filesystems.FileObject;
73 import org.openide.filesystems.FileUtil;
74 import org.openide.loaders.DataFolder;
75 import org.openide.loaders.DataObject;
76 import org.openide.loaders.TemplateWizard;
77 import org.openide.util.NbBundle;
78
79 public final class NewWSDLWizardIterator implements TemplateWizard.Iterator {
80     
81     private int index;
82     
83     private WizardDescriptor wizard;
84     private WizardDescriptor.Panel[] panels;
85     
86     private WizardDescriptor.Panel folderPanel;
87     private transient SourceGroup[] sourceGroups;
88     private transient DefaultProjectCatalogSupport catalogSupport;
89     
90     /**
91      * Initialize panels representing individual wizard's steps and sets
92      * various properties for them influencing wizard appearance.
93      */

94     private Panel[] createPanels(Project project) {
95         Sources sources = (Sources) project.getLookup().lookup(org.netbeans.api.project.Sources.class);
96         sourceGroups = sources.getSourceGroups(Sources.TYPE_GENERIC);
97         folderPanel=new WsdlPanel(project,sourceGroups);
98         // creates simple wizard panel with bottom panel
99
WizardDescriptor.Panel firstPanel = new WizardNewWSDLStep(Templates.createSimpleTargetChooser(project,sourceGroups,folderPanel));
100         JComponent JavaDoc c = (JComponent JavaDoc)firstPanel.getComponent();
101         // the bottom panel should listen to changes on file name text field
102
((WsdlPanel)folderPanel).setNameTF(findFileNameField(c, Templates.getTargetName(wizard)));
103         
104         WizardDescriptor.Panel secondPanel = new WizardPortTypeConfigurationStep(project);
105         WizardDescriptor.Panel thirdPanel = new WizardBindingConfigurationStep();
106                         
107         return new WizardDescriptor.Panel[] {
108             firstPanel,
109             secondPanel,
110             thirdPanel
111         };
112     }
113     
114     public Set JavaDoc instantiate(TemplateWizard wiz) throws IOException JavaDoc {
115 // Here is the default plain behavior. Simply takes the selected
116
// template (you need to have included the standard second panel
117
// in createPanels(), or at least set the properties targetName and
118
// targetFolder correctly), instantiates it in the provided
119
// position, and returns the result.
120
// More advanced wizards can create multiple objects from template
121
// (return them all in the result of this method), populate file
122
// contents on the fly, etc.
123

124         FileObject dir = Templates.getTargetFolder( wiz );
125         DataFolder df = DataFolder.findFolder( dir );
126         FileObject template = Templates.getTemplate( wiz );
127         WsdlPanel panel = (WsdlPanel)folderPanel;
128         boolean importSchemas=false;
129         if (panel.isImport() && panel.getSchemas().length>0) {
130             importSchemas=true;
131 // FileObject templateParent = template.getParent();
132
// template = templateParent.getFileObject("WSDL_import","wsdl"); //NOI18N
133
}
134         
135         DataObject dTemplate = DataObject.find( template );
136         DataObject dobj = dTemplate.createFromTemplate( df, Templates.getTargetName( wiz ) );
137         //create new data object
138
if (dobj!=null) {
139             
140             catalogSupport = DefaultProjectCatalogSupport.getInstance(dobj.getPrimaryFile());
141             WSDLModel model = null;
142            
143             //is there a temp wsdl model. it will be if wizard screen is 2 or 3
144
WSDLModel tempModel = (WSDLModel) wiz.getProperty(WizardPortTypeConfigurationStep.TEMP_WSDLMODEL);
145             wiz.putProperty(WizardPortTypeConfigurationStep.TEMP_WSDLMODEL, null);
146             if(tempModel != null) {
147                 try {
148                     postProcessImports(tempModel, dobj);
149                 } catch(Exception JavaDoc ex) {
150                     ErrorManager.getDefault().notify(ex);
151                 }
152                 
153                 FileObject tmpWsdlFileObject = (FileObject) tempModel.getModelSource().getLookup().lookup(FileObject.class);
154                 if(tmpWsdlFileObject != null) {
155                     File JavaDoc wsdlFile = FileUtil.toFile(dobj.getPrimaryFile());
156                     long lastMod = wsdlFile.lastModified();
157                     
158                     DataObject wsdlDataObj = DataObject.find(tmpWsdlFileObject);
159                     EditorCookie editorCookie = (EditorCookie)wsdlDataObj.getCookie(EditorCookie.class);
160                     editorCookie.openDocument();
161                     javax.swing.text.Document JavaDoc doc = editorCookie.getDocument();
162
163                     //write from tempModel to actual file
164
FileOutputStream JavaDoc stream = new FileOutputStream JavaDoc(wsdlFile);
165                     //set the charset to utf-8
166
OutputStreamWriter JavaDoc writer = new OutputStreamWriter JavaDoc(stream, "utf-8");
167                     
168                     try {
169                         writer.write(doc.getText(0, doc.getLength()));
170                     } catch (BadLocationException JavaDoc e) {
171                         ErrorManager.getDefault().notify(e);
172                     } finally {
173                         writer.close();
174                         stream.close();
175                     }
176                     wsdlFile.setLastModified(lastMod);
177                     
178                     //get the mode for newly created wsdl file
179
ModelSource modelSource = org.netbeans.modules.xml.retriever.catalog.Utilities.getModelSource(dobj.getPrimaryFile(),
180                     dobj.getPrimaryFile().canWrite());
181                     
182                     model = WSDLModelFactory.getDefault().getModel(modelSource);
183                     
184
185                 }
186             } else {
187                 FileObject wsdlFile = dobj.getPrimaryFile();
188                 ModelSource modelSource = org.netbeans.modules.xml.retriever.catalog.Utilities.getModelSource(wsdlFile,
189                     wsdlFile.canWrite());
190                 model = WSDLModelFactory.getDefault().getModel(modelSource);
191                 
192                 String JavaDoc definitionName = Templates.getTargetName(wizard);
193                 String JavaDoc targetNamespace = panel.getNS();
194                 model.startTransaction();
195                 Definitions def = model.getDefinitions();
196                 def.setName(definitionName);
197                 def.setTargetNamespace(targetNamespace);
198                 ((AbstractDocumentComponent) def).addPrefix("tns", targetNamespace);
199                 if (def.getTypes() != null) {
200                     def.setTypes(model.getFactory().createTypes());
201                 }
202                 
203                 model.endTransaction();
204             }
205             
206             if (model != null && importSchemas) {
207                 addSchemaImport(model, dobj);
208             }
209             
210             SaveCookie save = (SaveCookie)dobj.getCookie(SaveCookie.class);
211             if (save!=null) save.save();
212         }
213         
214         return Collections.singleton(dobj);
215     }
216
217     private void postProcessImports(WSDLModel model, DataObject dobj) throws Exception JavaDoc {
218         Types types = model.getDefinitions().getTypes();
219         if(types != null) {
220             Collection JavaDoc<WSDLSchema> schemas = types.getExtensibilityElements(WSDLSchema.class);
221             
222             if(schemas != null) {
223                 
224                 if(schemas.iterator().hasNext()) {
225                     WSDLSchema wsdlSchema = schemas.iterator().next();
226                     SchemaModel sModel = wsdlSchema.getSchemaModel();
227                     if(sModel != null) {
228                         Schema schema = sModel.getSchema();
229                         if(schema != null && schema.getImports() != null) {
230                             model.startTransaction();
231                             Iterator JavaDoc<Import> it = schema.getImports().iterator();
232                             while(it.hasNext()) {
233                                 Import imp = it.next();
234                                 postProcessImport(imp, sModel, dobj);
235                             }
236                             model.endTransaction();
237                         }
238                         
239                     }
240                 }
241             }
242         }
243     }
244     
245     private void postProcessImport(Import imp, SchemaModel model, DataObject dobj) throws Exception JavaDoc {
246         String JavaDoc namespace = imp.getNamespace();
247         Collection JavaDoc<Schema> schemas = model.findSchemas(namespace);
248         Iterator JavaDoc<Schema> it = schemas.iterator();
249         while(it.hasNext()) {
250             Schema schema = it.next();
251             SchemaModel sModel = schema.getModel();
252             FileObject schemaFileObj = (FileObject) sModel.getModelSource().getLookup().lookup(FileObject.class);
253             String JavaDoc location = getRelativePathOfSchema(dobj, schemaFileObj.getURL().toString());
254             imp.setSchemaLocation(location);
255         }
256     }
257     
258     private void addSchemaImport(WSDLModel model, DataObject dobj) {
259         model.startTransaction();
260         WsdlPanel panel = (WsdlPanel)folderPanel;
261         String JavaDoc targetNamespace = panel.getNS();
262
263         WsdlUIPanel.SchemaInfo[] infos = panel.getSchemas();
264         Schema schema = null;
265         WSDLSchema wsdlSchema = null;
266
267         for (int i=0;i<infos.length;i++) {
268             String JavaDoc ns = infos[i].getNamespace();
269             if (ns.length()==0) ns = targetNamespace;//"urn:WS/types"+String.valueOf(i+1); //NOI18N
270

271             String JavaDoc prefix = "ns" + String.valueOf(i+1);
272
273
274             String JavaDoc relativePath = null;
275             try{
276                 relativePath = getRelativePathOfSchema(dobj, infos[i].getSchemaName());
277             }catch(URISyntaxException JavaDoc e){
278                 relativePath= infos[i].getSchemaName();
279             }
280
281             Definitions def = model.getDefinitions();
282             Types types = def.getTypes();
283             if (types == null) {
284                 types = model.getFactory().createTypes();
285                 def.setTypes(types);
286             }
287
288             List JavaDoc<WSDLSchema> wsdlSchemas = types.getExtensibilityElements(WSDLSchema.class);
289
290             if (wsdlSchemas == null || wsdlSchemas.size() == 0) {
291                 wsdlSchema = model.getFactory().createWSDLSchema();
292                 SchemaModel schemaModel = wsdlSchema.getSchemaModel();
293                 schema = schemaModel.getSchema();
294                 schema.setTargetNamespace(model.getDefinitions().getTargetNamespace());
295                 types.addExtensibilityElement(wsdlSchema);
296             } else {
297                 wsdlSchema = wsdlSchemas.get(0);
298                 SchemaModel schemaModel = wsdlSchema.getSchemaModel();
299                 schema = schemaModel.getSchema();
300             }
301
302
303
304             if(!isSchemaImportExists(relativePath, ns, schema)) {
305                 schema.addPrefix(prefix, ns);
306                 ((AbstractDocumentComponent) def).addPrefix(prefix, ns);
307
308                 org.netbeans.modules.xml.schema.model.Import schemaImport =
309                     schema.getModel().getFactory().createImport();
310                 schemaImport.setNamespace(ns);
311                 schemaImport.setSchemaLocation(relativePath);
312
313                 schema.addExternalReference(schemaImport);
314             }
315         }
316
317         model.endTransaction();
318     }
319     
320     
321     private boolean isSchemaImportExists(String JavaDoc schemaLocation, String JavaDoc namespace, Schema schema) {
322         boolean isImportExist = false;
323         Collection JavaDoc<Import> imports = schema.getImports();
324         Iterator JavaDoc<Import> it = imports.iterator();
325         while(it.hasNext()) {
326             Import imp = it.next();
327             
328             String JavaDoc sLoc = imp.getSchemaLocation();
329             String JavaDoc ns = imp.getNamespace();
330             
331             if(ns != null && ns.equals(namespace) && sLoc != null && sLoc.equals(schemaLocation)) {
332                 isImportExist = true;
333                 break;
334             }
335         }
336         
337         return isImportExist;
338     }
339     
340     private String JavaDoc getRelativePathOfSchema(DataObject wsdlDO, String JavaDoc schemaURL) throws URISyntaxException JavaDoc{
341         FileObject fo = wsdlDO.getPrimaryFile();
342         File JavaDoc f = FileUtil.toFile(fo);
343         FileObject schemaFO = FileUtil.toFileObject(new File JavaDoc(new URI JavaDoc(schemaURL)));
344         
345         String JavaDoc relativePath = null;
346         if (catalogSupport != null && catalogSupport.needsCatalogEntry(fo, schemaFO)) {
347 // Remove the previous catalog entry, then create new one.
348
URI JavaDoc uri;
349             try {
350                 uri = catalogSupport.getReferenceURI(fo, schemaFO);
351                 catalogSupport.removeCatalogEntry(uri);
352                 catalogSupport.createCatalogEntry(fo, schemaFO);
353                 relativePath = catalogSupport.getReferenceURI(fo, schemaFO).toString();
354             } catch (URISyntaxException JavaDoc use) {
355                 ErrorManager.getDefault().notify(use);
356             } catch (IOException JavaDoc ioe) {
357                 ErrorManager.getDefault().notify(ioe);
358             } catch (CatalogModelException cme) {
359                 ErrorManager.getDefault().notify(cme);
360             }
361         } else {
362             relativePath = org.netbeans.modules.xml.retriever.catalog.Utilities.relativize(f.toURI(),new URI JavaDoc(schemaURL));
363         }
364         return relativePath;
365     }
366     
367     public void initialize(TemplateWizard wiz) {
368         this.wizard = wiz;
369         index = 0;
370         Project project = Templates.getProject( wiz );
371         panels = createPanels(project);
372         
373         // Creating steps.
374
Object JavaDoc prop = wiz.getProperty("WizardPanel_contentData"); // NOI18N
375
String JavaDoc[] beforeSteps = null;
376         if (prop != null && prop instanceof String JavaDoc[]) {
377             beforeSteps = (String JavaDoc[])prop;
378         }
379         String JavaDoc[] steps = Utilities.createSteps(beforeSteps, panels);
380         
381         for (int i = 0; i < panels.length; i++) {
382             Component JavaDoc c = panels[i].getComponent();
383             if (steps[i] == null) {
384                 // Default step name to component name of panel.
385
// Mainly useful for getting the name of the target
386
// chooser to appear in the list of steps.
387
steps[i] = c.getName();
388             }
389             if (c instanceof JComponent JavaDoc) { // assume Swing components
390
JComponent JavaDoc jc = (JComponent JavaDoc) c;
391                 // Step #.
392
jc.putClientProperty("WizardPanel_contentSelectedIndex", new Integer JavaDoc(i)); // NOI18N
393
// Step name (actually the whole list for reference).
394
jc.putClientProperty("WizardPanel_contentData", steps); // NOI18N
395
}
396         }
397     }
398
399
400
401     public void uninitialize(TemplateWizard wiz) {
402         
403         File JavaDoc tempWSDLFile = (File JavaDoc) wizard.getProperty(WizardPortTypeConfigurationStep.TEMP_WSDLFILE);
404         try {
405             if(tempWSDLFile != null) {
406                 
407                 FileObject tempFile = FileUtil.toFileObject(tempWSDLFile.getCanonicalFile());
408                 if(tempFile != null) {
409                     DataObject dObj = DataObject.find(tempFile);
410                     if(dObj != null) {
411                         dObj.delete();
412                     }
413                     
414                 }
415             }
416         } catch(Exception JavaDoc ex) {
417             ErrorManager.getDefault().notify(ex);
418         }
419         
420         this.wizard = null;
421         panels = null;
422         
423     }
424     
425     
426     public Set JavaDoc instantiate() throws IOException JavaDoc {
427         return Collections.EMPTY_SET;
428     }
429     
430     public void initialize(WizardDescriptor wizard) {
431         this.wizard = wizard;
432     }
433     
434     
435     public WizardDescriptor.Panel current() {
436         return panels[index];
437     }
438     
439     public String JavaDoc name() {
440         return index + 1 + ". from " + panels.length;
441     }
442     
443     public boolean hasNext() {
444         return index < panels.length - 1;
445     }
446     
447     public boolean hasPrevious() {
448         return index > 0;
449     }
450     
451     public void nextPanel() {
452         if (!hasNext()) {
453             throw new NoSuchElementException JavaDoc();
454         }
455         index++;
456     }
457     
458     public void previousPanel() {
459         if (!hasPrevious()) {
460             throw new NoSuchElementException JavaDoc();
461         }
462         index--;
463     }
464     
465     // If nothing unusual changes in the middle of the wizard, simply:
466
public void addChangeListener(ChangeListener JavaDoc l) {}
467     public void removeChangeListener(ChangeListener JavaDoc l) {}
468     
469     // If something changes dynamically (besides moving between panels), e.g.
470
// the number of panels changes in response to user input, then uncomment
471
// the following and call when needed: fireChangeEvent();
472
/*
473     private Set<ChangeListener> listeners = new HashSet<ChangeListener>(1);
474     public final void addChangeListener(ChangeListener l) {
475         synchronized (listeners) {
476             listeners.add(l);
477         }
478     }
479     public final void removeChangeListener(ChangeListener l) {
480         synchronized (listeners) {
481             listeners.remove(l);
482         }
483     }
484     protected final void fireChangeEvent() {
485         Iterator<ChangeListener> it;
486         synchronized (listeners) {
487             it = new HashSet<ChangeListener>(listeners).iterator();
488         }
489         ChangeEvent ev = new ChangeEvent(this);
490         while (it.hasNext()) {
491             it.next().stateChanged(ev);
492         }
493     }
494      */

495     
496     // You could safely ignore this method. Is is here to keep steps which were
497
// there before this wizard was instantiated. It should be better handled
498
// by NetBeans Wizard API itself rather than needed to be implemented by a
499
// client code.
500
private String JavaDoc[] createSteps() {
501         String JavaDoc[] beforeSteps = null;
502         Object JavaDoc prop = wizard.getProperty("WizardPanel_contentData");
503         if (prop != null && prop instanceof String JavaDoc[]) {
504             beforeSteps = (String JavaDoc[]) prop;
505         }
506         
507         if (beforeSteps == null) {
508             beforeSteps = new String JavaDoc[0];
509         }
510         
511         String JavaDoc[] res = new String JavaDoc[(beforeSteps.length - 1) + panels.length];
512         for (int i = 0; i < res.length; i++) {
513             if (i < (beforeSteps.length - 1)) {
514                 res[i] = beforeSteps[i];
515             } else {
516                 res[i] = panels[i - beforeSteps.length + 1].getComponent().getName();
517             }
518         }
519         return res;
520     }
521
522     //from schema wizard
523
private JTextField JavaDoc findFileNameField(Component JavaDoc panel, String JavaDoc text) {
524         Collection JavaDoc<Component JavaDoc> allComponents = new ArrayList JavaDoc<Component JavaDoc>();
525         getAllComponents(new Component JavaDoc[] {panel}, allComponents);
526         for (Component JavaDoc c : allComponents) {
527             // we assume that the first text field is the file text field
528
if (c instanceof JTextField JavaDoc) {
529                 JTextField JavaDoc tf = (JTextField JavaDoc) c;
530                 //if (text.equals(tf.getText())) {
531
return tf;
532                 //}
533
}
534         }
535         return null;
536     }
537
538     /*
539      * Recursively gets all components in the components array and puts it in allComponents
540      */

541     public static void getAllComponents( Component JavaDoc[] components, Collection JavaDoc<Component JavaDoc> allComponents ) {
542         for( int i = 0; i < components.length; i++ ) {
543             if( components[i] != null ) {
544                 allComponents.add( components[i] );
545                 if( ( ( Container JavaDoc )components[i] ).getComponentCount() != 0 ) {
546                     getAllComponents( ( ( Container JavaDoc )components[i] ).getComponents(), allComponents );
547                 }
548             }
549         }
550     }
551
552     
553 }
554
Popular Tags