KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > jcorporate > expresso > ext > report > XMLPrinter


1 /* ====================================================================
2  * The Jcorporate Apache Style Software License, Version 1.2 05-07-2002
3  *
4  * Copyright (c) 1995-2002 Jcorporate Ltd. All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  *
10  * 1. Redistributions of source code must retain the above copyright
11  * notice, this list of conditions and the following disclaimer.
12  *
13  * 2. Redistributions in binary form must reproduce the above copyright
14  * notice, this list of conditions and the following disclaimer in
15  * the documentation and/or other materials provided with the
16  * distribution.
17  *
18  * 3. The end-user documentation included with the redistribution,
19  * if any, must include the following acknowledgment:
20  * "This product includes software developed by Jcorporate Ltd.
21  * (http://www.jcorporate.com/)."
22  * Alternately, this acknowledgment may appear in the software itself,
23  * if and wherever such third-party acknowledgments normally appear.
24  *
25  * 4. "Jcorporate" and product names such as "Expresso" must
26  * not be used to endorse or promote products derived from this
27  * software without prior written permission. For written permission,
28  * please contact info@jcorporate.com.
29  *
30  * 5. Products derived from this software may not be called "Expresso",
31  * or other Jcorporate product names; nor may "Expresso" or other
32  * Jcorporate product names appear in their name, without prior
33  * written permission of Jcorporate Ltd.
34  *
35  * 6. No product derived from this software may compete in the same
36  * market space, i.e. framework, without prior written permission
37  * of Jcorporate Ltd. For written permission, please contact
38  * partners@jcorporate.com.
39  *
40  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
41  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
42  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
43  * DISCLAIMED. IN NO EVENT SHALL JCORPORATE LTD OR ITS CONTRIBUTORS
44  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
45  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
46  * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
47  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
48  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
49  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
50  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
51  * SUCH DAMAGE.
52  * ====================================================================
53  *
54  * This software consists of voluntary contributions made by many
55  * individuals on behalf of the Jcorporate Ltd. Contributions back
56  * to the project(s) are encouraged when you make modifications.
57  * Please send them to support@jcorporate.com. For more information
58  * on Jcorporate Ltd. and its products, please see
59  * <http://www.jcorporate.com/>.
60  *
61  * Portions of this software are based upon other open source
62  * products and are subject to their respective licenses.
63  */

64
65
66 package com.jcorporate.expresso.ext.report;
67
68
69 import com.jcorporate.expresso.core.misc.StringUtil;
70 import com.jcorporate.expresso.kernel.exception.ExpressoRuntimeException;
71 import com.jcorporate.expresso.kernel.management.DOMWriter;
72 import com.jcorporate.expresso.kernel.util.FastStringBuffer;
73 import org.apache.log4j.Logger;
74 import org.w3c.dom.Attr JavaDoc;
75 import org.w3c.dom.Document JavaDoc;
76 import org.w3c.dom.DocumentType JavaDoc;
77 import org.w3c.dom.Entity JavaDoc;
78 import org.w3c.dom.NamedNodeMap JavaDoc;
79 import org.w3c.dom.Node JavaDoc;
80 import org.w3c.dom.NodeList JavaDoc;
81 import org.xml.sax.ErrorHandler JavaDoc;
82 import org.xml.sax.InputSource JavaDoc;
83 import org.xml.sax.SAXException JavaDoc;
84 import org.xml.sax.SAXParseException JavaDoc;
85
86 import javax.xml.parsers.DocumentBuilder JavaDoc;
87 import javax.xml.parsers.DocumentBuilderFactory JavaDoc;
88 import java.io.BufferedWriter JavaDoc;
89 import java.io.File JavaDoc;
90 import java.io.FileWriter JavaDoc;
91 import java.io.IOException JavaDoc;
92 import java.io.OutputStream JavaDoc;
93 import java.io.OutputStreamWriter JavaDoc;
94 import java.io.StringWriter JavaDoc;
95 import java.io.Writer JavaDoc;
96 import java.util.StringTokenizer JavaDoc;
97
98
99 /**
100  * XMLPrinter is a simple (DOM) parser that outputs XML to a Writer stream.
101  *
102  * @author David Lloyd
103  */

