KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > openide > loaders > TemplateWizard


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.openide.loaders;
21
22
23 import java.awt.*;
24 import java.awt.event.ActionEvent JavaDoc;
25 import java.beans.*;
26 import java.io.IOException JavaDoc;
27 import java.net.*;
28 import java.text.MessageFormat JavaDoc;
29 import java.util.*;
30 import java.util.logging.Level JavaDoc;
31 import java.util.logging.Logger JavaDoc;
32 import javax.swing.*;
33 import org.netbeans.api.progress.ProgressHandle;
34 import org.openide.*;
35 import org.openide.WizardDescriptor.Panel;
36 import org.openide.filesystems.*;
37 import org.openide.nodes.Node;
38 import org.openide.util.*;
39
40 /** Wizard for creation of new objects from a template.
41 *
42 * @author Jaroslav Tulach, Jiri Rechtacek
43 */

44 public class TemplateWizard extends WizardDescriptor {
45     /** EA that defines the wizards description */
46     private static final String JavaDoc EA_DESCRIPTION = "templateWizardURL"; // NOI18N
47
/** EA that defines custom iterator*/
48     private static final String JavaDoc EA_ITERATOR = "templateWizardIterator"; // NOI18N
49
/** EA that defines resource string to the description instead of raw URL
50      * @deprecated
51      */

52     @Deprecated JavaDoc
53     private static final String JavaDoc EA_DESC_RESOURCE = "templateWizardDescResource"; // NOI18N
54

55     /** Defines the wizards description */
56     private static final String JavaDoc CUSTOM_DESCRIPTION = "instantiatingWizardURL"; // NOI18N
57
/** Defines custom iterator */
58     private static final String JavaDoc CUSTOM_ITERATOR = "instantiatingIterator"; // NOI18N
59

60     /** See org.openide.WizardDescriptor.PROP_CONTENT_SELECTED_INDEX
61      */

62     private static final String JavaDoc PROP_CONTENT_SELECTED_INDEX = "WizardPanel_contentSelectedIndex"; // NOI18N
63
/** See org.openide.WizardDescriptor.PROP_CONTENT_DATA
64      */

65     private static final String JavaDoc PROP_CONTENT_DATA = "WizardPanel_contentData"; // NOI18N
66

67     /** prefered dimmension of the panels */
68     static java.awt.Dimension JavaDoc PREF_DIM = new java.awt.Dimension JavaDoc (560, 350);
69
70     /** panel */
71     private Panel<WizardDescriptor> templateChooser;
72     /** panel */
73     private Panel<WizardDescriptor> targetChooser;
74     /** whether to show target chooser */
75     private boolean showTargetChooser = true;
76     
77     /** Iterator for the targetChooser */
78     private Iterator targetIterator;
79     /** whole iterator */
80     private TemplateWizardIteratorWrapper iterator;
81
82     /** values for wizards */
83     private DataObject template;
84     
85     /** root of all templates */
86     private DataFolder templatesFolder;
87
88     /** class name of object to create */
89     private String JavaDoc targetName = null;
90     /** target folder*/
91     private DataFolder targetDataFolder;
92     /** This is true if we have already set a value to the title format */
93     private boolean titleFormatSet = false;
94
95     /** listens on property (steps, index) changes and updates steps pane */
96     private PropertyChangeListener pcl;
97     
98     /** Component which we are listening on for changes of steps */
99     private Component lastComp;
100     
101     private Set<DataObject> newObjects = null;
102
103     private ProgressHandle progressHandle;
104     
105     /** Creates new TemplateWizard */
106     public TemplateWizard () {
107         this (new TemplateWizardIteratorWrapper.InstantiatingIterator (new TemplateWizardIterImpl ()));
108     }
109      
110     /** Constructor to be called from public default one.
111     */

112     private TemplateWizard (TemplateWizardIteratorWrapper it) {
113         super (it);
114         
115         this.iterator = it;
116         
117         // pass this to iterator
118
iterator.initialize(this);
119
120         putProperty("WizardPanel_autoWizardStyle", Boolean.TRUE); // NOI18N
121
putProperty("WizardPanel_contentDisplayed", Boolean.TRUE); // NOI18N
122
putProperty("WizardPanel_contentNumbered", Boolean.TRUE); // NOI18N
123
setTitle(NbBundle.getMessage(TemplateWizard.class,"CTL_TemplateTitle")); //NOI18N
124
setTitleFormat(new MessageFormat JavaDoc("{0}")); // NOI18N
125
}
126
127     /** Constructor
128      * for wizards that require the target chooser or template
129      * chooser panel.
130      * @param it panel iterator instance
131      */

132     protected TemplateWizard (TemplateWizard.Iterator it) {
133         this();
134         iterator.setIterator(it, false);
135     }
136     
137     /** Initializes important settings.
138      */

139     protected void initialize () {
140         if (iterator != null) {
141             iterator.initialize(this);
142             newObjects = null;
143         }
144         super.initialize ();
145     }
146
147     /** This is method used by TemplateWizardPanel1 to change the template
148     */

149     final void setTemplateImpl (DataObject obj, boolean notify) {
150         DataObject old = template;
151         if (template != obj) {
152             template = obj;
153         }
154         setTitle (getTitleFormat().format(new Object JavaDoc[] { obj.getNodeDelegate().getDisplayName() }));
155         if (old != template) {
156             Iterator it;
157             if (
158                 obj == null ||
159                 (it = getIterator (obj)) == null
160             ) {
161                 it = defaultIterator ();
162             }
163             
164             // change type of TemplateWizard's iterator to follow type of iterator corresponding to active template
165
if (it instanceof InstantiatingIteratorBridge) {
166                 WizardDescriptor.InstantiatingIterator newIt = ((InstantiatingIteratorBridge) it).getOriginalIterator ();
167                 if (newIt instanceof WizardDescriptor.ProgressInstantiatingIterator) {
168                     TemplateWizardIteratorWrapper newIterImplWrapper = new TemplateWizardIteratorWrapper.ProgressInstantiatingIterator (this.iterator.getOriginalIterImpl ());
169                     this.iterator = newIterImplWrapper;
170                     this.setPanels (newIterImplWrapper);
171                 } else if (newIt instanceof WizardDescriptor.AsynchronousInstantiatingIterator) {
172                     TemplateWizardIteratorWrapper newIterImplWrapper = new TemplateWizardIteratorWrapper.AsynchronousInstantiatingIterator (this.iterator.getOriginalIterImpl ());
173                     this.iterator = newIterImplWrapper;
174                     this.setPanels (newIterImplWrapper);
175                 }
176             }
177             this.iterator.setIterator (it, notify);
178         }
179     }
180
181     /** Getter for template to create object from.
182      * @return template
183      */

184     public DataObject getTemplate () {
185         return template;
186     }
187
188     /** Sets the template. If under the Templates/
189     * directory it will be selected by the dialog.
190     *
191     * @param obj the template to start with
192     */

193     public void setTemplate (DataObject obj) {
194         if (obj != null) {
195             setTemplateImpl (obj, true);
196         }
197     }
198     
199     /** Setter for the folder with templates. If not specified the
200      * Templates/ folder is used.
201      *
202      * @param folder the root folder for all templates if null the
203      * default folder is used
204      */

205     public void setTemplatesFolder (DataFolder folder) {
206         templatesFolder = folder;
207     }
208     
209     /** Getter for the folder with templates.
210      * @return the folder with templates that should be used as root
211      */

212     public DataFolder getTemplatesFolder () {
213         DataFolder df = templatesFolder;
214         if (df == null) {
215             FileObject fo = Repository.getDefault ().getDefaultFileSystem ().findResource ("/Templates"); // NOI18N
216
if (fo != null && fo.isFolder ()) {
217                 return DataFolder.findFolder (fo);
218             }
219         }
220         return df;
221     }
222         
223         
224
225     /**
226      * Getter for target folder.
227      * @return the target folder
228      * @throws IOException if the target folder has not been set
229      */

230     public DataFolder getTargetFolder () throws IOException JavaDoc {
231         if (targetDataFolder == null) {
232             throw new IOException JavaDoc(NbBundle.getMessage(TemplateWizard.class, "ERR_NoFilesystem"));
233         }
234         return targetDataFolder;
235     }
236     
237     // Note: called by reflection from projects/projectui/Hacks
238
private void reload (DataObject obj) {
239         Iterator it;
240         if (
241             obj == null ||
242             (it = getIterator (obj)) == null
243         ) {
244             it = defaultIterator ();
245         }
246         this.iterator.setIterator (it, true);
247     }
248     
249     /** Sets the target folder.
250     *
251     * @param f the folder
252     */

253     public void setTargetFolder (DataFolder f) {
254         targetDataFolder = f;
255     }
256
257     /** Getter for the name of the target template.
258     * @return the name or <code>null</code> if not yet set
259     */

260     public String JavaDoc getTargetName () {
261         return targetName;
262     }
263
264     /** Setter for the name of the template.
265     * @param name name for the new object, or <code>null</code>
266     */

267     public void setTargetName (String JavaDoc name) {
268         targetName = name;
269     }
270
271     /** Returns wizard panel that is used to choose a template.
272      * @return wizard panel
273      */

274     public Panel<WizardDescriptor> templateChooser () {
275         synchronized (this) {
276             if (templateChooser == null) {
277                 templateChooser = createTemplateChooser ();
278             }
279         }
280         return templateChooser;
281     }
282
283     /** Returns wizard panel that that is used to choose target folder and
284      * name of the template.
285      * @return wizard panel
286      */

287     public Panel<WizardDescriptor> targetChooser () {
288         synchronized (this) {
289             if (targetChooser == null) {
290                 targetChooser = createTargetChooser ();
291             }
292         }
293         return targetChooser;
294     }
295     
296     /** Access method to the default iterator.
297     */

298     final synchronized Iterator defaultIterator () {
299         if (targetIterator == null) {
300             targetIterator = createDefaultIterator ();
301         }
302         return targetIterator;
303     }
304     
305     /** Method that allows subclasses to provide their own panel
306      * for choosing the template (the first panel).
307      *
308      * @return the panel
309      */

310     protected Panel<WizardDescriptor> createTemplateChooser () {
311         return new TemplateWizardPanel1 ();
312     }
313
314     /** Method that allows subclasses to second (default) panel.
315      *
316      * @return the panel
317      */

318     protected Panel<WizardDescriptor> createTargetChooser () {
319         if (showTargetChooser) {
320             return new TemplateWizardPanel2 ();
321         } else {
322             return new NewObjectWizardPanel ();
323         }
324     }
325     
326     /** Allows subclasses to provide their own default iterator
327      * the one that will be used if not special iterator is associated
328      * with selected template.
329      * <P>
330      * This implementation creates iterator that just shows the targetChooser
331      * panel.
332      *
333      * @return the iterator to use as default one
334      */

335     protected Iterator createDefaultIterator () {
336         return new DefaultIterator ();
337     }
338     
339     /** Chooses the template and instantiates it.
340     * @return set of instantiated data objects (DataObject)
341     * or null if user canceled the dialog
342     * @exception IOException I/O error
343     */

344     public Set<DataObject> instantiate() throws IOException JavaDoc {
345         showTargetChooser = true;
346         return instantiateImpl (null, null);
347     }
348
349     /** Chooses the template and instantiates it.
350     *
351     * @param template predefined template that should be instantiated
352     * @return set of instantiated data objects (DataObject)
353     * or null if user canceled the dialog
354     * @exception IOException I/O error
355     */

356     public Set<DataObject> instantiate(DataObject template) throws IOException JavaDoc {
357         showTargetChooser = true;
358         return instantiateImpl (template, null);
359     }
360
361     /** Chooses the template and instantiates it.
362     *
363     * @param template predefined template that should be instantiated
364     * @param targetFolder the target folder
365     *
366     * @return set of instantiated data objects (DataObject)
367     * or null if user canceled the dialog
368     * @exception IOException I/O error
369     */

370     public Set<DataObject> instantiate(
371         DataObject template, DataFolder targetFolder
372     ) throws IOException JavaDoc {
373         showTargetChooser = false;
374         return instantiateImpl (template, targetFolder);
375     }
376     
377     private ProgressHandle getProgressHandle () {
378         return progressHandle;
379     }
380     
381     Set<DataObject> instantiateNewObjects (ProgressHandle handle) throws IOException JavaDoc {
382         progressHandle = handle;
383         try {
384             // #17341. The problem is handling ESC -> value is not
385
// set to CANCEL_OPTION for such cases.
386
Object JavaDoc option = getValue();
387             if(option == FINISH_OPTION || option == YES_OPTION
388                 || option == OK_OPTION) {
389
390                 // show wait cursor when handling instantiate
391
showWaitCursor ();
392
393                 newObjects = handleInstantiate ();
394                 if (lastComp != null) {
395                     lastComp.removePropertyChangeListener(propL());
396                     lastComp = null;
397                 }
398             } else {
399                 if (lastComp != null) {
400                     lastComp.removePropertyChangeListener(propL());
401                     lastComp = null;
402                 }
403                 newObjects = null;
404             }
405
406         } finally {
407             
408             // set normal cursor back
409
showNormalCursor ();
410         }
411             
412         return newObjects;
413     }
414
415     /** Chooses the template and instantiates it.
416     * @param template predefined template or nothing
417     * @return set of instantiated data objects (DataObject)
418     * or null if user canceled the dialog
419     * @exception IOException I/O error
420     */

421     private Set<DataObject> instantiateImpl(
422         DataObject template, DataFolder targetFolder
423     ) throws IOException JavaDoc {
424
425         showTargetChooser |= targetFolder == null;
426         targetChooser = null;
427
428         // Bugfix #16161
429
// Message which cancelled the previous attempt to instantiate the
430
// template
431
Throwable JavaDoc thrownMessage = null;
432         
433         // Bugfix #15458: Target folder should be set before readSettings of
434
// template wizard first panel is called.
435
if (targetFolder != null) {
436             setTargetFolder (targetFolder);
437         }
438
439         if (template != null) {
440             // force new template selection
441
this.template = null;
442             setTemplate (template);
443
444             // make sure that iterator is initialized
445
if (iterator != null) {
446                 iterator.initialize(this);
447             }
448         } else if (iterator != null) {
449             iterator.initialize(this);
450             iterator.first();
451         }
452
453         try {
454             updateState();
455             // bugfix #40876, set null as initial value before show wizard
456
setValue (null);
457
458             final java.awt.Dialog JavaDoc d = DialogDisplayer.getDefault().createDialog(this);
459             // Bugfix #16161: if there was a message to the user, notify it
460
// after the dialog has been shown on screen:
461
if (thrownMessage != null) {
462                 final Throwable JavaDoc t = thrownMessage;
463                 thrownMessage = null;
464                 d.addComponentListener(new java.awt.event.ComponentAdapter JavaDoc() {
465
466                                            public void componentShown(java.awt.event.ComponentEvent JavaDoc e) {
467                                                if (t.getMessage() != null) {
468                                                    // this is only for backward compatitility (plus bugfix #15618, using errMan to log stack trace)
469
DialogDisplayer.getDefault().notifyLater(new NotifyDescriptor.Exception(t));
470                                                } else {
471                                                    // this should be used (it checks for exception
472
// annotations and severity)
473
Exceptions.printStackTrace(t);
474                                                }
475                                                d.removeComponentListener(this);
476                                            }
477                                        });
478             }
479             d.setVisible(true);
480         } catch (IllegalStateException JavaDoc ise) {
481             thrownMessage = ise;
482         }
483         
484         // here can return newObjects because instantiateNewObjects() was called
485
// from WizardDescriptor before close dialog (on Finish)
486
return newObjects;
487     }
488     
489     private void showWaitCursor () {
490         //
491
// waiting times
492
//
493
org.openide.util.Mutex.EVENT.writeAccess(new java.lang.Runnable JavaDoc() {
494
495                                                      public void run() {
496                                                          try {
497                                                              java.awt.Frame JavaDoc f = org.openide.windows.WindowManager.getDefault().getMainWindow();
498
499                                                              if (f instanceof javax.swing.JFrame JavaDoc) {
500                                                                  java.awt.Component JavaDoc c = ((javax.swing.JFrame JavaDoc) f).getGlassPane();
501
502                                                                  c.setVisible(true);
503                                                                  c.setCursor(java.awt.Cursor.getPredefinedCursor(java.awt.Cursor.WAIT_CURSOR));
504                                                              }
505                                                          }
506                                                          catch (java.lang.NullPointerException JavaDoc npe) {
507                                                              Logger.getLogger(TemplateWizard.class.getName()).log(Level.WARNING,
508                                                                                null,
509                                                                                npe);
510                                                          }
511                                                      }
512                                                  });
513     }
514     
515     private void showNormalCursor () {
516         //
517
// normal times
518
//
519
org.openide.util.Mutex.EVENT.writeAccess(new java.lang.Runnable JavaDoc() {
520
521                                                      public void run() {
522                                                          try {
523                                                              java.awt.Frame JavaDoc f = org.openide.windows.WindowManager.getDefault().getMainWindow();
524
525                                                              if (f instanceof javax.swing.JFrame JavaDoc) {
526                                                                  java.awt.Component JavaDoc c = ((javax.swing.JFrame JavaDoc) f).getGlassPane();
527
528                                                                  c.setCursor(null);
529                                                                  c.setVisible(false);
530                                                              }
531                                                          }
532                                                          catch (java.lang.NullPointerException JavaDoc npe) {
533                                                              Logger.getLogger(TemplateWizard.class.getName()).log(Level.WARNING,
534                                                                                null,
535                                                                                npe);
536                                                          }
537                                                      }
538                                                  });
539     }
540     
541
542     /** Overridden to be able to set own default value for the title format.
543      * @param format message format
544      */

545     @Override JavaDoc
546     public void setTitleFormat(MessageFormat JavaDoc format) {
547         titleFormatSet = true; // someone have set the title format
548
super.setTitleFormat(format);
549     }
550
551     /** Overridden to be able to set a default value for the title format.
552      * @return message format in title
553      */

554     @Override JavaDoc
555     public MessageFormat JavaDoc getTitleFormat () {
556         if (!titleFormatSet) {
557             // we want to call this just for the first time getTitleFormat was called
558
// and not to call it when someone else called setTitleFormat
559
setTitleFormat (new MessageFormat JavaDoc (NbBundle.getMessage(TemplateWizard.class, "CTL_TemplateTitle")));
560         }
561         return super.getTitleFormat();
562     }
563
564     
565     /** Calls iterator's instantiate. It is called when user selects
566      * a option which is not CANCEL_OPTION or CLOSED_OPTION.
567      * @throws IOException if the instantiation fails
568      * @return set of data objects that have been created (should contain
569      * at least one)
570      */

571     protected Set<DataObject> handleInstantiate() throws IOException JavaDoc {
572         return iterator.getIterator ().instantiate (this);
573     }
574     
575     /** Method to attach a description to a data object.
576     * It is suggested that the URL use the <code>nbresloc</code> protocol.
577     * @param obj data object to attach description to
578     * @param url the url with description or null if there should be
579     * no description
580     * @exception IOException if I/O fails
581     */

582     public static void setDescription (DataObject obj, URL url) throws IOException JavaDoc {
583         obj.getPrimaryFile().setAttribute(EA_DESCRIPTION, url);
584         obj.getPrimaryFile().setAttribute(CUSTOM_DESCRIPTION, url);
585     }
586
587     /** Method to get a description for a data object.
588     * @param obj data object to attach description to
589     * @return the url with description or null
590     */

591     public static URL getDescription (DataObject obj) {
592         URL desc = (URL)obj.getPrimaryFile().getAttribute(CUSTOM_DESCRIPTION);
593         if (desc != null) return desc;
594         desc = (URL)obj.getPrimaryFile().getAttribute(EA_DESCRIPTION);
595         if (desc != null) return desc;
596         // Backwards compatibility:
597
String JavaDoc rsrc = (String JavaDoc) obj.getPrimaryFile ().getAttribute (EA_DESC_RESOURCE);
598         if (rsrc != null) {
599             try {
600                 URL better = new URL ("nbresloc:/" + rsrc); // NOI18N
601
try {
602                     setDescription (obj, better);
603                 } catch (IOException JavaDoc ioe) {
604                     // Oh well, just ignore.
605
}
606                 return better;
607             } catch (MalformedURLException mfue) {
608                 Exceptions.printStackTrace(mfue);
609             }
610         }
611         return null;
612     }
613
614     /** Set a description for a data object by resource path rather than raw URL.
615      * @deprecated Use {@link #setDescription} instead.
616      * @param obj data object to set description for
617      * @param rsrc a resource string, e.g. "com/foo/MyPage.html", or <code>null</code> to clear
618      * @throws IOException if the attribute cannot be set
619      */

620     @Deprecated JavaDoc
621     public static void setDescriptionAsResource (DataObject obj, String JavaDoc rsrc) throws IOException JavaDoc {
622         if (rsrc != null && rsrc.startsWith ("/")) { // NOI18N
623
Logger.getLogger(TemplateWizard.class.getName()).warning("auto-stripping leading slash from resource path in TemplateWizard.setDescriptionAsResource: " + rsrc);
624             rsrc = rsrc.substring (1);
625         }
626         obj.getPrimaryFile ().setAttribute (EA_DESC_RESOURCE, rsrc);
627     }
628
629     /** Get a description as a resource.
630     * @param obj the data object
631     * @return the resource path, or <code>null</code> if unset (incl. if only set as a raw URL)
632     * @deprecated Use {@link #getDescription} instead.
633     */

634     @Deprecated JavaDoc
635     public static String JavaDoc getDescriptionAsResource (DataObject obj) {
636         return (String JavaDoc) obj.getPrimaryFile ().getAttribute (EA_DESC_RESOURCE);
637     }
638
639     /** Allows to attach a special Iterator to a template. This allows
640     * templates to completelly control the way they are instantiated.
641     * <P>
642     * Better way for providing an Iterator is to return it from the
643     * <code>dataobject.getCookie (TemplateWizard.Iterator.class)</code>
644     * call.
645     *
646     * @param obj data object
647     * @param iter TemplateWizard.Iterator to use for instantiation of this
648     * data object, or <code>null</code> to clear
649     * @exception IOException if I/O fails
650      *
651     * @deprecated since 2.13 you should provide the iterator from <code>getCookie</code> method
652     */

653     @Deprecated JavaDoc
654     public static void setIterator (DataObject obj, Iterator iter)
655     throws IOException JavaDoc {
656         obj.getPrimaryFile().setAttribute(CUSTOM_ITERATOR, iter);
657         obj.getPrimaryFile().setAttribute(EA_ITERATOR, iter);
658     }
659
660     /** Finds a custom iterator attached to a template that should
661     * be used to instantiate the object. First of all it checks
662     * whether there is an iterator attached by <code>setIterator</code> method, if not it asks the
663     * data object for the Iterator as cookie.
664     *
665     * @param obj the data object
666     * @return custom iterator or null
667     */

668     @SuppressWarnings JavaDoc("unchecked")
669     public static Iterator getIterator (DataObject obj) {
670         Object JavaDoc unknownIterator = obj.getPrimaryFile ().getAttribute(CUSTOM_ITERATOR);
671         if (unknownIterator == null) {
672             unknownIterator = obj.getPrimaryFile ().getAttribute(EA_ITERATOR);
673         }
674         Iterator it = null;
675         if (unknownIterator instanceof Iterator) {
676             // old style iterator
677
it = (Iterator)unknownIterator;
678         // own brigde for each one iterator type
679
} if (unknownIterator instanceof WizardDescriptor.InstantiatingIterator) {
680             it = new InstantiatingIteratorBridge((WizardDescriptor.InstantiatingIterator<WizardDescriptor>) unknownIterator);
681         }
682         if (it != null) {
683             return it;
684         }
685         
686         return obj.getCookie (Iterator.class);
687     }
688     
689     // helper check for windows, its filesystem is case insensitive (workaround the bug #33612)
690
/** Check existence of file on case insensitive filesystem.
691      * Returns true if folder contains file with given name and extension.
692      * @param folder folder for search
693      * @param name name of file
694      * @param extension extension of file
695      * @return true if file with name and extension exists, false otherwise.
696      */

697     static boolean checkCaseInsensitiveName (FileObject folder, String JavaDoc name, String JavaDoc extension) {
698         // bugfix #41277, check only direct children
699
Enumeration children = folder.getChildren (false);
700         FileObject fo;
701         while (children.hasMoreElements ()) {
702             fo = (FileObject) children.nextElement ();
703             if (extension.equalsIgnoreCase (fo.getExt ()) && name.equalsIgnoreCase (fo.getName ())) {
704                 return true;
705             }
706         }
707         return false;
708     }
709     
710     /** Overriden to add/remove listener to/from displayed component. Also make recreation
711      * of steps and content.
712      */

713     protected void updateState() {
714         super.updateState();
715         
716         if (lastComp != null) {
717             lastComp.removePropertyChangeListener(propL());
718         }
719
720         // listener
721
lastComp = iterator.current().getComponent();
722         lastComp.addPropertyChangeListener(propL());
723         
724         // compoun steps pane info
725
putProperty(PROP_CONTENT_SELECTED_INDEX,
726             new Integer JavaDoc(getContentSelectedIndex()));
727         if (getContentData() != null) {
728             putProperty(PROP_CONTENT_DATA, getContentData());
729         }
730     }
731
732     /**
733      * @return String[] content taken from first panel and delegated iterator or null if
734      * delegated iterator doesn't supplied content steps name
735      */

736     private String JavaDoc[] getContentData() {
737         Component first = templateChooser().getComponent();
738         if (iterator.current() == templateChooser()) {
739             // return first panel steps
740
return (String JavaDoc[])((JComponent)first).getClientProperty(PROP_CONTENT_DATA);
741         }
742         String JavaDoc[] cd = null;
743         Component c = iterator.current().getComponent();
744         if (c instanceof JComponent) {
745             // merge first panel name with delegated iterator steps
746
Object JavaDoc property = ((JComponent)c).getClientProperty(PROP_CONTENT_DATA);
747             if (property instanceof String JavaDoc[]) {
748                 String JavaDoc[] cont = (String JavaDoc[])property;
749                 Object JavaDoc value = ((JComponent)first).getClientProperty(PROP_CONTENT_DATA);
750                 if (value instanceof String JavaDoc[]) {
751                     cd = new String JavaDoc[cont.length + 1];
752                     cd[0] = ((String JavaDoc[])value)[0];
753                     System.arraycopy(cont, 0, cd, 1, cont.length);
754                 } else {
755                     cd = new String JavaDoc[cont.length];
756                     System.arraycopy(cont, 0, cd, 0, cont.length);
757                 }
758             }
759         }
760         return cd;
761     }
762     
763     /** Returns selected item in content
764      * @return int selected index of content
765      */

766     private int getContentSelectedIndex() {
767         if (iterator.current() == templateChooser()) {
768             return 0;
769         }
770         Component c = iterator.current().getComponent();
771         if (c instanceof JComponent) {
772             // increase supplied selected index by one (template chooser)
773
Object JavaDoc property = ((JComponent)c).getClientProperty(PROP_CONTENT_SELECTED_INDEX);
774             if ((property instanceof Integer JavaDoc)) {
775                 return ((Integer JavaDoc)property).intValue() + 1;
776             }
777         }
778         return 1;
779     }
780     
781     /** Listens on content property changes in delegated iterator. Updates Wizard
782      * descriptor properties.
783      */

784     private PropertyChangeListener propL() {
785         if (pcl == null) {
786             pcl = new PropertyChangeListener() {
787                 public void propertyChange(PropertyChangeEvent ev) {
788                     if (PROP_CONTENT_SELECTED_INDEX.equals(ev.getPropertyName())) {
789                         putProperty(PROP_CONTENT_SELECTED_INDEX,
790                             new Integer JavaDoc(getContentSelectedIndex()));
791                     } else {
792                         if ((PROP_CONTENT_DATA.equals(ev.getPropertyName())) && (getContentData() != null)) {
793                             putProperty(PROP_CONTENT_DATA, getContentData());
794                         }
795                     }
796                 }
797             };
798         }
799         return pcl;
800     }
801
802     // needs for unit test only
803
final TemplateWizardIterImpl getIterImpl () {
804         return iterator.getOriginalIterImpl ();
805     }
806
807     /** The interface for custom iterator. Enhances to WizardDescriptor.Iterator
808     * by serialization and ability to instantiate the object.
809     * <P>
810     * All Panels provided by this iterator will receive a TemplateWizard
811     * as the settings object and they are encourage to store its data by the
812     * use of <CODE>putProperty</CODE> method and read it using <code>getProperty</code>.
813     * <P>
814     * Implements <code>Node.Cookie</code> since version 2.13
815     */

816     public interface Iterator extends WizardDescriptor.Iterator<WizardDescriptor>,
817     java.io.Serializable JavaDoc, org.openide.nodes.Node.Cookie {
818         /** Instantiates the template using information provided by
819          * the wizard. If instantiation fails then wizard remains open to enable correct values.
820          *
821          * @return set of data objects that have been created (should contain
822          * at least one)
823          * @param wiz the wizard
824          * @exception IOException if the instantiation fails
825          */

826         public Set<DataObject> instantiate(TemplateWizard wiz)
827             throws IOException JavaDoc;
828         
829         /** Initializes the iterator after it is constructed.
830          * The iterator can for example obtain the {@link #targetChooser target chooser}
831          * from the wizard if it does not wish to provide its own.
832          * @param wiz template wizard that wishes to use the iterator
833          */

834         public void initialize(TemplateWizard wiz);
835         
836         /** Informs the Iterator that the TemplateWizard finished using the Iterator.
837          * The main purpose of this method is to perform cleanup tasks that should
838          * not be left on the garbage collector / default cleanup mechanisms.
839          * @param wiz wizard which is no longer being used
840          */

841         public void uninitialize(TemplateWizard wiz);
842     } // end of Iterator
843

844     /** Implementation of default iterator.
845     */

846     private final class DefaultIterator implements Iterator {
847         DefaultIterator() {}
848         
849         /** Name */
850         public String JavaDoc name () {
851             return ""; // NOI18N
852
}
853
854         /** Instantiates the template using informations provided by
855         * the wizard.
856         *
857         * @param wiz the wizard
858         * @return set of data objects that has been created (should contain
859         * at least one)
860         * @exception IOException if the instantiation fails
861         */

862         public Set<DataObject> instantiate(TemplateWizard wiz) throws IOException JavaDoc {
863             String JavaDoc n = wiz.getTargetName ();
864             DataFolder folder = wiz.getTargetFolder ();
865             DataObject template = wiz.getTemplate ();
866             DataObject obj = template.createFromTemplate (folder, n, wiz.getProperties());
867
868             // run default action (hopefully should be here)
869
final Node node = obj.getNodeDelegate ();
870             final Action a = node.getPreferredAction();
871             if (a != null) {
872                 SwingUtilities.invokeLater(new Runnable JavaDoc() {
873                     public void run() {
874                         a.actionPerformed(new ActionEvent JavaDoc(node, ActionEvent.ACTION_PERFORMED, "")); // NOI18N
875
}
876                 });
877             }
878
879             return Collections.singleton(obj);
880         }
881         
882         /** No-op implementation.
883          */

884         public void initialize(TemplateWizard wiz) {
885         }
886         
887         /** No-op implementation.
888          */

889         public void uninitialize(TemplateWizard wiz) {
890         }
891         
892         /** Get the current panel.
893         * @return the panel
894         */

895         public Panel<WizardDescriptor> current() {
896             return targetChooser ();
897         }
898         
899         /** Test whether there is a next panel.
900         * @return <code>true</code> if so
901         */

902         public boolean hasNext() {
903             return false;
904         }
905         
906         /** Test whether there is a previous panel.
907         * @return <code>true</code> if so
908         */

909         public boolean hasPrevious() {
910             return false;
911         }
912         
913         /** Move to the next panel.
914         * I.e. increment its index, need not actually change any GUI itself.
915         * @exception NoSuchElementException if the panel does not exist
916         */

917         public void nextPanel() {
918             throw new java.util.NoSuchElementException JavaDoc ();
919         }
920         
921         /** Move to the previous panel.
922         * I.e. decrement its index, need not actually change any GUI itself.
923         * @exception NoSuchElementException if the panel does not exist
924         */

925         public void previousPanel() {
926             throw new java.util.NoSuchElementException JavaDoc ();
927         }
928         
929         /** Add a listener to changes of the current panel.
930         * The listener is notified when the possibility to move forward/backward changes.
931         * @param l the listener to add
932         */

933         public void addChangeListener(javax.swing.event.ChangeListener JavaDoc l) {
934         }
935         
936         /** Remove a listener to changes of the current panel.
937         * @param l the listener to remove
938         */

939         public void removeChangeListener(javax.swing.event.ChangeListener JavaDoc l) {
940         }
941     }
942     
943     private static class InstantiatingIteratorBridge implements TemplateWizard.Iterator {
944         private WizardDescriptor.InstantiatingIterator<WizardDescriptor> instantiatingIterator;
945         public InstantiatingIteratorBridge (WizardDescriptor.InstantiatingIterator<WizardDescriptor> it) {
946             instantiatingIterator = it;
947         }
948         
949         private WizardDescriptor.InstantiatingIterator getOriginalIterator () {
950             return instantiatingIterator;
951         }
952         
953         public void addChangeListener (javax.swing.event.ChangeListener JavaDoc l) {
954             instantiatingIterator.addChangeListener (l);
955         }
956         
957         public org.openide.WizardDescriptor.Panel<WizardDescriptor> current () {
958             return instantiatingIterator.current ();
959         }
960         
961         public boolean hasNext () {
962             return instantiatingIterator.hasNext ();
963         }
964         
965         public boolean hasPrevious () {
966             return instantiatingIterator.hasPrevious ();
967         }
968         
969         public String JavaDoc name () {
970             return instantiatingIterator.name ();
971         }
972         
973         public void nextPanel () {
974             instantiatingIterator.nextPanel ();
975         }
976         
977         public void previousPanel () {
978             instantiatingIterator.previousPanel ();
979         }
980         
981         public void removeChangeListener (javax.swing.event.ChangeListener JavaDoc l) {
982             instantiatingIterator.removeChangeListener (l);
983         }
984         
985         public void initialize (TemplateWizard wiz) {
986             instantiatingIterator.initialize (wiz);
987         }
988         
989         public Set<DataObject> instantiate (TemplateWizard wiz) throws IOException JavaDoc {
990             // iterate Set and replace unexpected object with dataobjects
991
Set workSet = null;
992             if (instantiatingIterator instanceof WizardDescriptor.ProgressInstantiatingIterator) {
993                 assert wiz.getProgressHandle () != null : "ProgressHandle cannot be null.";
994                 workSet = ((ProgressInstantiatingIterator)instantiatingIterator).instantiate (wiz.getProgressHandle ());
995             } else {
996                 workSet = instantiatingIterator.instantiate ();
997             }
998             java.util.Iterator JavaDoc it = workSet.iterator ();
999             Object JavaDoc obj;
1000            DataObject dobj;
1001            Set<DataObject> resultSet = new LinkedHashSet<DataObject>(workSet.size());
1002            while (it.hasNext ()) {
1003                obj = it.next ();
1004                assert obj != null;
1005                if (obj instanceof DataObject) {
1006                    // XXX what?? aren't we adding it?
1007
continue;
1008                }
1009                if (obj instanceof FileObject) {
1010                    try {
1011                        dobj = DataObject.find ((FileObject)obj);
1012                        resultSet.add (dobj);
1013                    } catch (DataObjectNotFoundException ex) {
1014                        assert false : obj;
1015                    }
1016                } else if (obj instanceof Node) {
1017                    dobj = ((Node) obj).getCookie(DataObject.class);
1018                    assert dobj != null : obj; // XXX assertions are not appropriate here!
1019
resultSet.add (dobj);
1020                }
1021            }
1022            return resultSet;
1023        }
1024        
1025        public void uninitialize (TemplateWizard wiz) {
1026            instantiatingIterator.uninitialize (wiz);
1027        }
1028        
1029    }
1030
1031}
1032
Popular Tags