KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > modules > xml > xam > ui > customizer > ExternalReferenceCreator


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.xam.ui.customizer;
21
22 import java.awt.BorderLayout JavaDoc;
23 import java.awt.event.MouseAdapter JavaDoc;
24 import java.awt.event.MouseEvent JavaDoc;
25 import java.beans.PropertyChangeEvent JavaDoc;
26 import java.beans.PropertyChangeListener JavaDoc;
27 import java.io.IOException JavaDoc;
28 import java.lang.reflect.InvocationTargetException JavaDoc;
29 import java.net.URI JavaDoc;
30 import java.net.URISyntaxException JavaDoc;
31 import java.util.ArrayList JavaDoc;
32 import java.util.Collection JavaDoc;
33 import java.util.HashMap JavaDoc;
34 import java.util.LinkedList JavaDoc;
35 import java.util.List JavaDoc;
36 import java.util.Map JavaDoc;
37 import java.util.Set JavaDoc;
38 import javax.swing.ImageIcon JavaDoc;
39 import javax.swing.tree.TreePath JavaDoc;
40 import javax.swing.tree.TreeSelectionModel JavaDoc;
41 import org.netbeans.api.project.FileOwnerQuery;
42 import org.netbeans.api.project.Project;
43 import org.netbeans.modules.xml.catalogsupport.DefaultProjectCatalogSupport;
44 import org.netbeans.modules.xml.xam.Component;
45 import org.netbeans.modules.xml.xam.Model;
46 import org.netbeans.modules.xml.xam.locator.CatalogModelException;
47 import org.netbeans.modules.xml.xam.ui.ModelCookie;
48 import org.netbeans.spi.project.ui.LogicalViewProvider;
49 import org.openide.ErrorManager;
50 import org.openide.explorer.ExplorerManager;
51 import org.openide.explorer.view.TreeTableView;
52 import org.openide.explorer.view.Visualizer;
53 import org.openide.filesystems.FileObject;
54 import org.openide.loaders.DataObject;
55 import org.openide.nodes.AbstractNode;
56 import org.openide.nodes.Children;
57 import org.openide.nodes.Node;
58 import org.openide.nodes.PropertySupport;
59 import org.openide.util.NbBundle;
60 import org.openide.util.Utilities;
61
62 /**
63  * Base class for external reference creators. Unlike a customizer, a
64  * creator may create mulitple new components at a time.
65  *
66  * @author Ajit Bhate
67  * @author Nathan Fiedler
68  */

