SAXTreeViewer requires java 1.5 or later.
[vamsas.git] / src / uk / ac / vamsas / test / document / SAXTreeViewer.java
1 package uk.ac.vamsas.test.document;\r
2 \r
3 \r
4 /*-- \r
5 \r
6  Copyright (C) 2001 Brett McLaughlin.\r
7  All rights reserved.\r
8  \r
9  Redistribution and use in source and binary forms, with or without\r
10  modification, are permitted provided that the following conditions\r
11  are met:\r
12  \r
13  1. Redistributions of source code must retain the above copyright\r
14     notice, this list of conditions, and the following disclaimer.\r
15  \r
16  2. Redistributions in binary form must reproduce the above copyright\r
17     notice, this list of conditions, and the disclaimer that follows \r
18     these conditions in the documentation and/or other materials \r
19     provided with the distribution.\r
20 \r
21  3. The name "Java and XML" must not be used to endorse or promote products\r
22     derived from this software without prior written permission.  For\r
23     written permission, please contact brett@newInstance.com.\r
24  \r
25  In addition, we request (but do not require) that you include in the \r
26  end-user documentation provided with the redistribution and/or in the \r
27  software itself an acknowledgement equivalent to the following:\r
28      "This product includes software developed for the\r
29       'Java and XML' book, by Brett McLaughlin (O'Reilly & Associates)."\r
30 \r
31  THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED\r
32  WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\r
33  OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\r
34  DISCLAIMED.  IN NO EVENT SHALL THE JDOM AUTHORS OR THE PROJECT\r
35  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\r
36  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\r
37  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\r
38  USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\r
39  ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\r
40  OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\r
41  OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\r
42  SUCH DAMAGE.\r
43 \r
44  */\r
45 import java.io.File;\r
46 import java.io.IOException;\r
47 import java.util.HashMap;\r
48 import java.util.Iterator;\r
49 import java.util.Map;\r
50 import org.xml.sax.Attributes;\r
51 import org.xml.sax.ContentHandler;\r
52 import org.xml.sax.ErrorHandler;\r
53 import org.xml.sax.InputSource;\r
54 import org.xml.sax.Locator;\r
55 import org.xml.sax.SAXException;\r
56 import org.xml.sax.SAXParseException;\r
57 import org.xml.sax.XMLReader;\r
58 import org.xml.sax.helpers.XMLReaderFactory;\r
59 \r
60 import uk.ac.vamsas.client.simpleclient.FileWatcher;\r
61 import uk.ac.vamsas.client.simpleclient.Lock;\r
62 import uk.ac.vamsas.client.simpleclient.SimpleDocument;\r
63 import uk.ac.vamsas.client.simpleclient.VamsasArchiveReader;\r
64 \r
65 // This is an XML book - no need for explicit Swing imports\r
66 import java.awt.*;\r
67 import javax.swing.*;\r
68 import javax.swing.tree.*;\r
69 \r
70 /**\r
71  * <b><code>SAXTreeViewer</code></b> uses Swing to graphically\r
72  *   display an XML document.\r
73  */\r
74 public class SAXTreeViewer extends JFrame {\r
75   /** Default parser to use */\r
76 private String vendorParserClass = \r
77     "org.apache.xerces.parsers.SAXParser";\r
78 \r
79 /** The base tree to render */\r
80 private JTree jTree;\r
81 \r
82 /** Tree model to use */\r
83 DefaultTreeModel defaultTreeModel;\r
84 \r
85 /**\r
86  * <p> This initializes the needed Swing settings. </p>\r
87  */\r
88 public SAXTreeViewer() {\r
89     // Handle Swing setup\r
90     super("SAX Tree Viewer");\r
91     setSize(600, 450);\r
92 }\r
93 \r
94 /**\r
95  * <p> This will construct the tree using Swing. </p>\r
96  *\r
97  * @param filename <code>String</code> path to XML document.\r
98  */\r
99 public void init(String xmlURI) throws IOException, SAXException {\r
100   init(xmlURI, null);\r
101 }\r
102 /**\r
103  * <p> This will construct the tree using Swing. </p>\r
104  *\r
105  * @param filename <code>String</code> apparent path to XML document.\r
106  * @param inputSource <code>InputSource</code> content of XML document\r
107  */\r
108   public void init(String xmlURI, InputSource inputSource) throws IOException, SAXException {\r
109     \r
110     DefaultMutableTreeNode base = \r
111         new DefaultMutableTreeNode("XML Document: " + \r
112             xmlURI);\r
113     \r
114     // Build the tree model\r
115     defaultTreeModel = new DefaultTreeModel(base);\r
116     jTree = new JTree(defaultTreeModel);\r
117 \r
118     // Construct the tree hierarchy\r
119     if (inputSource==null) {\r
120       buildTree(defaultTreeModel, base, xmlURI);\r
121     } else {\r
122       buildTree(defaultTreeModel, base, xmlURI,inputSource);\r
123     }\r
124     // Display the results\r
125     getContentPane().add(new JScrollPane(jTree), \r
126         BorderLayout.CENTER);\r
127 }\r
128 \r
129 /**\r
130  * <p>This handles building the Swing UI tree.</p>\r
131  *\r
132  * @param treeModel Swing component to build upon.\r
133  * @param base tree node to build on.\r
134  * @param xmlURI URI to build XML document from.\r
135  * @throws <code>IOException</code> - when reading the XML URI fails.\r
136  * @throws <code>SAXException</code> - when errors in parsing occur.\r
137  */\r
138 public void buildTree(DefaultTreeModel treeModel, \r
139                       DefaultMutableTreeNode base, String xmlURI) \r
140     throws IOException, SAXException {\r
141   // Parse\r
142   InputSource inputSource = \r
143       new InputSource(xmlURI);\r
144   buildTree(treeModel,base,xmlURI,inputSource);\r
145 }\r
146 /**\r
147  * <p>This handles building the Swing UI tree.</p>\r
148  *\r
149  * @param treeModel Swing component to build upon.\r
150  * @param base tree node to build on.\r
151  * @param xmlURI apparent URI to build XML document from.\r
152  * @param inputSource the xml datasource to get the content from\r
153  * @throws SAXException \r
154  * @throws IOException \r
155  * @throws <code>IOException</code> - when reading the XML URI fails.\r
156  * @throws <code>SAXException</code> - when errors in parsing occur.\r
157  */\r
158 public void buildTree(DefaultTreeModel treeModel, \r
159     DefaultMutableTreeNode base, String xmlURI, InputSource inputSource) throws IOException, SAXException {\r
160 \r
161     // Create instances needed for parsing\r
162     XMLReader reader = \r
163         XMLReaderFactory.createXMLReader(vendorParserClass);\r
164     ContentHandler jTreeContentHandler = \r
165         new JTreeContentHandler(treeModel, base);\r
166     ErrorHandler jTreeErrorHandler = new JTreeErrorHandler();\r
167 \r
168     // Register content handler\r
169     reader.setContentHandler(jTreeContentHandler);\r
170 \r
171     // Register error handler\r
172     reader.setErrorHandler(jTreeErrorHandler);\r
173 \r
174     reader.parse(inputSource);\r
175 }\r
176 private static org.apache.commons.logging.Log log = org.apache.commons.logging.LogFactory.getLog(SAXTreeViewer.class);\r
177 \r
178 /**\r
179  * <p> Static entry point for running the viewer. </p>\r
180  */\r
181 public static void main(String[] args) {\r
182     try {\r
183       File archive = new File(args[0]);\r
184       // start watching a vamsas document archive\r
185       // watch\r
186       log.info("Endlessly Watching file " + archive);\r
187       /*\r
188        * if (!archive.exists()) archive.createNewFile();\r
189        */// watch the new file... - taken straight from ClientsFileTest\r
190       FileWatcher w = new FileWatcher(archive);\r
191       SAXTreeViewer currentview = null;\r
192       boolean first=true;\r
193       while (true) {\r
194         // get watcher's lock to ensure state change is fixed for\r
195         // retrieval\r
196         Lock chlock = w.getChangedState();\r
197         if (first || chlock != null) {\r
198           log.info("Got lock on "\r
199               + archive\r
200               + (archive.exists() ? " exists l=" + archive.length()\r
201                   : "(non existant)"));\r
202           first = false;\r
203           if (archive.length() > 0) {\r
204             VamsasArchiveReader vreader = new VamsasArchiveReader(archive);\r
205             SimpleDocument sdoc = new SimpleDocument(\r
206                 "testing vamsas watcher");\r
207             try {\r
208               // pass the archive XML content to the xml viewer.\r
209               SAXTreeViewer newview = new SAXTreeViewer();\r
210               newview.init(archive.toURI().toString(), new org.xml.sax.InputSource(vreader.getVamsasDocumentStream()));\r
211               if (currentview != null)\r
212               {\r
213                 newview.setBounds(currentview.getBounds());\r
214                 // somehow copy over expanded state for existing objects and scroll state.\r
215                 // could also highlight new / modified nodes.\r
216                 newview.setVisible(true);\r
217                 currentview.setVisible(false);\r
218                 currentview.dispose();\r
219               } else {\r
220                 newview.setVisible(true);\r
221               }\r
222               currentview = newview;\r
223               \r
224               /* VamsasDocument d = sdoc.getVamsasDocument(vreader);\r
225               if (d != null) {\r
226                 ArchiveReports.reportDocument(d, vreader, false,\r
227                     System.out);\r
228               }*/\r
229               System.out\r
230                   .println("Update at "\r
231                       + System.currentTimeMillis()\r
232                       + "\n\n********************************************************\n");\r
233             } catch (Exception e) {\r
234               log.error("Unmarshalling failed.", e);\r
235             }\r
236             vreader.close();\r
237             w.setState();\r
238           } \r
239         }\r
240         Thread.sleep(2000);\r
241       }\r
242     } catch (Exception e) {\r
243       log.info("Going away now.",e);\r
244     }\r
245 }\r
246 }\r
247 \r
248 /**\r
249 * <b><code>JTreeContentHandler</code></b> implements the SAX\r
250 *   <code>ContentHandler</code> interface and defines callback\r
251 *   behavior for the SAX callbacks associated with an XML\r
252 *   document's content, bulding up JTree nodes.\r
253 */\r
254 class JTreeContentHandler implements ContentHandler {\r
255 \r
256 /** Hold onto the locator for location information */\r
257 private Locator locator;\r
258 \r
259 /** Store URI to prefix mappings */\r
260 private Map namespaceMappings;\r
261 \r
262 /** Tree Model to add nodes to */\r
263 private DefaultTreeModel treeModel;\r
264 \r
265 /** Current node to add sub-nodes to */\r
266 private DefaultMutableTreeNode current;\r
267 \r
268 /**\r
269  * <p> Set up for working with the JTree. </p>\r
270  *\r
271  * @param treeModel tree to add nodes to.\r
272  * @param base node to start adding sub-nodes to.\r
273  */\r
274 public JTreeContentHandler(DefaultTreeModel treeModel, \r
275                            DefaultMutableTreeNode base) {\r
276     this.treeModel = treeModel;\r
277     this.current = base;\r
278     this.namespaceMappings = new HashMap();\r
279 }\r
280 \r
281 /**\r
282  * <p>\r
283  *  Provide reference to <code>Locator</code> which provides\r
284  *    information about where in a document callbacks occur.\r
285  * </p>\r
286  *\r
287  * @param locator <code>Locator</code> object tied to callback\r
288  *        process\r
289  */\r
290 public void setDocumentLocator(Locator locator) {\r
291     // Save this for later use\r
292     this.locator = locator;\r
293 }\r
294 \r
295 /**\r
296  * <p>\r
297  *  This indicates the start of a Document parse-this precedes\r
298  *    all callbacks in all SAX Handlers with the sole exception\r
299  *    of <code>{@link #setDocumentLocator}</code>.\r
300  * </p>\r
301  *\r
302  * @throws <code>SAXException</code> when things go wrong\r
303  */\r
304 public void startDocument() throws SAXException {\r
305     // No visual events occur here\r
306 }\r
307 \r
308 /**\r
309  * <p>\r
310  *  This indicates the end of a Document parse-this occurs after\r
311  *    all callbacks in all SAX Handlers.</code>.\r
312  * </p>\r
313  *\r
314  * @throws <code>SAXException</code> when things go wrong\r
315  */\r
316 public void endDocument() throws SAXException {\r
317     // No visual events occur here\r
318 }\r
319 \r
320 /**\r
321  * <p>\r
322  *   This indicates that a processing instruction (other than\r
323  *     the XML declaration) has been encountered.\r
324  * </p>\r
325  *\r
326  * @param target <code>String</code> target of PI\r
327  * @param data <code>String</code containing all data sent to the PI.\r
328  *               This typically looks like one or more attribute value\r
329  *               pairs.\r
330  * @throws <code>SAXException</code> when things go wrong\r
331  */\r
332 public void processingInstruction(String target, String data)\r
333     throws SAXException {\r
334 \r
335     DefaultMutableTreeNode pi = \r
336         new DefaultMutableTreeNode("PI (target = '" + target +\r
337                                    "', data = '" + data + "')");\r
338     current.add(pi);\r
339 }\r
340 \r
341 /**\r
342  * <p>\r
343  *   This indicates the beginning of an XML Namespace prefix\r
344  *     mapping. Although this typically occurs within the root element\r
345  *     of an XML document, it can occur at any point within the\r
346  *     document. Note that a prefix mapping on an element triggers\r
347  *     this callback <i>before</i> the callback for the actual element\r
348  *     itself (<code>{@link #startElement}</code>) occurs.\r
349  * </p>\r
350  *\r
351  * @param prefix <code>String</code> prefix used for the namespace\r
352  *                being reported\r
353  * @param uri <code>String</code> URI for the namespace\r
354  *               being reported\r
355  * @throws <code>SAXException</code> when things go wrong\r
356  */\r
357 public void startPrefixMapping(String prefix, String uri) {\r
358     // No visual events occur here.\r
359     namespaceMappings.put(uri, prefix);\r
360 }\r
361 \r
362 /**\r
363  * <p>\r
364  *   This indicates the end of a prefix mapping, when the namespace\r
365  *     reported in a <code>{@link #startPrefixMapping}</code> callback\r
366  *     is no longer available.\r
367  * </p>\r
368  *\r
369  * @param prefix <code>String</code> of namespace being reported\r
370  * @throws <code>SAXException</code> when things go wrong\r
371  */\r
372 public void endPrefixMapping(String prefix) {\r
373     // No visual events occur here.\r
374     for (Iterator i = namespaceMappings.keySet().iterator(); \r
375          i.hasNext(); ) {\r
376 \r
377         String uri = (String)i.next();\r
378         String thisPrefix = (String)namespaceMappings.get(uri);\r
379         if (prefix.equals(thisPrefix)) {\r
380             namespaceMappings.remove(uri);\r
381             break;\r
382         }\r
383     }\r
384 }\r
385 \r
386 /**\r
387  * <p>\r
388  *   This reports the occurrence of an actual element. It includes\r
389  *     the element's attributes, with the exception of XML vocabulary\r
390  *     specific attributes, such as\r
391  *     <code>xmlns:[namespace prefix]</code> and\r
392  *     <code>xsi:schemaLocation</code>.\r
393  * </p>\r
394  *\r
395  * @param namespaceURI <code>String</code> namespace URI this element\r
396  *               is associated with, or an empty <code>String</code>\r
397  * @param localName <code>String</code> name of element (with no\r
398  *               namespace prefix, if one is present)\r
399  * @param qName <code>String</code> XML 1.0 version of element name:\r
400  *                [namespace prefix]:[localName]\r
401  * @param atts <code>Attributes</code> list for this element\r
402  * @throws <code>SAXException</code> when things go wrong\r
403  */\r
404 public void startElement(String namespaceURI, String localName,\r
405                          String qName, Attributes atts)\r
406     throws SAXException {\r
407 \r
408     DefaultMutableTreeNode element = \r
409         new DefaultMutableTreeNode("Element: " + localName);\r
410     current.add(element);\r
411     current = element;\r
412 \r
413     // Determine namespace\r
414     if (namespaceURI.length() > 0) {\r
415         String prefix = \r
416             (String)namespaceMappings.get(namespaceURI);\r
417         if (prefix.equals("")) {\r
418             prefix = "[None]";\r
419         }\r
420         DefaultMutableTreeNode namespace =\r
421             new DefaultMutableTreeNode("Namespace: prefix = '" +\r
422                 prefix + "', URI = '" + namespaceURI + "'");\r
423         current.add(namespace);\r
424     }\r
425 \r
426     // Process attributes\r
427     for (int i=0; i<atts.getLength(); i++) {\r
428         DefaultMutableTreeNode attribute =\r
429             new DefaultMutableTreeNode("Attribute (name = '" +\r
430                                        atts.getLocalName(i) + \r
431                                        "', value = '" +\r
432                                        atts.getValue(i) + "')");\r
433         String attURI = atts.getURI(i);\r
434         if (attURI.length() > 0) {\r
435             String attPrefix = \r
436                 (String)namespaceMappings.get(namespaceURI);\r
437             if (attPrefix.equals("")) {\r
438                 attPrefix = "[None]";\r
439             }\r
440             DefaultMutableTreeNode attNamespace =\r
441                 new DefaultMutableTreeNode("Namespace: prefix = '" +\r
442                     attPrefix + "', URI = '" + attURI + "'");\r
443             attribute.add(attNamespace);            \r
444         }\r
445         current.add(attribute);\r
446     }\r
447 }\r
448 \r
449 /**\r
450  * <p>\r
451  *   Indicates the end of an element\r
452  *     (<code>&lt;/[element name]&gt;</code>) is reached. Note that\r
453  *     the parser does not distinguish between empty\r
454  *     elements and non-empty elements, so this occurs uniformly.\r
455  * </p>\r
456  *\r
457  * @param namespaceURI <code>String</code> URI of namespace this\r
458  *                element is associated with\r
459  * @param localName <code>String</code> name of element without prefix\r
460  * @param qName <code>String</code> name of element in XML 1.0 form\r
461  * @throws <code>SAXException</code> when things go wrong\r
462  */\r
463 public void endElement(String namespaceURI, String localName,\r
464                        String qName)\r
465     throws SAXException {\r
466 \r
467     // Walk back up the tree\r
468     current = (DefaultMutableTreeNode)current.getParent();\r
469 }\r
470 \r
471 /**\r
472  * <p>\r
473  *   This reports character data (within an element).\r
474  * </p>\r
475  *\r
476  * @param ch <code>char[]</code> character array with character data\r
477  * @param start <code>int</code> index in array where data starts.\r
478  * @param length <code>int</code> index in array where data ends.\r
479  * @throws <code>SAXException</code> when things go wrong\r
480  */\r
481 public void characters(char[] ch, int start, int length)\r
482     throws SAXException {\r
483 \r
484     String s = new String(ch, start, length);\r
485     DefaultMutableTreeNode data =\r
486         new DefaultMutableTreeNode("Character Data: '" + s + "'");\r
487     current.add(data);\r
488 }\r
489 \r
490 /**\r
491  * <p>\r
492  * This reports whitespace that can be ignored in the\r
493  * originating document. This is typically invoked only when\r
494  * validation is ocurring in the parsing process.\r
495  * </p>\r
496  *\r
497  * @param ch <code>char[]</code> character array with character data\r
498  * @param start <code>int</code> index in array where data starts.\r
499  * @param end <code>int</code> index in array where data ends.\r
500  * @throws <code>SAXException</code> when things go wrong\r
501  */\r
502 public void ignorableWhitespace(char[] ch, int start, int length)\r
503     throws SAXException {\r
504     \r
505     // This is ignorable, so don't display it\r
506 }\r
507 \r
508 /**\r
509  * <p>\r
510  *   This reports an entity that is skipped by the parser. This\r
511  *     should only occur for non-validating parsers, and then is still\r
512  *     implementation-dependent behavior.\r
513  * </p>\r
514  *\r
515  * @param name <code>String</code> name of entity being skipped\r
516  * @throws <code>SAXException</code> when things go wrong\r
517  */\r
518 public void skippedEntity(String name) throws SAXException {\r
519     DefaultMutableTreeNode skipped =\r
520         new DefaultMutableTreeNode("Skipped Entity: '" + name + "'");\r
521     current.add(skipped);\r
522 }\r
523 }\r
524 \r
525 /**\r
526 * <b><code>JTreeErrorHandler</code></b> implements the SAX\r
527 *   <code>ErrorHandler</code> interface and defines callback\r
528 *   behavior for the SAX callbacks associated with an XML\r
529 *   document's warnings and errors.\r
530 */\r
531 class JTreeErrorHandler implements ErrorHandler {\r
532 \r
533 /**\r
534  * <p>\r
535  * This will report a warning that has occurred; this indicates\r
536  *   that while no XML rules were "broken", something appears\r
537  *   to be incorrect or missing.\r
538  * </p>\r
539  *\r
540  * @param exception <code>SAXParseException</code> that occurred.\r
541  * @throws <code>SAXException</code> when things go wrong \r
542  */\r
543 public void warning(SAXParseException exception)\r
544     throws SAXException {\r
545         \r
546     System.out.println("**Parsing Warning**\n" +\r
547                        "  Line:    " + \r
548                           exception.getLineNumber() + "\n" +\r
549                        "  URI:     " + \r
550                           exception.getSystemId() + "\n" +\r
551                        "  Message: " + \r
552                           exception.getMessage());        \r
553     throw new SAXException("Warning encountered");\r
554 }\r
555 \r
556 /**\r
557  * <p>\r
558  * This will report an error that has occurred; this indicates\r
559  *   that a rule was broken, typically in validation, but that\r
560  *   parsing can reasonably continue.\r
561  * </p>\r
562  *\r
563  * @param exception <code>SAXParseException</code> that occurred.\r
564  * @throws <code>SAXException</code> when things go wrong \r
565  */\r
566 public void error(SAXParseException exception)\r
567     throws SAXException {\r
568     \r
569     System.out.println("**Parsing Error**\n" +\r
570                        "  Line:    " + \r
571                           exception.getLineNumber() + "\n" +\r
572                        "  URI:     " + \r
573                           exception.getSystemId() + "\n" +\r
574                        "  Message: " + \r
575                           exception.getMessage());\r
576     throw new SAXException("Error encountered");\r
577 }\r
578 \r
579 /**\r
580  * <p>\r
581  * This will report a fatal error that has occurred; this indicates\r
582  *   that a rule has been broken that makes continued parsing either\r
583  *   impossible or an almost certain waste of time.\r
584  * </p>\r
585  *\r
586  * @param exception <code>SAXParseException</code> that occurred.\r
587  * @throws <code>SAXException</code> when things go wrong \r
588  */\r
589 public void fatalError(SAXParseException exception)\r
590     throws SAXException {\r
591 \r
592     System.out.println("**Parsing Fatal Error**\n" +\r
593                        "  Line:    " + \r
594                           exception.getLineNumber() + "\n" +\r
595                        "  URI:     " + \r
596                           exception.getSystemId() + "\n" +\r
597                        "  Message: " + \r
598                           exception.getMessage());        \r
599     throw new SAXException("Fatal Error encountered");\r
600 }\r
601 }