KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > dom > traversal > IteratorView


1 /*
2  * Copyright 1999,2000,2004,2005 The Apache Software Foundation.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */

16 package dom.traversal;
17
18 import java.awt.BorderLayout JavaDoc;
19 import java.awt.Dimension JavaDoc;
20 import java.awt.event.ActionEvent JavaDoc;
21 import java.awt.event.ActionListener JavaDoc;
22 import java.util.Enumeration JavaDoc;
23 import java.util.Hashtable JavaDoc;
24
25 import javax.swing.BorderFactory JavaDoc;
26 import javax.swing.JButton JavaDoc;
27 import javax.swing.JCheckBox JavaDoc;
28 import javax.swing.JFrame JavaDoc;
29 import javax.swing.JList JavaDoc;
30 import javax.swing.JPanel JavaDoc;
31 import javax.swing.JScrollPane JavaDoc;
32 import javax.swing.JTextArea JavaDoc;
33 import javax.swing.JTextField JavaDoc;
34 import javax.swing.event.ListSelectionEvent JavaDoc;
35 import javax.swing.event.ListSelectionListener JavaDoc;
36 import javax.swing.event.TreeSelectionEvent JavaDoc;
37 import javax.swing.event.TreeSelectionListener JavaDoc;
38 import javax.swing.tree.DefaultTreeModel JavaDoc;
39 import javax.swing.tree.MutableTreeNode JavaDoc;
40 import javax.swing.tree.TreeNode JavaDoc;
41 import javax.swing.tree.TreePath JavaDoc;
42 import javax.swing.tree.TreeSelectionModel JavaDoc;
43
44 import org.apache.xerces.parsers.DOMParser;
45 import org.w3c.dom.DOMException JavaDoc;
46 import org.w3c.dom.Document JavaDoc;
47 import org.w3c.dom.Node JavaDoc;
48 import org.w3c.dom.traversal.DocumentTraversal;
49 import org.w3c.dom.traversal.NodeFilter;
50 import org.w3c.dom.traversal.NodeIterator;
51 import org.xml.sax.ErrorHandler JavaDoc;
52 import org.xml.sax.SAXException JavaDoc;
53 import org.xml.sax.SAXParseException JavaDoc;
54
55 import ui.DOMTreeFull;
56
57 /** This class shows a DOM Document in a JTree, and presents controls
58  * which allow the user to create and view the progress of a NodeIterator
59  * in the DOM tree.
60  */