69 public abstract class ExternalReferenceCreator<T extends Component>
70         extends AbstractReferenceCustomizer<T>
71         implements ExplorerManager.Provider, PropertyChangeListener JavaDoc {
72     /** silence compiler warnings */
73     private static final long serialVersionUID = 1L;
74     /** Map of registered nodes, keyed by their representative DataObject. */
75     private Map JavaDoc<DataObject, NodeSet> registeredNodes;
76     /** The file being modified (where the import will be added). */
77     private transient FileObject sourceFO;
78     /** Used to deal with project catalogs. */
79     private transient DefaultProjectCatalogSupport catalogSupport;
80
81     /**
82      * Creates new form ExternalReferenceCreator
83      *
84      * @param component component in which to create new components.
85      * @param model model in which to create components.
86      */

87     public ExternalReferenceCreator(T component, Model JavaDoc model) {
88         super(component);
89         registeredNodes = new HashMap JavaDoc<DataObject, NodeSet>();
90         initComponents();
91         sourceFO = (FileObject) component.getModel().getModelSource().
92                 getLookup().lookup(FileObject.class);
93         catalogSupport = DefaultProjectCatalogSupport.getInstance(sourceFO);
94         init(component, model);
95         // View for selecting an external reference.
96
TreeTableView locationView = new LocationView();
97         locationView.setDefaultActionAllowed(false);
98         locationView.setPopupAllowed(false);
99         locationView.setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
100         locationView.setRootVisible(false);
101         locationView.getAccessibleContext().setAccessibleName(locationLabel.getToolTipText());
102         locationView.getAccessibleContext().setAccessibleDescription(locationLabel.getToolTipText());
103         Node.Property[] columns = new Node.Property[] {
104             new Column(ExternalReferenceDataNode.PROP_NAME, String JavaDoc.class, true),
105             new ImportColumn(referenceTypeName()),
106             new Column(ExternalReferenceDataNode.PROP_PREFIX, String JavaDoc.class, false),
107         };
108         locationView.setProperties(columns);
109         locationView.setTreePreferredWidth(200);
110         locationView.setTableColumnPreferredWidth(0, 25);
111         locationView.setTableColumnPreferredWidth(1, 25);
112         locationPanel.add(locationView, BorderLayout.CENTER);
113         explorerManager = new ExplorerManager();
114         explorerManager.addPropertyChangeListener(this);
115         explorerManager.setRootContext(createRootNode());
116     }
117
118     public void applyChanges() throws IOException JavaDoc {
119         List JavaDoc<Node> nodes = getSelectedNodes();
120         for (Node node : nodes) {
121             if (node instanceof ExternalReferenceNode) {
122                 Model JavaDoc model = ((ExternalReferenceNode) node).getModel();
123                 // Without a model, the selection is completely invalid.
124
if (model != null && model != getModelComponent().getModel()) {
125                     FileObject fileObj = (FileObject) model.getModelSource().
126                             getLookup().lookup(FileObject.class);
127                     if (fileObj != null) {
128                         try {
129                             if (catalogSupport.needsCatalogEntry(sourceFO, fileObj)) {
130                                 // Remove the previous catalog entry, then create new one.
131
URI JavaDoc uri = catalogSupport.getReferenceURI(sourceFO, fileObj);
132                                 catalogSupport.removeCatalogEntry(uri);
133                                 catalogSupport.createCatalogEntry(sourceFO, fileObj);
134                             }
135                         } catch (URISyntaxException JavaDoc use) {
136                             ErrorManager.getDefault().notify(use);
137                         } catch (IOException JavaDoc ioe) {
138                             ErrorManager.getDefault().notify(ioe);
139                         } catch (CatalogModelException cme) {
140                             ErrorManager.getDefault().notify(cme);
141                         }
142                     }
143                 }
144             }
145         }
146     }
147
148     /**
149      * Return the target namespace of the given model.
150      *
151      * @param model the model for which to get the namespace.
152      * @return target namespace, or null if none.
153      */

154     protected abstract String JavaDoc getTargetNamespace(Model JavaDoc model);
155
156     /**
157      * Retrieve the list of nodes that the user selected.
158      *
159      * @return list of selected nodes (empty if none).
160      */

161     protected List JavaDoc<Node> getSelectedNodes() {
162         List JavaDoc<Node> results = new LinkedList JavaDoc<Node>();
163         Collection JavaDoc<NodeSet> sets = registeredNodes.values();
164         for (NodeSet set : sets) {
165             if (set.isSelected()) {
166                 List JavaDoc<ExternalReferenceDataNode> nodes = set.getNodes();
167                 if (nodes.size() > 0) {
168                     // Use just one of the corresponding nodes, as the
169
// others are basically duplicates.
170
results.add(nodes.get(0));
171                 }
172             }
173         }
174         return results;
175     }
176
177     /**
178      * Check if prefix is unique on UI.
179      *
180      * @return true if Prefix is not unique on UI, false otherwise.
181      */

182     private boolean isValidPrefix(ExternalReferenceDataNode node) {
183         DataObject dobj = (DataObject) node.getLookup().lookup(DataObject.class);
184         NodeSet nodeSet = registeredNodes.get(dobj);
185         Collection JavaDoc<NodeSet> sets = registeredNodes.values();
186         for (NodeSet set : sets) {
187             // Ignore the set which contains the given node, and those
188
// sets which are not selected.
189
if (!set.equals(nodeSet) && set.isSelected()) {
190                 // Only need to check the first node, as all of them have
191
// the same prefix (or at least that is the idea).
192
ExternalReferenceDataNode other = set.getNodes().get(0);
193                 if (node.getPrefix().equals(other.getPrefix())) {
194                     return false;
195                 }
196             }
197         }
198         return true;
199     }
200
201     /**
202      * Determine the number of nodes that the user selected, useful for
203      * knowing if any nodes are selected or not.
204      *
205      * @return number of selected nodes.
206      */

207     private int countSelectedNodes() {
208         int results = 0;
209         Collection JavaDoc<NodeSet> sets = registeredNodes.values();
210         for (NodeSet set : sets) {
211             if (set.isSelected()) {
212                 List JavaDoc<ExternalReferenceDataNode> nodes = set.getNodes();
213                 if (nodes.size() > 0) {
214                     results++;
215                 }
216             }
217         }
218         return results;
219     }
220
221     /**
222      * Return the existing external reference prefixes for the given model.
223      *
224      * @param model the model for which to get the namespace.
225      * @return set of prefixes; empty if none.
226      */

227     protected abstract Map JavaDoc<String JavaDoc, String JavaDoc> getPrefixes(Model JavaDoc model);
228
229     /**
230      * Returns the NodeDecorator for this customizer, if any.
231      *
232      * @return node decorator for files nodes, or null if none.
233      */

234     protected abstract ExternalReferenceDecorator getNodeDecorator();
235
236     /**
237      * Indicates if the namespace value must be different than that of
238      * the model containing the component being customized. If false,
239      * then the opposite must hold - the namespace must be the same.
240      * The one exception is if the namespace is not defined at all.
241      *
242      * @return true if namespace must differ, false if same.
243      */

244     public abstract boolean mustNamespaceDiffer();
245
246     /**
247      * Return the proper name of the type of reference this creator is to
248      * be used for. This will become the title of the first column in the
249      * tree-table. Generally this should be something of the form of
250      * "Import", "Include", "Redefine", etc.
251      *
252      * @return human-readable name for the first column title.
253      */

254     protected abstract String JavaDoc referenceTypeName();
255
256     /**
257      * Called from constructor, after the interface components have been
258      * constructed, but before they have been initialized. Gives subclasses
259      * a chance to perform initialization based on the given component.
260      *
261      * @param component the reference to be customized.
262      * @param model the model passed to the constructor (may be null).
263      */

264     protected void init(T component, Model JavaDoc model) {
265         // Note, do not place any code here, as there is no guarantee
266
// that the subclasses will delegate to this method at all.
267
}
268
269     protected void initializeUI() {
270         if (!mustNamespaceDiffer()) {
271             namespaceLabel.setVisible(false);
272             namespaceTextField.setVisible(false);
273         }
274     }
275
276     public ExternalReferenceDataNode createExternalReferenceNode(Node original) {
277         DataObject dobj = (DataObject) original.getLookup().lookup(DataObject.class);
278         NodeSet set = registeredNodes.get(dobj);
279         if (set == null) {
280             set = new NodeSet(this);
281             registeredNodes.put(dobj, set);
282         }
283         ExternalReferenceDataNode erdn = new ExternalReferenceDataNode(
284                 original, getNodeDecorator());
285         set.add(erdn);
286         if (set.isSelected() && erdn.canSelect()) {
287             erdn.setSelected(true);
288         }
289         erdn.addPropertyChangeListener(this);
290         return erdn;
291     }
292
293     /**
294      * Indicate if this creator allows the user to select no files at all.
295      * This is useful from the new file wizard which needs to allow the
296      * user to deselect what they had previously selected.
297      *
298      * @return true if user may select no files and still be considered
299      * as valid input, false to require one or more selections.
300      */

301     protected boolean allowEmptySelection() {
302         // By default we require the user to select at least one file.
303
return false;
304     }
305
306     /**
307      * Determine if the user's input is valid or not. This will enable
308      * or disable the save/reset controls based on the results, as well
309      * as issue error messages.
310      *
311      * @param node selected node.
312      */

313     private void validateInput(ExternalReferenceNode node) {
314         String JavaDoc msg = null;
315         if (mustNamespaceDiffer() && node instanceof ExternalReferenceDataNode) {
316             ExternalReferenceDataNode erdn = (ExternalReferenceDataNode) node;
317             Map JavaDoc<String JavaDoc, String JavaDoc> prefixMap = getPrefixes(getModelComponent().getModel());
318             String JavaDoc ep = erdn.getPrefix();
319             // Must be a non-empty prefix, that is not already in use, and
320
// is unique among the selected nodes (and be selected itself).
321
if (ep.length() == 0 || prefixMap.containsKey(ep) ||
322                     (!isValidPrefix(erdn) && erdn.isSelected())) {
323                 msg = NbBundle.getMessage(ExternalReferenceCreator.class,
324                         "LBL_ExternalReferenceCreator_InvalidPrefix");
325             }
326         }
327         if (node instanceof RetrievedFilesChildren.RetrievedFileNode) {
328             RetrievedFilesChildren.RetrievedFileNode rNode =
329                     (RetrievedFilesChildren.RetrievedFileNode) node;
330             if (!rNode.isValid()) {
331                 msg = NbBundle.getMessage(ExternalReferenceCreator.class,
332                         "LBL_ExternalReferenceCreator_InvalidCatalogEntry");
333             }
334         }
335         if (msg != null) {
336             showMessage(msg);
337         }
338         int selected = countSelectedNodes();
339         // Must have selected nodes, and no error messages.
340
setSaveEnabled((allowEmptySelection() || selected > 0) && msg == null);
341     }
342
343     protected void showMessage(String JavaDoc msg) {
344         if (msg == null) {
345             messageLabel.setText(" ");
346             messageLabel.setIcon(null);
347         } else {
348             messageLabel.setText(msg);
349             // Image is in openide/dialogs module.
350
messageLabel.setIcon(new ImageIcon JavaDoc(Utilities.loadImage(
351                     "org/openide/resources/error.gif"))); // NOI18N
352
}
353     }
354
355     /**
356      * A TreeTableView that toggles the selection of the external reference
357      * data nodes using a single mouse click.
358      */

359     private class LocationView extends TreeTableView {
360         /** silence compiler warnings */
361         private static final long serialVersionUID = 1L;
362
363         /**
364          * Creates a new instance of LocationView.
365          */

366         public LocationView() {
367             super();
368             tree.addMouseListener(new MouseAdapter JavaDoc() {
369                 public void mouseClicked(MouseEvent JavaDoc e) {
370                     // Invert the selection of the data node, if such a
371
// node was clicked on.
372
TreePath JavaDoc path = tree.getPathForLocation(e.getX(), e.getY());
373                     if (path != null) {
374                         Object JavaDoc comp = path.getLastPathComponent();
375                         Node node = Visualizer.findNode(comp);
376                         if (node instanceof ExternalReferenceDataNode) {
377                             ExternalReferenceDataNode erdn =
378                                     (ExternalReferenceDataNode) node;
379                             if (erdn.canSelect()) {
380                                 boolean selected = !erdn.isSelected();
381                                 String JavaDoc ns = null;
382                                 if (selected) {
383                                     // Have to collect the namespace value
384
// when the node is selected.
385
Model JavaDoc model = erdn.getModel();
386                                     if (model != null) {
387                                         ns = getTargetNamespace(model);
388                                     }
389                                 }
390                                 // This will clear the field if the user has
391
// deselected the file, which is to prevent
392
// the user from being confused as to what
393
// the namespace field represents.
394
namespaceTextField.setText(ns);
395                                 erdn.setSelected(selected);
396                             }
397                         }
398                     }
399                 }
400             });
401         }
402     }
403
404     protected Node createRootNode() {
405         Set JavaDoc/*<Project>*/ refProjects = null;
406         if (catalogSupport.supportsCrossProject()) {
407             refProjects = catalogSupport.getProjectReferences();
408         }
409         ExternalReferenceDecorator decorator = getNodeDecorator();
410         Node[] rootNodes = new Node[1 + (refProjects == null ? 0 : refProjects.size())];
411         Project prj = FileOwnerQuery.getOwner(sourceFO);
412         LogicalViewProvider viewProvider = (LogicalViewProvider) prj.getLookup().
413                 lookup(LogicalViewProvider.class);
414         rootNodes[0] = decorator.createExternalReferenceNode(
415                 viewProvider.createLogicalView());
416         int rootIndex = 1;
417         List JavaDoc<FileObject> projectRoots = new ArrayList JavaDoc<FileObject>();
418         projectRoots.add(prj.getProjectDirectory());
419         if (refProjects != null) {
420             for (Object JavaDoc o : refProjects) {
421                 Project refPrj = (Project) o;
422                 viewProvider = (LogicalViewProvider) refPrj.getLookup().
423                         lookup(LogicalViewProvider.class);
424                 rootNodes[rootIndex++] = decorator.createExternalReferenceNode(
425                         viewProvider.createLogicalView());
426                 projectRoots.add(refPrj.getProjectDirectory());
427             }
428         }
429         FileObject[] roots = projectRoots.toArray(
430                 new FileObject[projectRoots.size()]);
431         Children fileChildren = new Children.Array();
432         fileChildren.add(rootNodes);
433         Node byFilesNode = new FolderNode(fileChildren);
434         byFilesNode.setDisplayName(NbBundle.getMessage(
435                 ExternalReferenceCreator.class,
436                 "LBL_ExternalReferenceCreator_Category_By_File"));
437
438         // Construct the By Namespace node.
439
Children nsChildren = new NamespaceChildren(roots, decorator);
440         Node byNsNode = new FolderNode(nsChildren);
441         byNsNode.setDisplayName(NbBundle.getMessage(
442                 ExternalReferenceCreator.class,
443                 "LBL_ExternalReferenceCreator_Category_By_Namespace"));
444 // Hide the Retrieved node tree until we are sure the runtime can handle
445
// URLs with respect to the catalog.
446
// Node retrievedNode;
447
// CatalogWriteModel cwm = getCatalogWriteModel();
448
// if (cwm != null) {
449
// Children rChildren = new RetrievedFilesChildren(cwm , decorator);
450
// retrievedNode = new ExternalReferenceNode(projectNode, rChildren, decorator);
451
// } else {
452
// retrievedNode = new ExternalReferenceNode(projectNode, Children.LEAF, decorator);
453
// }
454
// retrievedNode.setDisplayName(NbBundle.getMessage(
455
// ExternalReferenceCreator.class,
456
// "LBL_ExternalReferenceCreator_Category_By_Retrieved"));
457
Children categories = new Children.Array();
458 // categories.add(new Node[]{ byFilesNode, byNsNode, retrievedNode });
459
categories.add(new Node[] { byFilesNode, byNsNode });
460         Node rootNode = new AbstractNode(categories);
461         // Surprisingly, this becomes the name and description of the first column.
462
rootNode.setDisplayName(NbBundle.getMessage(ExternalReferenceCreator.class,
463                 "CTL_ExternalReferenceCreator_Column_Name_name"));
464         rootNode.setShortDescription(NbBundle.getMessage(ExternalReferenceCreator.class,
465                 "CTL_ExternalReferenceCreator_Column_Desc_name"));
466         return rootNode;
467     }
468
469 // private CatalogWriteModel getCatalogWriteModel() {
470
// try {
471
// FileObject myFobj = (FileObject) getModelComponent().getModel().
472
// getModelSource().getLookup().lookup(FileObject.class);
473
// CatalogWriteModel cwm = CatalogWriteModelFactory.getInstance().
474
// getCatalogWriteModelForProject(myFobj);
475
// return cwm;
476
// } catch (CatalogModelException cme) {
477
// }
478
// return null;
479
// }
480

481     public void propertyChange(PropertyChangeEvent JavaDoc event) {
482         String JavaDoc pname = event.getPropertyName();
483         if (ExplorerManager.PROP_SELECTED_NODES.equals(pname)) {
484             showMessage(null);
485             Node[] nodes = (Node[]) event.getNewValue();
486             // Validate the node selection.
487
if (nodes != null && nodes.length > 0 &&
488                     nodes[0] instanceof ExternalReferenceNode) {
489                 ExternalReferenceNode node = (ExternalReferenceNode) nodes[0];
490                 Model JavaDoc model = node.getModel();
491                 // Without a model, the selection is completely invalid.
492
if (model != null) {
493                     // Ask decorator if selection is valid or not.
494
String JavaDoc msg = getNodeDecorator().validate(node);
495                     if (msg != null) {
496                         showMessage(msg);
497                     } else {
498                         // If node is okay, validate the rest of the input.
499
validateInput(node);
500                     }
501                 }
502             }
503         } else if (pname.equals(ExternalReferenceDataNode.PROP_PREFIX)) {
504             ExternalReferenceDataNode erdn =
505                     (ExternalReferenceDataNode) event.getSource();
506             // Look up the node in the map of sets, and ensure they all
507
// have the same prefix.
508
String JavaDoc prefix = (String JavaDoc) event.getNewValue();
509             DataObject dobj = (DataObject) erdn.getLookup().lookup(DataObject.class);
510             NodeSet set = registeredNodes.get(dobj);
511             // Ideally the set should already exist, but cope gracefully.
512
assert set != null : "node not created by customizer";
513             if (set == null) {
514                 set = new NodeSet(this);
515                 set.add(erdn);
516             }
517             set.setPrefix(prefix);
518             validateInput(erdn);
519         } else if (pname.equals(ExternalReferenceDataNode.PROP_SELECTED)) {
520             ExternalReferenceDataNode erdn =
521                     (ExternalReferenceDataNode) event.getSource();
522             // Look up the node in the map of sets, and ensure they are all
523
// selected as a unit.
524
boolean selected = ((Boolean JavaDoc) event.getNewValue()).booleanValue();
525             DataObject dobj = (DataObject) erdn.getLookup().lookup(DataObject.class);
526             NodeSet set = registeredNodes.get(dobj);
527             // Ideally the set should already exist, but cope gracefully.
528
assert set != null : "node not created by customizer";
529             if (set == null) {
530                 set = new NodeSet(this);
531                 set.add(erdn);
532             }
533             set.setSelected(selected);
534             // Check if the current selection is valid.
535
validateInput(erdn);
536         }
537     }
538
539     /**
540      * Get the URI location for the given node.
541      *
542      * @param node Node from which to retrieve location value.
543      * @return location for given Node, or null.
544      */

545     protected String JavaDoc getLocation(Node node) {
546         String JavaDoc location = null;
547         if (node instanceof RetrievedFilesChildren.RetrievedFileNode) {
548             RetrievedFilesChildren.RetrievedFileNode rNode =
549                     (RetrievedFilesChildren.RetrievedFileNode) node;
550             if (rNode.isValid()) {
551                 String JavaDoc ns = rNode.getNamespace();
552                 if (ns == null || mustNamespaceDiffer() !=
553                         ns.equals(getTargetNamespace())) {
554                     location = rNode.getLocation();
555                 }
556             }
557         } else {
558             DataObject dobj = (DataObject) node.getLookup().
559                     lookup(DataObject.class);
560             if (dobj != null && dobj.isValid()) {
561                 FileObject fileObj = dobj.getPrimaryFile();
562                 ModelCookie cookie = (ModelCookie) dobj.getCookie(
563                         ModelCookie.class);
564                 Model JavaDoc model;
565                 try {
566                     if (cookie != null && (model = cookie.getModel()) !=
567                             getModelComponent().getModel()) {
568                         String JavaDoc ns = getTargetNamespace(model);
569                         if (ns == null || mustNamespaceDiffer() !=
570                                 ns.equals(getTargetNamespace())) {
571                             return catalogSupport.getReferenceURI(
572                                     sourceFO, fileObj).toString();
573                         }
574                     }
575                 } catch (URISyntaxException JavaDoc urise) {
576                     ErrorManager.getDefault().notify(urise);
577                 } catch (IOException JavaDoc ioe) {
578                     ErrorManager.getDefault().notify(ioe);
579                 }
580             }
581         }
582         if (location != null) {
583             try {
584                 URI JavaDoc uri = new URI JavaDoc("file", location, null);
585                 uri = uri.normalize();
586                 location = uri.getRawSchemeSpecificPart();
587             } catch (URISyntaxException JavaDoc use) {
588                 showMessage(use.toString());
589                 // Despite this, we can still use the location we have.
590
}
591         }
592         return location;
593     }
594
595     /**
596      * Get the namespace for the given node.
597      *
598      * @param node Node from which to retrieve namespace value.
599      * @return namespace for given Node, or null.
600      */

601     protected String JavaDoc getNamespace(Node node) {
602         String JavaDoc ns = null;
603         if (node instanceof RetrievedFilesChildren.RetrievedFileNode) {
604             RetrievedFilesChildren.RetrievedFileNode rNode =
605                     (RetrievedFilesChildren.RetrievedFileNode) node;
606             if (!rNode.isValid()) {
607                 return null;
608             }
609             ns = rNode.getNamespace();
610         } else {
611             DataObject dobj = (DataObject) node.getLookup().
612                     lookup(DataObject.class);
613             if (dobj != null && dobj.isValid()) {
614                 ModelCookie cookie = (ModelCookie) dobj.getCookie(
615                         ModelCookie.class);
616                 Model JavaDoc model;
617                 try {
618                     if (cookie != null && (model = cookie.getModel()) !=
619                             getModelComponent().getModel()) {
620                         ns = getTargetNamespace(model);
621                     }
622                 } catch (IOException JavaDoc ioe) {
623                     // Fall through and return null.
624
}
625             }
626         }
627         return ns;
628     }
629
630     public ExplorerManager getExplorerManager() {
631         return explorerManager;
632     }
633
634     /**
635      * A column for the reference customizer table.
636      *
637      * @author Nathan Fiedler
638      */

639     protected class Column extends PropertySupport.ReadOnly {
640         /** The keyword for this column. */
641         private String JavaDoc key;
642
643         /**
644          * Constructs a new instance of Column.
645          *
646          * @param key keyword for this column.
647          * @param type type of the property (e.g. String.class).
648          * @param tree true if this is the 'tree' column.
649          */

650         public Column(String JavaDoc key, Class JavaDoc type, boolean tree) {
651             super(key, type,
652                   NbBundle.getMessage(Column.class,
653                     "CTL_ExternalReferenceCreator_Column_Name_" + key),
654                   NbBundle.getMessage(Column.class,
655                     "CTL_ExternalReferenceCreator_Column_Desc_" + key));
656             this.key = key;
657             setValue("TreeColumnTTV", Boolean.valueOf(tree));
658         }
659
660         public Object JavaDoc getValue()
661                 throws IllegalAccessException JavaDoc, InvocationTargetException JavaDoc {
662             return key;
663         }
664     }
665
666     /**
667      * Special column for the reference customizer table's import column.
668      *
669      * @author Nathan Fiedler
670      */

671     protected class ImportColumn extends PropertySupport.ReadOnly {
672         /** The keyword for this column. */
673         private String JavaDoc key;
674
675         /**
676          * Creates a new instance of ImportColumn.
677          *
678          * @param name the column's name.
679          */

680         public ImportColumn(String JavaDoc name) {
681             super("selected", Boolean.TYPE, name,
682                   NbBundle.getMessage(Column.class,
683                     "CTL_ExternalReferenceCreator_Column_Desc_selected"));
684             this.key = "selected";
685             setValue("TreeColumnTTV", Boolean.FALSE);
686         }
687
688         public Object JavaDoc getValue()
689                 throws IllegalAccessException JavaDoc, InvocationTargetException JavaDoc {
690             return key;
691         }
692     }
693
694     /**
695      * Manages the state of a set of nodes.
696      */

697     private static class NodeSet {
698         /** The property change listener for each node. */
699         private PropertyChangeListener JavaDoc listener;
700         /** Nodes in this set. */
701         private List JavaDoc<ExternalReferenceDataNode> nodes;
702         /** True if this set is selected, false otherwise. */
703         private boolean selected;
704
705         /**
706          * Creates a new instance of NodeSet.
707          *
708          * @param listener listens to the Node.
709          */

710         public NodeSet(PropertyChangeListener JavaDoc listener) {
711             this.listener = listener;
712         }
713
714         /**
715          * Add the given node to this set.
716          *
717          * @param node node to be added to set.
718          */

719         public void add(ExternalReferenceDataNode node) {
720             if (nodes == null) {
721                 nodes = new LinkedList JavaDoc<ExternalReferenceDataNode>();
722             }
723             nodes.add(node);
724         }
725
726         /**
727          * Returns the list of nodes in this set.
728          *
729          * @return list of nodes.
730          */

731         public List JavaDoc<ExternalReferenceDataNode> getNodes() {
732             return nodes;
733         }
734
735         /**
736          * Indicates if this set is selected or not.
737          *
738          * @return true if selected, false otherwise.
739          */

740         public boolean isSelected() {
741             return selected;
742         }
743
744         /**
745          * Set the prefix for Nodes in this group.
746          *
747          * @param prefix new namespace prefix.
748          */

749         public void setPrefix(String JavaDoc prefix) {
750             for (ExternalReferenceDataNode node : nodes) {
751                 if (!node.getPrefix().equals(prefix)) {
752                     node.removePropertyChangeListener(listener);
753                     node.setPrefix(prefix);
754                     node.addPropertyChangeListener(listener);
755                 }
756             }
757         }
758
759         /**
760          * Set this group of Nodes as being selected.
761          *
762          * @param select true to select, false to de-select.
763          */

764         public void setSelected(boolean select) {
765             selected = select;
766             for (ExternalReferenceDataNode node : nodes) {
767                 if (node.canSelect()) {
768                     node.removePropertyChangeListener(listener);
769                     node.setSelected(select);
770                     node.addPropertyChangeListener(listener);
771                 }
772             }
773         }
774     }
775
776     /**
777      * This method is called from within the constructor to
778      * initializeTypeView the form.
779      * WARNING: Do NOT modify this code. The content of this method is
780      * always regenerated by the Form Editor.
781      */

782     // <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
783
private void initComponents() {
784         locationLabel = new javax.swing.JLabel JavaDoc();
785         locationPanel = new javax.swing.JPanel JavaDoc();
786         namespaceLabel = new javax.swing.JLabel JavaDoc();
787         namespaceTextField = new javax.swing.JTextField JavaDoc();
788         messageLabel = new javax.swing.JLabel JavaDoc();
789
790         locationLabel.setLabelFor(locationPanel);
791         org.openide.awt.Mnemonics.setLocalizedText(locationLabel, java.util.ResourceBundle.getBundle("org/netbeans/modules/xml/xam/ui/customizer/Bundle").getString("LBL_ExternalReferenceCreator_Location"));
792         locationLabel.setToolTipText(java.util.ResourceBundle.getBundle("org/netbeans/modules/xml/xam/ui/customizer/Bundle").getString("TIP_ExternalReferenceCreator_Location"));
793
794         locationPanel.setLayout(new java.awt.BorderLayout JavaDoc());
795
796         locationPanel.setBorder(javax.swing.BorderFactory.createEtchedBorder());
797
798         namespaceLabel.setLabelFor(namespaceTextField);
799         org.openide.awt.Mnemonics.setLocalizedText(namespaceLabel, java.util.ResourceBundle.getBundle("org/netbeans/modules/xml/xam/ui/customizer/Bundle").getString("LBL_ExternalReferenceCreator_Namespace"));
800         namespaceLabel.setToolTipText(java.util.ResourceBundle.getBundle("org/netbeans/modules/xml/xam/ui/customizer/Bundle").getString("TIP_ExternalReferenceCreator_Namespace"));
801
802         namespaceTextField.setEditable(false);
803
804         messageLabel.setForeground(new java.awt.Color JavaDoc(255, 0, 0));
805         org.openide.awt.Mnemonics.setLocalizedText(messageLabel, " ");
806
807         org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this);
808         this.setLayout(layout);
809         layout.setHorizontalGroup(
810             layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
811             .add(layout.createSequentialGroup()
812                 .addContainerGap()
813                 .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
814                     .add(locationPanel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 382, Short.MAX_VALUE)
815                     .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
816                         .add(namespaceLabel)
817                         .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
818                         .add(namespaceTextField, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 297, Short.MAX_VALUE))
819                     .add(locationLabel)
820                     .add(messageLabel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 382, Short.MAX_VALUE))
821                 .addContainerGap())
822         );
823         layout.setVerticalGroup(
824             layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
825             .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
826                 .addContainerGap()
827                 .add(locationLabel)
828                 .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
829                 .add(locationPanel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 329, Short.MAX_VALUE)
830                 .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
831                 .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
832                     .add(namespaceLabel)
833                     .add(namespaceTextField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
834                 .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
835                 .add(messageLabel)
836                 .addContainerGap())
837         );
838     }// </editor-fold>//GEN-END:initComponents
839

840     // Variables declaration - do not modify//GEN-BEGIN:variables
841
public javax.swing.JLabel JavaDoc locationLabel;
842     public javax.swing.JPanel JavaDoc locationPanel;
843     public javax.swing.JLabel JavaDoc messageLabel;
844     public javax.swing.JLabel JavaDoc namespaceLabel;
845     public javax.swing.JTextField JavaDoc namespaceTextField;
846     // End of variables declaration//GEN-END:variables
847
}
848
Popular Tags