1 package uk.ac.vamsas.test.document;
\r
6 Copyright (C) 2001 Brett McLaughlin.
\r
9 Redistribution and use in source and binary forms, with or without
\r
10 modification, are permitted provided that the following conditions
\r
13 1. Redistributions of source code must retain the above copyright
\r
14 notice, this list of conditions, and the following disclaimer.
\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
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
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
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
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
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
65 // This is an XML book - no need for explicit Swing imports
\r
67 import javax.swing.*;
\r
68 import javax.swing.tree.*;
\r
71 * <b><code>SAXTreeViewer</code></b> uses Swing to graphically
\r
72 * display an XML document.
\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
79 /** The base tree to render */
\r
80 private JTree jTree;
\r
82 /** Tree model to use */
\r
83 DefaultTreeModel defaultTreeModel;
\r
86 * <p> This initializes the needed Swing settings. </p>
\r
88 public SAXTreeViewer() {
\r
89 // Handle Swing setup
\r
90 super("SAX Tree Viewer");
\r
95 * <p> This will construct the tree using Swing. </p>
\r
97 * @param filename <code>String</code> path to XML document.
\r
99 public void init(String xmlURI) throws IOException, SAXException {
\r
100 init(xmlURI, null);
\r
103 * <p> This will construct the tree using Swing. </p>
\r
105 * @param filename <code>String</code> apparent path to XML document.
\r
106 * @param inputSource <code>InputSource</code> content of XML document
\r
108 public void init(String xmlURI, InputSource inputSource) throws IOException, SAXException {
\r
110 DefaultMutableTreeNode base =
\r
111 new DefaultMutableTreeNode("XML Document: " +
\r
114 // Build the tree model
\r
115 defaultTreeModel = new DefaultTreeModel(base);
\r
116 jTree = new JTree(defaultTreeModel);
\r
118 // Construct the tree hierarchy
\r
119 if (inputSource==null) {
\r
120 buildTree(defaultTreeModel, base, xmlURI);
\r
122 buildTree(defaultTreeModel, base, xmlURI,inputSource);
\r
124 // Display the results
\r
125 getContentPane().add(new JScrollPane(jTree),
\r
126 BorderLayout.CENTER);
\r
130 * <p>This handles building the Swing UI tree.</p>
\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
138 public void buildTree(DefaultTreeModel treeModel,
\r
139 DefaultMutableTreeNode base, String xmlURI)
\r
140 throws IOException, SAXException {
\r
142 InputSource inputSource =
\r
143 new InputSource(xmlURI);
\r
144 buildTree(treeModel,base,xmlURI,inputSource);
\r
147 * <p>This handles building the Swing UI tree.</p>
\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
158 public void buildTree(DefaultTreeModel treeModel,
\r
159 DefaultMutableTreeNode base, String xmlURI, InputSource inputSource) throws IOException, SAXException {
\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
168 // Register content handler
\r
169 reader.setContentHandler(jTreeContentHandler);
\r
171 // Register error handler
\r
172 reader.setErrorHandler(jTreeErrorHandler);
\r
174 reader.parse(inputSource);
\r
176 private static org.apache.commons.logging.Log log = org.apache.commons.logging.LogFactory.getLog(SAXTreeViewer.class);
\r
179 * <p> Static entry point for running the viewer. </p>
\r
181 public static void main(String[] args) {
\r
183 File archive = new File(args[0]);
\r
184 // start watching a vamsas document archive
\r
186 log.info("Endlessly Watching file " + archive);
\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
194 // get watcher's lock to ensure state change is fixed for
\r
196 Lock chlock = w.getChangedState();
\r
197 if (first || chlock != null) {
\r
198 log.info("Got lock on "
\r
200 + (archive.exists() ? " exists l=" + archive.length()
\r
201 : "(non existant)"));
\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
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
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
220 newview.setVisible(true);
\r
222 currentview = newview;
\r
224 /* VamsasDocument d = sdoc.getVamsasDocument(vreader);
\r
226 ArchiveReports.reportDocument(d, vreader, false,
\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
240 Thread.sleep(2000);
\r
242 } catch (Exception e) {
\r
243 log.info("Going away now.",e);
\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
254 class JTreeContentHandler implements ContentHandler {
\r
256 /** Hold onto the locator for location information */
\r
257 private Locator locator;
\r
259 /** Store URI to prefix mappings */
\r
260 private Map namespaceMappings;
\r
262 /** Tree Model to add nodes to */
\r
263 private DefaultTreeModel treeModel;
\r
265 /** Current node to add sub-nodes to */
\r
266 private DefaultMutableTreeNode current;
\r
269 * <p> Set up for working with the JTree. </p>
\r
271 * @param treeModel tree to add nodes to.
\r
272 * @param base node to start adding sub-nodes to.
\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
283 * Provide reference to <code>Locator</code> which provides
\r
284 * information about where in a document callbacks occur.
\r
287 * @param locator <code>Locator</code> object tied to callback
\r
290 public void setDocumentLocator(Locator locator) {
\r
291 // Save this for later use
\r
292 this.locator = locator;
\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
302 * @throws <code>SAXException</code> when things go wrong
\r
304 public void startDocument() throws SAXException {
\r
305 // No visual events occur here
\r
310 * This indicates the end of a Document parse-this occurs after
\r
311 * all callbacks in all SAX Handlers.</code>.
\r
314 * @throws <code>SAXException</code> when things go wrong
\r
316 public void endDocument() throws SAXException {
\r
317 // No visual events occur here
\r
322 * This indicates that a processing instruction (other than
\r
323 * the XML declaration) has been encountered.
\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
330 * @throws <code>SAXException</code> when things go wrong
\r
332 public void processingInstruction(String target, String data)
\r
333 throws SAXException {
\r
335 DefaultMutableTreeNode pi =
\r
336 new DefaultMutableTreeNode("PI (target = '" + target +
\r
337 "', data = '" + data + "')");
\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
351 * @param prefix <code>String</code> prefix used for the namespace
\r
353 * @param uri <code>String</code> URI for the namespace
\r
355 * @throws <code>SAXException</code> when things go wrong
\r
357 public void startPrefixMapping(String prefix, String uri) {
\r
358 // No visual events occur here.
\r
359 namespaceMappings.put(uri, prefix);
\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
369 * @param prefix <code>String</code> of namespace being reported
\r
370 * @throws <code>SAXException</code> when things go wrong
\r
372 public void endPrefixMapping(String prefix) {
\r
373 // No visual events occur here.
\r
374 for (Iterator i = namespaceMappings.keySet().iterator();
\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
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
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
404 public void startElement(String namespaceURI, String localName,
\r
405 String qName, Attributes atts)
\r
406 throws SAXException {
\r
408 DefaultMutableTreeNode element =
\r
409 new DefaultMutableTreeNode("Element: " + localName);
\r
410 current.add(element);
\r
413 // Determine namespace
\r
414 if (namespaceURI.length() > 0) {
\r
416 (String)namespaceMappings.get(namespaceURI);
\r
417 if (prefix.equals("")) {
\r
420 DefaultMutableTreeNode namespace =
\r
421 new DefaultMutableTreeNode("Namespace: prefix = '" +
\r
422 prefix + "', URI = '" + namespaceURI + "'");
\r
423 current.add(namespace);
\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
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
440 DefaultMutableTreeNode attNamespace =
\r
441 new DefaultMutableTreeNode("Namespace: prefix = '" +
\r
442 attPrefix + "', URI = '" + attURI + "'");
\r
443 attribute.add(attNamespace);
\r
445 current.add(attribute);
\r
451 * Indicates the end of an element
\r
452 * (<code></[element name]></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
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
463 public void endElement(String namespaceURI, String localName,
\r
465 throws SAXException {
\r
467 // Walk back up the tree
\r
468 current = (DefaultMutableTreeNode)current.getParent();
\r
473 * This reports character data (within an element).
\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
481 public void characters(char[] ch, int start, int length)
\r
482 throws SAXException {
\r
484 String s = new String(ch, start, length);
\r
485 DefaultMutableTreeNode data =
\r
486 new DefaultMutableTreeNode("Character Data: '" + s + "'");
\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
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
502 public void ignorableWhitespace(char[] ch, int start, int length)
\r
503 throws SAXException {
\r
505 // This is ignorable, so don't display it
\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
515 * @param name <code>String</code> name of entity being skipped
\r
516 * @throws <code>SAXException</code> when things go wrong
\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
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
531 class JTreeErrorHandler implements ErrorHandler {
\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
540 * @param exception <code>SAXParseException</code> that occurred.
\r
541 * @throws <code>SAXException</code> when things go wrong
\r
543 public void warning(SAXParseException exception)
\r
544 throws SAXException {
\r
546 System.out.println("**Parsing Warning**\n" +
\r
548 exception.getLineNumber() + "\n" +
\r
550 exception.getSystemId() + "\n" +
\r
552 exception.getMessage());
\r
553 throw new SAXException("Warning encountered");
\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
563 * @param exception <code>SAXParseException</code> that occurred.
\r
564 * @throws <code>SAXException</code> when things go wrong
\r
566 public void error(SAXParseException exception)
\r
567 throws SAXException {
\r
569 System.out.println("**Parsing Error**\n" +
\r
571 exception.getLineNumber() + "\n" +
\r
573 exception.getSystemId() + "\n" +
\r
575 exception.getMessage());
\r
576 throw new SAXException("Error encountered");
\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
586 * @param exception <code>SAXParseException</code> that occurred.
\r
587 * @throws <code>SAXException</code> when things go wrong
\r
589 public void fatalError(SAXParseException exception)
\r
590 throws SAXException {
\r
592 System.out.println("**Parsing Fatal Error**\n" +
\r
594 exception.getLineNumber() + "\n" +
\r
596 exception.getSystemId() + "\n" +
\r
598 exception.getMessage());
\r
599 throw new SAXException("Fatal Error encountered");
\r