61 public class IteratorView
62     extends JFrame JavaDoc
63     implements ActionListener JavaDoc {
64     
65     private static final long serialVersionUID = 3256726186452662580L;
66     
67     Document JavaDoc document;
68     TreeNode JavaDoc lastSelected;
69     DOMParser parser;
70     JTextArea JavaDoc messageText;
71     JScrollPane JavaDoc messageScroll;
72     DOMTreeFull jtree;
73     NodeIterator iterator;
74     NameNodeFilter nameNodeFilter;
75     
76     JButton JavaDoc nextButton;
77     JButton JavaDoc prevButton;
78     JButton JavaDoc removeButton;
79     JButton JavaDoc addButton;
80     JTextField JavaDoc addText;
81     JButton JavaDoc newIterator;
82     JList JavaDoc whatToShow;
83     JCheckBox JavaDoc match;
84     JTextField JavaDoc nameFilter;
85     String JavaDoc whatArray[] = new String JavaDoc [] {
86             "ALL",
87             "ELEMENT",
88             "ATTRIBUTE",
89             "TEXT",
90             "CDATA_SECTION",
91             "ENTITY_REFERENCE",
92             "ENTITY",
93             "PROCESSING_INSTRUCTION",
94             "COMMENT",
95             "DOCUMENT",
96             "DOCUMENT_TYPE",
97             "DOCUMENT_FRAGMENT",
98             "NOTATION"
99             };
100     JCheckBox JavaDoc expandERs;
101     
102     Hashtable JavaDoc treeNodeMap = new Hashtable JavaDoc();
103     
104     
105     /** main */
106     public static void main (String JavaDoc args[]) {
107
108         if (args.length > 0) {
109             String JavaDoc filename = args[0];
110             try {
111                 IteratorView frame = new IteratorView(filename) ;
112                 frame.addWindowListener(new java.awt.event.WindowAdapter JavaDoc() {
113                  public void windowClosing(java.awt.event.WindowEvent JavaDoc e) {
114                      System.exit(0);
115                  }
116                 });
117                 frame.setSize(640, 480);
118                 frame.setVisible(true);
119                 } catch (Exception JavaDoc e) {
120                     e.printStackTrace(System.err);
121                 }
122         }
123     }
124     
125     /** Constructor */
126     public IteratorView (String JavaDoc filename) {
127         super("IteratorView: "+filename);
128         try {
129             parser = new DOMParser();
130             parser.setFeature("http://apache.org/xml/features/dom/defer-node-expansion", true);
131             parser.setFeature("http://apache.org/xml/features/continue-after-fatal-error", true);
132             Errors errors = new Errors();
133             parser.setErrorHandler(errors);
134             parser.parse(filename);
135             document = parser.getDocument();
136             
137             if (!document.isSupported("Traversal", "2.0")) {
138                 // This cannot happen with ou DOMParser...
139
throw new RuntimeException JavaDoc("This DOM Document does not support Traversal");
140             }
141
142             // jtree UI setup
143
jtree = new DOMTreeFull((Node JavaDoc)document);
144             jtree.getSelectionModel().setSelectionMode
145                 (TreeSelectionModel.SINGLE_TREE_SELECTION);
146             jtree.setRootVisible(false);
147
148             // Listen for when the selection changes, call nodeSelected(node)
149
jtree.addTreeSelectionListener(
150                 new TreeSelectionListener JavaDoc() {
151                     public void valueChanged(TreeSelectionEvent JavaDoc e) {
152                         TreePath JavaDoc path = (TreePath JavaDoc)e.getPath();
153                         TreeNode JavaDoc treeNode = (TreeNode JavaDoc)path.getLastPathComponent();
154                         if(jtree.getSelectionModel().isPathSelected(path))
155                                 nodeSelected(treeNode);
156                     }
157                 }
158             );
159             
160             
161             //expandTree();
162

163                         
164             // controls
165

166             //iterate panel
167
JPanel JavaDoc iteratePanel = new JPanel JavaDoc();
168             iteratePanel.setBorder(BorderFactory.createCompoundBorder(
169                 BorderFactory.createTitledBorder("Iterate"),
170                 BorderFactory.createEmptyBorder(4, 4, 4, 4)
171                 ));
172             
173             prevButton = new JButton JavaDoc("Previous");
174             iteratePanel.add(prevButton);
175             prevButton.addActionListener(this);
176             
177             nextButton = new JButton JavaDoc("Next");
178             iteratePanel.add(nextButton);
179             nextButton.addActionListener(this);
180         
181             //DOM tree panel
182
JPanel JavaDoc domPanel = new JPanel JavaDoc();
183             domPanel.setLayout(new BorderLayout JavaDoc());
184             domPanel.setBorder(BorderFactory.createCompoundBorder(
185                 BorderFactory.createTitledBorder("Selected Node"),
186                 BorderFactory.createEmptyBorder(4, 4, 4, 4)
187                 ));
188             
189             removeButton = new JButton JavaDoc("Remove Selected Node");
190             domPanel.add(removeButton, BorderLayout.NORTH);
191             removeButton.addActionListener(this);
192             
193             addButton = new JButton JavaDoc("Add Text Node");
194             addText = new JTextField JavaDoc(10);
195             domPanel.add(addButton, BorderLayout.CENTER);
196             domPanel.add(addText, BorderLayout.SOUTH);
197             addButton.addActionListener(this);
198          
199             // iterator settings
200
JPanel JavaDoc settingsPanel = new JPanel JavaDoc();
201             settingsPanel.setLayout(new BorderLayout JavaDoc());
202             settingsPanel.setBorder(BorderFactory.createCompoundBorder(
203                 BorderFactory.createTitledBorder("Iterator Settings"),
204                 BorderFactory.createEmptyBorder(4, 4, 4, 4)
205                 ));
206             JPanel JavaDoc iteratorPanel = new JPanel JavaDoc();
207             newIterator = new JButton JavaDoc("createNodeIterator");
208             expandERs = new JCheckBox JavaDoc("expandEntityReferences");
209             iteratorPanel.add(newIterator);
210             expandERs.setSelected(true);
211             iteratorPanel.add(expandERs);
212             settingsPanel.add(iteratorPanel, BorderLayout.NORTH);
213             newIterator.addActionListener(this);
214     
215             JPanel JavaDoc whatPanel = new JPanel JavaDoc();
216             whatPanel.setBorder(BorderFactory.createCompoundBorder(
217                 BorderFactory.createTitledBorder("whatToShow"),
218                 BorderFactory.createEmptyBorder(4, 4, 4, 4)
219                 ));
220             whatToShow = new JList JavaDoc(DOMTreeFull.whatArray);
221             JScrollPane JavaDoc whatScroll =
222             new JScrollPane JavaDoc(whatToShow) {
223                     private static final long serialVersionUID = 3546357344813724213L;
224                     public Dimension JavaDoc getPreferredSize(){
225                         return new Dimension JavaDoc(200, 75 );
226                     }
227                 };
228             
229             whatPanel.add(whatScroll);
230             
231             
232             JPanel JavaDoc filterPanel = new JPanel JavaDoc();
233             filterPanel.setBorder(BorderFactory.createCompoundBorder(
234                 BorderFactory.createTitledBorder("NodeNameFilter"),
235                 BorderFactory.createEmptyBorder(4, 4, 4, 4)
236                 ));
237             filterPanel.setLayout(new BorderLayout JavaDoc());
238             match = new JCheckBox JavaDoc("match/ignore node name", true);
239             nameFilter = new JTextField JavaDoc(10);
240             filterPanel.add(match, BorderLayout.NORTH);
241             filterPanel.add(nameFilter, BorderLayout.SOUTH);
242             
243             settingsPanel.add(whatPanel, BorderLayout.WEST);
244             settingsPanel.add(filterPanel, BorderLayout.EAST);
245             
246
247             // Listen for when the selection changes, call nodeSelected(node)
248
whatToShow.addListSelectionListener(
249                 new ListSelectionListener JavaDoc() {
250                     public void valueChanged(ListSelectionEvent JavaDoc e) {
251                         // do nothing on selection...
252
}
253                 }
254             );
255             
256             
257             JPanel JavaDoc controlsPanel = new JPanel JavaDoc(new BorderLayout JavaDoc());
258             JPanel JavaDoc buttonsPanel = new JPanel JavaDoc(new BorderLayout JavaDoc());
259             buttonsPanel.add(iteratePanel, BorderLayout.NORTH);
260             buttonsPanel.add(domPanel, BorderLayout.SOUTH);
261             controlsPanel.add(buttonsPanel, BorderLayout.WEST);
262             controlsPanel.add(settingsPanel, BorderLayout.CENTER);
263             
264             controlsPanel.setBorder(BorderFactory.createCompoundBorder(
265                 BorderFactory.createTitledBorder("Controls"),
266                 BorderFactory.createEmptyBorder(4, 4, 4, 4)
267                 ));
268                 
269                 
270             // tree panel
271
JPanel JavaDoc treePanel = new JPanel JavaDoc(new BorderLayout JavaDoc());
272                 
273             JScrollPane JavaDoc treeScroll = new JScrollPane JavaDoc(jtree) ;
274             treeScroll.setBorder(BorderFactory.createCompoundBorder(
275                 BorderFactory.createTitledBorder("Tree View"),
276                 BorderFactory.createEmptyBorder(4, 4, 4, 4)
277                 ));
278
279             // message text UI setup
280
messageText = new JTextArea JavaDoc(3,5);
281
282             JPanel JavaDoc messagePanel = new JPanel JavaDoc(new BorderLayout JavaDoc());
283             messageScroll = new JScrollPane JavaDoc(messageText);
284             messagePanel.add(messageScroll);
285             messagePanel.setBorder(BorderFactory.createCompoundBorder(
286                 BorderFactory.createTitledBorder("Messages"),
287                 BorderFactory.createEmptyBorder(4, 4, 4, 4)
288                 ));
289             
290             JPanel JavaDoc mainPanel = new JPanel JavaDoc();
291             mainPanel.setLayout(new BorderLayout JavaDoc());
292             mainPanel.add(controlsPanel, BorderLayout.NORTH);
293             mainPanel.add(treeScroll, BorderLayout.CENTER);
294             mainPanel.add(messagePanel, BorderLayout.SOUTH);
295             getContentPane().add(mainPanel);
296             
297             Hashtable JavaDoc errorNodes = errors.getErrorNodes();
298             Enumeration JavaDoc elements = errorNodes.elements();
299             while (elements.hasMoreElements()) {
300                 //*** append errors to messageText
301
messageText.append( (String JavaDoc)elements.nextElement());
302             }
303             
304             // This cast must work, because we have tested above
305
// with document.isSupported("Traversal")
306
iterator = ((DocumentTraversal)document).
307                 createNodeIterator(
308                     document,
309                     NodeFilter.SHOW_ALL,
310                     new NameNodeFilter(),
311                     true);
312             
313         } catch (Exception JavaDoc e) {
314             e.printStackTrace(System.err);
315         }
316     }
317     
318     public void actionPerformed(ActionEvent JavaDoc e) {
319         
320         if (e.getSource() == newIterator) {
321             Node JavaDoc node = document;
322             
323             // whatToShow section
324
int [] indices = whatToShow.getSelectedIndices();
325             int mask = 0x0;
326             for (int i = 0; i < indices.length; i++) {
327                 if (indices[i] == 0) {
328                     mask = 0xFFFF;
329                     break;
330                 } else {
331                     mask = mask | 1<<indices[i]-1;
332                 }
333             }
334             // filter section
335
String JavaDoc nameText = nameFilter.getText();
336             boolean matched = match.isSelected();
337             if (nameNodeFilter==null) {
338                 nameNodeFilter = new NameNodeFilter();
339             }
340             if (nameText.equals("")) {
341                 setMessage("NodeNameFilter name is \"\". Assuming null.");
342                 nameText = null;
343             }
344             nameNodeFilter.setName(nameText);
345             nameNodeFilter.setMatch(matched);
346             
347             if (iterator !=null) iterator.detach();
348             boolean expand = expandERs.isSelected();
349             iterator = ((DocumentTraversal)document).
350                 createNodeIterator(
351                     node,
352                     (short)mask,
353                     nameNodeFilter,
354                     expand);
355             setMessage("doc.createNodeIterator("+
356                         " root="+node+
357                         ", whatToShow="+mask+
358                         ", match="+matched+
359                         ", name="+nameText+")"
360                         );
361             return;
362             
363         }
364         
365         if (e.getSource() == addButton) {
366             
367             String JavaDoc text = addText.getText();
368             
369             if (text==null) return;
370             
371             TreeNode JavaDoc treeNode = (TreeNode JavaDoc)jtree.getLastSelectedPathComponent();
372             if (treeNode == null) {
373                 messageText.append("Must select a tree component to add a child to it.");
374                 return;
375             }
376             TreePath JavaDoc path = new TreePath JavaDoc(
377                     ((DefaultTreeModel JavaDoc)jtree.getModel()).getPathToRoot(treeNode));
378             if (path == null) {
379                 setMessage("Could not create a path.");
380                 return;
381             }
382             if(!jtree.getSelectionModel().isPathSelected(path))
383                 return;
384             Node JavaDoc node = jtree.getNode(treeNode);
385             Node JavaDoc textNode = document.createTextNode(text);
386             try {
387                 node.appendChild(textNode);
388             } catch (DOMException JavaDoc dome) {
389                 setMessage("DOMException:"+dome.code+", "+dome);
390                 return;
391             }
392             ((DOMTreeFull.Model)jtree.getModel()).insertNode(textNode, (MutableTreeNode JavaDoc)treeNode);
393             
394             return;
395         }
396         if (e.getSource() == nextButton) {
397             Node JavaDoc node = iterator.nextNode();
398             if (node==null) {
399                 setMessage("iterator.nextNode() == null");
400                 return;
401             }
402             
403             setMessage("iterator.nextNode() == "+node);
404
405             TreeNode JavaDoc treeNode = jtree.getTreeNode(node);
406             if (treeNode == null) {
407                 setMessage("No JTree TreeNode for Node name:" + node.getNodeName());
408                 return;
409             }
410             
411             TreePath JavaDoc path = new TreePath JavaDoc(
412                     ((DefaultTreeModel JavaDoc)jtree.getModel()).getPathToRoot(treeNode));
413             jtree.requestFocus();
414             jtree.setSelectionPath(path);
415             jtree.scrollPathToVisible(path);
416             return;
417         }
418         
419         if (e.getSource() == prevButton) {
420             Node JavaDoc node = iterator.previousNode();
421             if (node==null) {
422                 setMessage("iterator.previousNode() == null");
423                 return;
424             }
425             
426             setMessage("iterator.previousNode() == "+node);
427
428             TreeNode JavaDoc treeNode = jtree.getTreeNode(node);
429             if (treeNode == null) {
430                 setMessage("No JTree TreeNode for Node name:" + node.getNodeName());
431                 return;
432             }
433             
434             TreePath JavaDoc path = new TreePath JavaDoc(
435                     ((DefaultTreeModel JavaDoc)jtree.getModel()).getPathToRoot(treeNode));
436             jtree.requestFocus();
437             jtree.setSelectionPath(path);
438             jtree.scrollPathToVisible(path);
439             return;
440         }
441         if (e.getSource() == removeButton) {
442             
443             /** If the node is not selected don't remove. */
444             TreeNode JavaDoc treeNode = (TreeNode JavaDoc)jtree.getLastSelectedPathComponent();
445             if (treeNode == null) {
446                 messageText.append("Must select a tree component to remove it.");
447                 return;
448             }
449             TreePath JavaDoc path = new TreePath JavaDoc(
450                     ((DefaultTreeModel JavaDoc)jtree.getModel()).getPathToRoot(treeNode));
451             if (path == null) {
452                 setMessage("Could not create a path.");
453                 return;
454             }
455             if(!jtree.getSelectionModel().isPathSelected(path))
456                 return;
457             Node JavaDoc node = jtree.getNode(treeNode);
458             if (node == null) return;
459             Node JavaDoc parent = node.getParentNode();
460             if (parent == null) return;
461             
462             parent.removeChild(node);
463     
464             ((DefaultTreeModel JavaDoc)jtree.getModel()).removeNodeFromParent((MutableTreeNode JavaDoc)treeNode);
465             return;
466         }
467         
468     }
469     
470     /** Helper function to set messages */
471     void setMessage(String JavaDoc string) {
472         messageText.selectAll();
473         messageText.cut();
474         messageText.append(string);
475         messageText.setCaretPosition(0);
476     }
477         
478     /** called when our JTree's nodes are selected.
479      */

480     void nodeSelected(TreeNode JavaDoc treeNode) {
481
482         lastSelected = treeNode;
483         Node JavaDoc node = jtree.getNode(treeNode);
484         
485         System.out.println("nodeSelected.node="+node);
486         if (node == null) return;
487                             
488         setMessage(DOMTreeFull.toString(node));
489     }
490     
491     /** Utility function to expand the jtree */
492     void expandTree() {
493         for (int i = 0; i < jtree.getRowCount(); i++) {
494             jtree.expandRow(i);
495         }
496     }
497     
498     class Errors implements ErrorHandler JavaDoc {
499
500         Hashtable JavaDoc errorNodes = new Hashtable JavaDoc();
501
502         public void warning(SAXParseException JavaDoc ex) {
503             store(ex, "[Warning]");
504         }
505
506         public void error(SAXParseException JavaDoc ex) {
507             store(ex, "[Error]");
508         }
509
510         public void fatalError(SAXParseException JavaDoc ex) throws SAXException JavaDoc {
511             store(ex, "[Fatal Error]");
512         }
513
514         public Hashtable JavaDoc getErrorNodes() {
515             return errorNodes;
516         }
517
518         public Object JavaDoc getError(Node JavaDoc node) {
519             return errorNodes.get(node);
520         }
521
522         public void clearErrors() {
523             errorNodes.clear();
524         }
525
526         void store(SAXParseException JavaDoc ex, String JavaDoc type) {
527
528             // build error text
529
String JavaDoc errorString= type+" at line number, "+ex.getLineNumber()
530                 +": "+ex.getMessage()+"\n";
531             Node JavaDoc currentNode = null;
532             try {
533                 currentNode = (Node JavaDoc)parser.getProperty("http://apache.org/xml/properties/dom-node");
534             } catch (SAXException JavaDoc se) {
535                 System.err.println(se.getMessage());
536                 return;
537             }
538             if (currentNode == null) return;
539
540             // accumulate any multiple errors per node in the Hashtable.
541
String JavaDoc previous = (String JavaDoc) errorNodes.get(currentNode);
542             if (previous != null)
543                 errorNodes.put(currentNode, previous +errorString);
544             else
545                 errorNodes.put(currentNode, errorString);
546         }
547     }
548     
549 }
550
Popular Tags