104
105 public class XMLPrinter implements ErrorHandler JavaDoc, DOMWriter {
106
107     protected static Logger log;
108     public static final OutputStreamWriter JavaDoc SYSTEM_OUT = new OutputStreamWriter JavaDoc(System.out);
109     public static final String JavaDoc DEFAULT_INDENT = " "; //3-spaces
110

111     /**
112      * The writer that will contain the XML written.
113      */

114     protected Writer _out = null;
115
116     /**
117      * The indention prefix string.
118      */

119     protected String JavaDoc _indent = DEFAULT_INDENT;
120
121     /**
122      * The character to use for indenting.
123      */

124     protected char _indentChar = ' ';
125
126     /**
127      * The virtual area occupied by an indention.
128      */

129     protected int _indentLength = 0;
130
131     /**
132      * The current indention level.
133      */

134     protected int _column = 0;
135
136     /**
137      * Set to keep the &lt;?xml ... header from printing.
138      */

139     protected boolean _omitXmlDecl = false;
140
141     /**
142      * The character sequence for a newline.
143      */

144     protected String JavaDoc _newline = System.getProperty("line.separator");
145
146     public XMLPrinter() {
147         log = Logger.getLogger(XMLPrinter.class);
148         setWriter(SYSTEM_OUT);
149     }
150
151     /**
152      * Override to actually save a DOM document to the output stream via whatever
153      * method you desire
154      *
155      * @param os The output stream to save to
156      * @param document the DOM document representing the config.
157      * @throws ExpressoRuntimeException if there's an error saving the file.
158      */

159     public void saveDocument(OutputStream JavaDoc os, Document JavaDoc document)
160             throws ExpressoRuntimeException {
161         try {
162             setWriter(new OutputStreamWriter JavaDoc(os));
163             outputDocument(document.getDocumentElement());
164             getWriter().flush();
165         } catch (IOException JavaDoc ioe) {
166             throw new ExpressoRuntimeException(ioe);
167         }
168     }
169
170     /**
171      * Retrieve a class that must exist in the classpath for this to work.
172      * Used as a sanity check to make sure the appropriate jars are installed.
173      *
174      * @return java.lang.String a name of a class
175      */

176     public String JavaDoc getRequiredClass() {
177         return "org.w3c.dom.Document";
178     }
179
180     /**
181      * Output the document whose root element is the specified node.
182      */

183     public void outputDocument(Node JavaDoc node) throws IOException JavaDoc {
184         if (!_omitXmlDecl && node.getNodeType() == Node.ELEMENT_NODE) {
185             println("<?xml version='1.0' ?>");
186             println("");
187         }
188         printTree(node);
189     }
190
191     /**
192      * Set the output writer.
193      */

194     public void setWriter(Writer out) {
195         this._out = out;
196     }
197
198     /**
199      * Get the output writer.
200      */

201     public Writer getWriter() {
202         return this._out;
203     }
204
205     /**
206      * Set the indentation size to the number of characters specified using the
207      * current indent character.
208      */

209     public void setIndentSize(int indentSize) {
210         _indent = "";
211         _indentLength = 0;
212
213         int inc;
214         if (_indentChar == '\t') {
215             inc = 4;
216         } else {
217             inc = 1;
218         }
219
220         for (int i = 0; i < indentSize; i++) {
221             _indent += _indentChar;
222             _indentLength += inc;
223         }
224     }
225
226     /**
227      * Set the indent semantics.
228      *
229      * @param indentChar The character to use for indentions.
230      * @param size The number of characters to use for each indention level.
231      */

232     public void setIndent(char indentChar, int size) {
233         _indentChar = indentChar;
234         setIndentSize(size);
235     }
236
237     /**
238      * Set whether the xml declaration should be output at the start of a document.
239      */

240     public void setOmitXmlDecl(boolean b) {
241         _omitXmlDecl = b;
242     }
243
244     /**
245      * Closes the output writer ignoring any errors recieved. You are encouraged
246      * to close the writer yourself to recieve any errors encountered.
247      */

248     public void closeWriter() {
249         try {
250             this._out.close();
251         } catch (IOException JavaDoc ioe) {
252             //oe.printStackTrace();
253
}
254     }
255
256     /**
257      * Creates an output writer that will create the file specified and any
258      * parent directories needed to do so.
259      */

260     public void setFile(File JavaDoc file) throws IOException JavaDoc {
261         File JavaDoc parentDirectory = file.getParentFile();
262
263         if (parentDirectory != null && !parentDirectory.exists()) {
264             parentDirectory.mkdirs();
265         }
266
267         setWriter(new BufferedWriter JavaDoc(new FileWriter JavaDoc(file)));
268     }
269
270     /**
271      * Creates an output writer that will create the file specified and any
272      * parent directories needed to do so.
273      */

274     public void setFile(String JavaDoc filename) throws IOException JavaDoc {
275         setFile(new File JavaDoc(filename));
276     }
277
278     /**
279      * Return the given node as a string. If any error occurs
280      * in processing (likely an io exception from outputDocument()),
281      * null will be returned.
282      */

283     public static String JavaDoc nodeToString(Node JavaDoc node) {
284         try {
285             XMLPrinter printer = new XMLPrinter();
286
287             StringWriter JavaDoc writer = new StringWriter JavaDoc();
288
289             printer.setWriter(writer);
290
291             printer.outputDocument(node);
292
293             return writer.getBuffer().toString();
294
295         } catch (IOException JavaDoc e) {
296             return null;
297         }
298     }
299
300     /**
301      * Parse an string and convert it to xml style
302      *
303      * @param html The string to be parsed
304      * @return The resulting xml string
305      */

306     public static String JavaDoc toXML(String JavaDoc html) {
307         return toXML(html, true);
308     }
309
310     /**
311      * Parse an string and convert it to xml style
312      *
313      * @param html The string to be parsed
314      * @param escapeAll If false, the semicolon, apostrophe, and quote are left alone (useful for text nodes).
315      * @return The resulting xml string
316      */

317     public static String JavaDoc toXML(String JavaDoc html, boolean escapeAll) {
318         if (html == null) {
319             return "";
320         }
321
322         FastStringBuffer parsedString = new FastStringBuffer(html.length());
323
324         String JavaDoc delim;
325         delim = "&;><'\"";
326
327         StringTokenizer JavaDoc st;
328         st = new StringTokenizer JavaDoc(html, delim, true);
329
330         String JavaDoc token;
331
332         while (st.hasMoreTokens()) {
333             token = st.nextToken();
334
335             // recognizes and replaces html tokens with xml style tokens
336
if (token.equals("&")) {
337                 token = "&amp;";
338             } else if (token.equals(">")) {
339                 token = "&gt;";
340             } else if (token.equals("<")) {
341                 token = "&lt;";
342             } else if (escapeAll) {
343                 if (token.equals(";")) {
344                     token = "&semi;";
345                 } else if (token.equals("'")) {
346                     token = "&apos;";
347                 } else if (token.equals("\"")) {
348                     token = "&quot;";
349                 }
350             }
351             parsedString.append(token);
352         }
353         return parsedString.toString();
354     }
355
356     /**
357      * Prints the string to the output at an indentation.
358      *
359      * @param string The string to print.
360      * @param indent The indentation to prefix the string.
361      */

362     public void print(String JavaDoc string, String JavaDoc indent) throws IOException JavaDoc {
363         print(indent);
364         if (string != null) {
365             print(string.trim());
366         }
367     }
368
369     /**
370      * Prints the string to the output at an indentation following it with a newline.
371      *
372      * @param string The string to print.
373      * @param indent The indentation to prefix the string.
374      */

375     public void println(String JavaDoc string, String JavaDoc indent) throws IOException JavaDoc {
376         print(indent);
377         if (string != null) {
378             println(string.trim());
379         } else {
380             println("");
381         }
382     }
383
384     /**
385      * Prints the string to the output.
386      *
387      * @param string The string to print.
388      */

389     public void print(String JavaDoc string) throws IOException JavaDoc {
390         this._out.write(string);
391     }
392
393     /**
394      * Prints the string to the output following it with a newline.
395      *
396      * @param string The string to print.
397      */

398     public void println(String JavaDoc string) throws IOException JavaDoc {
399         print(string);
400         print(_newline);
401     }
402
403     /**
404      * Get the normal indentation for a level.
405      *
406      * @param col The level of indentation.
407      */

408     protected String JavaDoc getIndent(int col) {
409         String JavaDoc indent = "";
410
411         // go by twos to improve performance
412
String JavaDoc indent2x = this._indent + this._indent;
413         for (int i = (col & 0x7ffffe); i > 0; i -= 2) {
414             indent += indent2x;
415         }
416         if ((col & 0x01) == 1) {
417             indent += this._indent;
418         }
419
420         return indent;
421     }
422
423     /**
424      * Output the node (and children) at the specified indentation level.
425      */

426     protected void printTree(Node JavaDoc node, int col) throws IOException JavaDoc {
427         int old = _column;
428         _column = col;
429         printTree(node);
430         _column = old;
431     }
432
433     /**
434      * Output the node (and children) at the current indentation level.
435      */

436     protected void printTree(Node JavaDoc node) throws IOException JavaDoc {
437         int nodeType = -1;
438
439         if (node != null) {
440             nodeType = node.getNodeType();
441             switch (nodeType) {
442                 case Node.DOCUMENT_NODE:
443                     {
444                         NodeList JavaDoc nodes = node.getChildNodes();
445
446                         if (nodes != null) {
447                             for (int i = 0; i < nodes.getLength(); i++) {
448                                 printTree(nodes.item(i));
449                             }
450                         }
451
452                         break;
453                     }
454
455                 case Node.ELEMENT_NODE:
456                     {
457                         String JavaDoc name = node.getNodeName();
458                         this.print("<" + name, getIndent(this._column));
459
460                         NamedNodeMap JavaDoc attributes = node.getAttributes();
461                         for (int i = 0; i < attributes.getLength(); i++) {
462                             Attr JavaDoc current = (Attr JavaDoc) attributes.item(i);
463
464                             /*
465                                With some DOM implementations the default value shows up in addition to a
466                                specified value so you get duplicate attributes. We will only write
467                                specified attributes.
468                             */

469                             if (current.getSpecified() == true) {
470                                 this.print(" " + current.getNodeName() + "='" + current.getNodeValue() + "'");
471                             }
472
473
474                         }//for attrs
475

476                         if (!node.hasChildNodes()) {
477                             // Close opening tag, because no children
478
this.println(" />");
479                         } else {
480                             // Close opening tag normally to account for children
481
this.print(">");
482
483                             NodeList JavaDoc children = node.getChildNodes();
484
485                             // If a child is a text node, we don't want to print carriage returns that get picked
486
// up as string text
487
boolean hasChildElements = false;
488                             if (children != null) {
489                                 int len = children.getLength();
490                                 for (int i = 0; i < len; i++) {
491                                     if (children.item(i).getNodeType() != Node.TEXT_NODE) {
492                                         hasChildElements = true;
493                                         break;
494                                     }
495                                 }
496                             }
497
498                             // If non-text node as child, we can print enter
499
if (hasChildElements) {
500                                 this.println("");
501                             }
502
503                             this._column++;
504
505                             for (int i = 0; i < children.getLength(); i++) {
506                                 printTree(children.item(i));
507                             }
508                             this._column--;
509
510                             // Write closing tag. Once again for text nodes treat differently
511
if (hasChildElements) {
512                                 this.println("</" + name + ">", getIndent(this._column));
513                             } else {
514                                 this.println("</" + name + ">");
515                             }
516                         }
517
518                         break;
519                     }
520
521                 case Node.TEXT_NODE:
522                     {
523                         String JavaDoc nodeValue = node.getNodeValue().trim();
524                         if (!nodeValue.equals("")) {
525                             // Normalize string
526
this.print(toXML(nodeValue));
527                         }
528                         break;
529                     }
530
531                 case Node.CDATA_SECTION_NODE:
532                     {
533                         this.print("<![CDATA[", getIndent(this._column));
534
535                         this.print(convertNewline(node.getNodeValue()));
536                         this.println("]]>");
537                         break;
538                     }
539
540                 case Node.PROCESSING_INSTRUCTION_NODE:
541                     {
542                         if (node.getNodeName() != null) {
543                             if (!_omitXmlDecl && (false == node.getNodeName().startsWith("xml")) && (false == node.getNodeName().startsWith(
544                                     "xsl"))) {
545                                 // This should NOT be correct, but Xerces seems to have a bug - bt 4/2001
546
this.println("<?xml " + node.getNodeName() + "=\"" + node.getNodeValue() + "\"?>");
547                             } else {
548                                 // This should be the normal behaviour
549
if (!_omitXmlDecl || !"xml".equals(node.getNodeName())) {
550                                     this.println("<?" + node.getNodeName() + " " + node.getNodeValue() + " ?>");
551                                 }
552                             }
553                         }
554                         break;
555                     }
556
557                 case Node.ENTITY_REFERENCE_NODE:
558                     {
559                         this.println("&" + node.getNodeName() + ";");
560                         break;
561                     }
562
563                 case Node.DOCUMENT_TYPE_NODE:
564                     {
565                         DocumentType JavaDoc docType = (DocumentType JavaDoc) node;
566
567                         // Note: below is since DOM 2 - bt
568
// Print either SYSTEM '...' or PUBLIC '...' '...'
569
this.print("<!DOCTYPE " + docType.getName());
570                         if (docType.getPublicId() != null) {
571                             this.print(" PUBLIC ");
572                         } else if (docType.getSystemId() != null) {
573                             this.print(" SYSTEM ");
574                         }
575                         // There may not even be a public or system, that's OK
576

577                         if (docType.getPublicId() != null) {
578
579                             this.print("\"" + docType.getPublicId() + "\" ");
580                         }
581                         if (docType.getSystemId() != null) {
582                             this.print("\"" + docType.getSystemId() + "\" ");
583                         }
584
585                         // Also print any entities that were defined, such as [<!ENTITY lt "<" >]
586
NamedNodeMap JavaDoc nodes = docType.getEntities();
587
588                         for (int i = 0; i < nodes.getLength(); i++) {
589                             this.println("");
590                             Entity JavaDoc entity = (Entity JavaDoc) nodes.item(i);
591                             this.print(" [<!ENTITY " + entity.getNodeName() + " ");
592
593                             // Entity should have a child node that is its value
594
NodeList JavaDoc children = entity.getChildNodes();
595                             if (children != null && children.getLength() > 0) {
596                                 this.print("\"" + XMLPrinter.nodeToString(children.item(0)) + "\">]");
597                             } else {
598                                 this.print("\"" + entity.getNodeValue() + "\">]");
599                             }
600                         }
601
602                         // End the doctype entry
603
this.println("");
604                         this.println(">");
605
606                         break;
607                     }
608             }
609
610         }
611
612         this._out.flush();
613     }
614
615     /**
616      * Convert newlines to what we want.
617      */

618     protected String JavaDoc convertNewline(String JavaDoc text) {
619         //convert MSDOS crlf to a lf
620
text = StringUtil.replace(text, "\r\n", "\n");
621         //convert lf to the set newline seq
622
text = StringUtil.replace(text, "\n", _newline);
623
624         return text;
625     }
626
627
628     public static int run(String JavaDoc[] args, XMLPrinter printer) {
629         String JavaDoc filename = null;
630         String JavaDoc outputname = null;
631
632         File JavaDoc tempOut = null;
633
634         try {
635             if (System.getProperty("log4j.configuration") == null ||
636                     System.getProperty("log4j.configuration").trim().length() == 0) {
637                 System.err.println("ERROR: Logging will not work - 'log4j.configuration' must be defined.");
638             } else {
639                 org.apache.log4j.PropertyConfigurator.configureAndWatch(System.getProperty("log4j.configuration"));
640             }
641
642             for (int i = 0; i < args.length; i++) {
643                 if (args[i].toLowerCase().startsWith("-omitxml=")) {
644                     printer.setOmitXmlDecl(StringUtil.toBoolean(args[i].substring(9)));
645                 } else if (args[i].toLowerCase().equals("-out") && args.length > i + 1) {
646                     outputname = args[++i];
647                 } else if (args[i].toLowerCase().equals("-in") && args.length > i + 1) {
648                     filename = args[++i];
649                 }
650             }
651
652             if (filename == null) {
653                 log.error("No input file specified.");
654                 return (2);
655             }
656
657             File JavaDoc inputfile = new File JavaDoc(filename);
658
659             Document JavaDoc doc = null;
660
661             java.io.Reader JavaDoc inputReader = null;
662             try {
663                 inputReader = new DocBookFilterReader(new java.io.FileReader JavaDoc(inputfile));
664                 InputSource JavaDoc inputSource = new InputSource JavaDoc(inputReader);
665                 DocumentBuilderFactory JavaDoc dbf = DocumentBuilderFactory.newInstance();
666                 dbf.setNamespaceAware(true);
667                 dbf.setValidating(false);
668
669                 DocumentBuilder JavaDoc db = dbf.newDocumentBuilder();
670                 db.setErrorHandler(printer);
671                 
672                 // Set the path so that relative SYSTEM entities can be found
673
if (inputfile.getParentFile() != null) {
674                     inputSource.setSystemId(inputfile.getParentFile().toURL().toString());
675                 }
676
677                 doc = db.parse(inputSource);
678             } catch (Exception JavaDoc e) {
679                 log.error("Error Parsing XML Document.", e);
680                 return (1);
681             } finally {
682                 try {
683                     inputReader.close();
684                 } catch (Throwable JavaDoc t) {
685                 }
686             }
687
688             // The parsing has now succeeded.
689

690             File JavaDoc outputfile = null;
691             if (outputname != null) {
692                 outputfile = new File JavaDoc(outputname);
693             } else {
694                 outputfile = inputfile;
695             }
696
697             tempOut = File.createTempFile(outputfile.getName() + "-", ".xmlpp", outputfile.getParentFile());
698
699             try {
700                 Writer outfilewriter = new java.io.FileWriter JavaDoc(tempOut);
701                 printer.setWriter(new DocBookFilterWriter(outfilewriter));
702
703                 // The parsing has now succeeded.
704
printer.outputDocument(doc.getDocumentElement());
705             } catch (Exception JavaDoc e) {
706                 log.error("Error formatting XML Document.", e);
707                 return (1);
708             } finally {
709                 try {
710                     printer.getWriter().close();
711                 } catch (Throwable JavaDoc t) {
712                 }
713             }
714
715             // try to rename the input file to keep from trashing the input
716
if (outputname == null) {
717                 File JavaDoc bak = new File JavaDoc(inputfile.getParentFile(), inputfile.getName() + ".bak");
718                 if (!inputfile.renameTo(bak) || inputfile.exists()) {
719                     bak = File.createTempFile(inputfile.getName() + "-", ".xmlpp", inputfile.getParentFile());
720
721                     log.warn("Can't rename input to *.bak - trying copy to " + bak.getName());
722
723                     try {
724                         copyFile(inputfile, bak);
725                         log.info("input file backed up");
726                     } catch (IOException JavaDoc ioe) {
727                         tempOut = null;
728                         log.error("Unable to backup the input file. The output was left in "
729                                 + tempOut.getAbsolutePath(), ioe);
730                         return 1;
731                     }
732                 }
733             }
734
735             // write the output file
736
try {
737                 copyFile(tempOut, outputfile);
738             } catch (IOException JavaDoc ioe) {
739                 log.error("Unable to overwrite output file " + outputfile.getAbsolutePath());
740                 return 1;
741             }
742
743         } catch (Exception JavaDoc e) {
744             log.error("Error prettying XML Document.", e);
745             return (1);
746         } finally {
747             if (tempOut != null) {
748                 try {
749                     if (tempOut.delete()) {
750                         return 0;
751                     }
752                 } catch (Throwable JavaDoc t) {
753                 }
754                 try {
755                     log.warn("A temporary file was left on disk - " + tempOut.getAbsolutePath());
756                 } catch (Throwable JavaDoc t) {
757                     log.warn("A temporary file was left on disk - ");
758                 }
759             }
760         }
761         return 0;
762     }
763
764     public static int run(String JavaDoc[] args) {
765         org.apache.log4j.BasicConfigurator.configure();
766
767         XMLPrinter printer = new XMLPrinter();
768
769         return run(args, printer);
770     }
771
772     public static void main(String JavaDoc[] args) {
773         System.exit(run(args));
774     }
775
776     protected static void copyFile(File JavaDoc in, File JavaDoc out) throws IOException JavaDoc {
777         java.io.FileWriter JavaDoc filewriter = null;
778         java.io.FileReader JavaDoc filereader = null;
779         try {
780             filewriter = new java.io.FileWriter JavaDoc(out);
781             filereader = new java.io.FileReader JavaDoc(in);
782
783             char[] buf = new char[4096];
784             int nread = filereader.read(buf, 0, 4096);
785             while (nread >= 0) {
786                 filewriter.write(buf, 0, nread);
787                 nread = filereader.read(buf, 0, 4096);
788             }
789             buf = null;
790         } finally {
791             try {
792                 filereader.close();
793             } catch (Throwable JavaDoc t) {
794             }
795             try {
796                 filewriter.close();
797             } catch (Throwable JavaDoc t) {
798             }
799         }
800     }
801
802     //
803
// ErrorHandler methods
804
//
805
/**
806      * Issue a warning on parsing errors
807      *
808      * @param ex A Sax Parse Exception event
809      */

810     public void warning(SAXParseException JavaDoc ex) {
811
812         log.warn(getLocationString(ex) + ": " + ex.getMessage());
813     }
814
815     /**
816      * Issue an error
817      *
818      * @param ex A Sax Parse Exception event
819      */

820     public void error(SAXParseException JavaDoc ex) {
821         log.error(getLocationString(ex) + ": " + ex.getMessage());
822     }
823
824     /**
825      * Fatal error. Used Internally for parsing only
826      *
827      * @param ex A Sax Parse Exception event
828      * @throws SAXException after logging the Parsing Exception
829      */

830     public void fatalError(SAXParseException JavaDoc ex)
831             throws SAXException JavaDoc {
832         log.error(getLocationString(ex) + ": " + ex.getMessage());
833         throw ex;
834     }
835
836     /**
837      * Returns a string of the location. Used Internally For Parsing Only
838      *
839      * @param ex A Sax Parse Exception event
840      * @return java.lang.String
841      */

842     private String JavaDoc getLocationString(SAXParseException JavaDoc ex) {
843         FastStringBuffer str = new FastStringBuffer(128);
844         String JavaDoc systemId = ex.getSystemId();
845
846         if (systemId != null) {
847             int index = systemId.lastIndexOf('/');
848
849             if (index != -1) {
850                 systemId = systemId.substring(index + 1);
851             }
852
853             str.append(systemId);
854         }
855
856         str.append(':');
857         str.append(ex.getLineNumber());
858         str.append(':');
859         str.append(ex.getColumnNumber());
860
861         return str.toString();
862     } // getLocationString(SAXParseException):String
863
}
864
Popular Tags