1 9 10 package org.dom4j.samples; 11 12 import org.dom4j.Document; 13 import org.dom4j.DocumentException; 14 import org.dom4j.io.OutputFormat; 15 import org.dom4j.io.XMLWriter; 16 17 23 public abstract class AbstractDemo { 24 25 26 protected OutputFormat format = new OutputFormat(); 27 28 29 protected XMLWriter writer; 30 31 public AbstractDemo() { 32 } 33 34 protected static void run(AbstractDemo demo, String [] args) { 35 try { 36 demo.run(args); 37 } catch (DocumentException e) { 38 System.out.println("Exception occurred: " + e); 39 Throwable nestedException = e.getNestedException(); 40 if (nestedException != null) { 41 System.out.println("NestedException: " + nestedException); 42 nestedException.printStackTrace(); 43 } else { 44 e.printStackTrace(); 45 } 46 } catch (Throwable t) { 47 System.out.println("Exception occurred: " + t); 48 t.printStackTrace(); 49 } 50 } 51 52 public void run(String [] args) throws Exception { 53 if (args.length < 1) { 54 printUsage("no XML document URL specified"); 55 return; 56 } 57 58 int idx = format.parseOptions(args, 0); 59 if (idx >= args.length) { 60 printUsage("no XML document URL specified"); 61 return; 62 } else { 63 writer = createXMLWriter(); 64 65 Document document = parse(args[idx]); 66 process(document); 67 } 68 } 69 70 protected Document parse(String xmlFile) throws Exception { 71 throw new RuntimeException ( 72 "parse(String xmlFile) not implemented in this demo"); 73 } 74 75 protected void process(Document document) throws Exception { 76 getXMLWriter().write(document); 77 getXMLWriter().flush(); 78 } 79 80 protected void print(String text) { 81 System.out.print(text); 82 } 83 84 protected void println(String text) { 85 System.out.println(text); 86 } 87 88 protected void printUsage(String text) { 89 println("Usage: java " + getClass().getName() + " " + text); 90 } 91 92 protected XMLWriter getXMLWriter() throws Exception { 93 if (writer == null) { 94 writer = createXMLWriter(); 95 } 96 return writer; 97 } 98 99 103 protected XMLWriter createXMLWriter() throws Exception { 104 return new XMLWriter(System.out, format); 105 } 106 107 } 108 109 147 | Popular Tags |