KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > sax > DocumentTracer


1 /*
2  * Copyright 2000-2002,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
17 package sax;
18
19 import java.io.OutputStream JavaDoc;
20 import java.io.OutputStreamWriter JavaDoc;
21 import java.io.PrintWriter JavaDoc;
22 import java.io.UnsupportedEncodingException JavaDoc;
23 import java.io.Writer JavaDoc;
24
25 import org.xml.sax.AttributeList JavaDoc;
26 import org.xml.sax.Attributes JavaDoc;
27 import org.xml.sax.ContentHandler JavaDoc;
28 import org.xml.sax.DocumentHandler JavaDoc;
29 import org.xml.sax.DTDHandler JavaDoc;
30 import org.xml.sax.ErrorHandler JavaDoc;
31 import org.xml.sax.Locator JavaDoc;
32 import org.xml.sax.Parser JavaDoc;
33 import org.xml.sax.SAXException JavaDoc;
34 import org.xml.sax.SAXNotRecognizedException JavaDoc;
35 import org.xml.sax.SAXNotSupportedException JavaDoc;
36 import org.xml.sax.SAXParseException JavaDoc;
37 import org.xml.sax.XMLReader JavaDoc;
38 import org.xml.sax.helpers.DefaultHandler JavaDoc;
39 import org.xml.sax.helpers.ParserAdapter JavaDoc;
40 import org.xml.sax.helpers.ParserFactory JavaDoc;
41 import org.xml.sax.helpers.XMLReaderFactory JavaDoc;
42 import org.xml.sax.ext.DeclHandler JavaDoc;
43 import org.xml.sax.ext.LexicalHandler JavaDoc;
44
45 /**
46  * Provides a complete trace of SAX2 events for files parsed. This is
47  * useful for making sure that a SAX parser implementation faithfully
48  * communicates all information in the document to the SAX handlers.
49  *
50  * @author Andy Clark, IBM
51  * @author Arnaud Le Hors, IBM
52  *
53  * @version $Id: DocumentTracer.java,v 1.13 2005/05/09 00:29:47 mrglavas Exp $
54  */

55 public class DocumentTracer
56     extends DefaultHandler JavaDoc
57     implements ContentHandler JavaDoc, DTDHandler JavaDoc, ErrorHandler JavaDoc, // SAX2
58
DeclHandler JavaDoc, LexicalHandler JavaDoc, // SAX2 extensions
59
DocumentHandler JavaDoc // deprecated in SAX2
60
{
61
62     //
63
// Constants
64
//
65

66     // feature ids
67

68     /** Namespaces feature id (http://xml.org/sax/features/namespaces). */
69     protected static final String JavaDoc NAMESPACES_FEATURE_ID = "http://xml.org/sax/features/namespaces";
70     
71     /** Namespace prefixes feature id (http://xml.org/sax/features/namespace-prefixes). */
72     protected static final String JavaDoc NAMESPACE_PREFIXES_FEATURE_ID = "http://xml.org/sax/features/namespace-prefixes";
73
74     /** Validation feature id (http://xml.org/sax/features/validation). */
75     protected static final String JavaDoc VALIDATION_FEATURE_ID = "http://xml.org/sax/features/validation";
76
77     /** Schema validation feature id (http://apache.org/xml/features/validation/schema). */
78     protected static final String JavaDoc SCHEMA_VALIDATION_FEATURE_ID = "http://apache.org/xml/features/validation/schema";
79
80     /** Schema full checking feature id (http://apache.org/xml/features/validation/schema-full-checking). */
81     protected static final String JavaDoc SCHEMA_FULL_CHECKING_FEATURE_ID = "http://apache.org/xml/features/validation/schema-full-checking";
82     
83     /** Validate schema annotations feature id (http://apache.org/xml/features/validate-annotations) */
84     protected static final String JavaDoc VALIDATE_ANNOTATIONS_ID = "http://apache.org/xml/features/validate-annotations";
85     
86     /** Dynamic validation feature id (http://apache.org/xml/features/validation/dynamic). */
87     protected static final String JavaDoc DYNAMIC_VALIDATION_FEATURE_ID = "http://apache.org/xml/features/validation/dynamic";
88     
89     /** Load external DTD feature id (http://apache.org/xml/features/nonvalidating/load-external-dtd). */
90     protected static final String JavaDoc LOAD_EXTERNAL_DTD_FEATURE_ID = "http://apache.org/xml/features/nonvalidating/load-external-dtd";
91     
92     /** XInclude feature id (http://apache.org/xml/features/xinclude). */
93     protected static final String JavaDoc XINCLUDE_FEATURE_ID = "http://apache.org/xml/features/xinclude";
94     
95     /** XInclude fixup base URIs feature id (http://apache.org/xml/features/xinclude/fixup-base-uris). */
96     protected static final String JavaDoc XINCLUDE_FIXUP_BASE_URIS_FEATURE_ID = "http://apache.org/xml/features/xinclude/fixup-base-uris";
97     
98     /** XInclude fixup language feature id (http://apache.org/xml/features/xinclude/fixup-language). */
99     protected static final String JavaDoc XINCLUDE_FIXUP_LANGUAGE_FEATURE_ID = "http://apache.org/xml/features/xinclude/fixup-language";
100
101     // property ids
102

103     /** Lexical handler property id (http://xml.org/sax/properties/lexical-handler). */
104     protected static final String JavaDoc LEXICAL_HANDLER_PROPERTY_ID = "http://xml.org/sax/properties/lexical-handler";
105
106     // default settings
107

108     /** Default parser name. */
109     protected static final String JavaDoc DEFAULT_PARSER_NAME = "org.apache.xerces.parsers.SAXParser";
110
111     /** Default namespaces support (true). */
112     protected static final boolean DEFAULT_NAMESPACES = true;
113     
114     /** Default namespace prefixes (false). */
115     protected static final boolean DEFAULT_NAMESPACE_PREFIXES = false;
116
117     /** Default validation support (false). */
118     protected static final boolean DEFAULT_VALIDATION = false;
119     
120     /** Default load external DTD (true). */
121     protected static final boolean DEFAULT_LOAD_EXTERNAL_DTD = true;
122
123     /** Default Schema validation support (false). */
124     protected static final boolean DEFAULT_SCHEMA_VALIDATION = false;
125
126     /** Default Schema full checking support (false). */
127     protected static final boolean DEFAULT_SCHEMA_FULL_CHECKING = false;
128     
129     /** Default validate schema annotations (false). */
130     protected static final boolean DEFAULT_VALIDATE_ANNOTATIONS = false;
131     
132     /** Default dynamic validation support (false). */
133     protected static final boolean DEFAULT_DYNAMIC_VALIDATION = false;
134     
135     /** Default XInclude processing support (false). */
136     protected static final boolean DEFAULT_XINCLUDE = false;
137     
138     /** Default XInclude fixup base URIs support (true). */
139     protected static final boolean DEFAULT_XINCLUDE_FIXUP_BASE_URIS = true;
140     
141     /** Default XInclude fixup language support (true). */
142     protected static final boolean DEFAULT_XINCLUDE_FIXUP_LANGUAGE = true;
143
144     //
145
// Data
146
//
147

148     /** Print writer. */
149     protected PrintWriter JavaDoc fOut;
150
151     /** Indent level. */
152     protected int fIndent;
153
154     //
155
// Constructors
156
//
157

158     /** Default constructor. */
159     public DocumentTracer() {
160         setOutput(new PrintWriter JavaDoc(System.out));
161     } // <init>()
162

163     //
164
// Public methods
165
//
166

167     /** Sets the output stream for printing. */
168     public void setOutput(OutputStream JavaDoc stream, String JavaDoc encoding)
169         throws UnsupportedEncodingException JavaDoc {
170
171         if (encoding == null) {
172             encoding = "UTF8";
173         }
174
175         Writer writer = new OutputStreamWriter JavaDoc(stream, encoding);
176         fOut = new PrintWriter JavaDoc(writer);
177
178     } // setOutput(OutputStream,String)
179

180     /** Sets the output writer. */
181     public void setOutput(Writer writer) {
182
183         fOut = writer instanceof PrintWriter JavaDoc
184              ? (PrintWriter JavaDoc)writer : new PrintWriter JavaDoc(writer);
185
186     } // setOutput(Writer)
187

188     //
189
// ContentHandler and DocumentHandler methods
190
//
191

192     /** Set document locator. */
193     public void setDocumentLocator(Locator JavaDoc locator) {
194
195         printIndent();
196         fOut.print("setDocumentLocator(");
197         fOut.print("locator=");
198         fOut.print(locator);
199         fOut.println(')');
200         fOut.flush();
201
202     } // setDocumentLocator(Locator)
203

204     /** Start document. */
205     public void startDocument() throws SAXException JavaDoc {
206
207         fIndent = 0;
208         printIndent();
209         fOut.println("startDocument()");
210         fOut.flush();
211         fIndent++;
212
213     } // startDocument()
214

215     /** Processing instruction. */
216     public void processingInstruction(String JavaDoc target, String JavaDoc data)
217         throws SAXException JavaDoc {
218
219         printIndent();
220         fOut.print("processingInstruction(");
221         fOut.print("target=");
222         printQuotedString(target);
223         fOut.print(',');
224         fOut.print("data=");
225         printQuotedString(data);
226         fOut.println(')');
227         fOut.flush();
228
229     } // processingInstruction(String,String)
230

231     /** Characters. */
232     public void characters(char[] ch, int offset, int length)
233         throws SAXException JavaDoc {
234
235         printIndent();
236         fOut.print("characters(");
237         fOut.print("text=");
238         printQuotedString(ch, offset, length);
239         fOut.println(')');
240         fOut.flush();
241
242     } // characters(char[],int,int)
243

244     /** Ignorable whitespace. */
245     public void ignorableWhitespace(char[] ch, int offset, int length)
246         throws SAXException JavaDoc {
247
248         printIndent();
249         fOut.print("ignorableWhitespace(");
250         fOut.print("text=");
251         printQuotedString(ch, offset, length);
252         fOut.println(')');
253         fOut.flush();
254
255     } // ignorableWhitespace(char[],int,int)
256

257     /** End document. */
258     public void endDocument() throws SAXException JavaDoc {
259
260         fIndent--;
261         printIndent();
262         fOut.println("endDocument()");
263         fOut.flush();
264
265     } // endDocument()
266

267     //
268
// ContentHandler methods
269
//
270

271     /** Start prefix mapping. */
272     public void startPrefixMapping(String JavaDoc prefix, String JavaDoc uri)
273         throws SAXException JavaDoc {
274
275         printIndent();
276         fOut.print("startPrefixMapping(");
277         fOut.print("prefix=");
278         printQuotedString(prefix);
279         fOut.print(',');
280         fOut.print("uri=");
281         printQuotedString(uri);
282         fOut.println(')');
283         fOut.flush();
284
285     } // startPrefixMapping(String,String)
286

287     /** Start element. */
288     public void startElement(String JavaDoc uri, String JavaDoc localName, String JavaDoc qname,
289                              Attributes JavaDoc attributes) throws SAXException JavaDoc {
290
291         printIndent();
292         fOut.print("startElement(");
293         fOut.print("uri=");
294         printQuotedString(uri);
295         fOut.print(',');
296         fOut.print("localName=");
297         printQuotedString(localName);
298         fOut.print(',');
299         fOut.print("qname=");
300         printQuotedString(qname);
301         fOut.print(',');
302         fOut.print("attributes=");
303         if (attributes == null) {
304             fOut.println("null");
305         }
306         else {
307             fOut.print('{');
308             int length = attributes.getLength();
309             for (int i = 0; i < length; i++) {
310                 if (i > 0) {
311                     fOut.print(',');
312                 }
313                 String JavaDoc attrLocalName = attributes.getLocalName(i);
314                 String JavaDoc attrQName = attributes.getQName(i);
315                 String JavaDoc attrURI = attributes.getURI(i);
316                 String JavaDoc attrType = attributes.getType(i);
317                 String JavaDoc attrValue = attributes.getValue(i);
318                 fOut.print('{');
319                 fOut.print("uri=");
320                 printQuotedString(attrURI);
321                 fOut.print(',');
322                 fOut.print("localName=");
323                 printQuotedString(attrLocalName);
324                 fOut.print(',');
325                 fOut.print("qname=");
326                 printQuotedString(attrQName);
327                 fOut.print(',');
328                 fOut.print("type=");
329                 printQuotedString(attrType);
330                 fOut.print(',');
331                 fOut.print("value=");
332                 printQuotedString(attrValue);
333                 fOut.print('}');
334             }
335             fOut.print('}');
336         }
337         fOut.println(')');
338         fOut.flush();
339         fIndent++;
340
341     } // startElement(String,String,String,Attributes)
342

343     /** End element. */
344     public void endElement(String JavaDoc uri, String JavaDoc localName, String JavaDoc qname)
345         throws SAXException JavaDoc {
346
347         fIndent--;
348         printIndent();
349         fOut.print("endElement(");
350         fOut.print("uri=");
351         printQuotedString(uri);
352         fOut.print(',');
353         fOut.print("localName=");
354         printQuotedString(localName);
355         fOut.print(',');
356         fOut.print("qname=");
357         printQuotedString(qname);
358         fOut.println(')');
359         fOut.flush();
360
361     } // endElement(String,String,String)
362

363     /** End prefix mapping. */
364     public void endPrefixMapping(String JavaDoc prefix) throws SAXException JavaDoc {
365
366         printIndent();
367         fOut.print("endPrefixMapping(");
368         fOut.print("prefix=");
369         printQuotedString(prefix);
370         fOut.println(')');
371         fOut.flush();
372
373     } // endPrefixMapping(String)
374

375     /** Skipped entity. */
376     public void skippedEntity(String JavaDoc name) throws SAXException JavaDoc {
377
378         printIndent();
379         fOut.print("skippedEntity(");
380         fOut.print("name=");
381         printQuotedString(name);
382         fOut.println(')');
383         fOut.flush();
384
385     } // skippedEntity(String)
386

387     //
388
// DocumentHandler methods
389
//
390

391     /** Start element. */
392     public void startElement(String JavaDoc name, AttributeList JavaDoc attributes)
393         throws SAXException JavaDoc {
394
395         printIndent();
396         fOut.print("startElement(");
397         fOut.print("name=");
398         printQuotedString(name);
399         fOut.print(',');
400         fOut.print("attributes=");
401         if (attributes == null) {
402             fOut.println("null");
403         }
404         else {
405             fOut.print('{');
406             int length = attributes.getLength();
407             for (int i = 0; i < length; i++) {
408                 if (i > 0) {
409                     System.out.print(',');
410                 }
411                 String JavaDoc attrName = attributes.getName(i);
412                 String JavaDoc attrType = attributes.getType(i);
413                 String JavaDoc attrValue = attributes.getValue(i);
414                 fOut.print('{');
415                 fOut.print("name=");
416                 printQuotedString(attrName);
417                 fOut.print(',');
418                 fOut.print("type=");
419                 printQuotedString(attrType);
420                 fOut.print(',');
421                 fOut.print("value=");
422                 printQuotedString(attrValue);
423                 fOut.print('}');
424             }
425             fOut.print('}');
426         }
427         fOut.println(')');
428         fOut.flush();
429         fIndent++;
430
431     } // startElement(String,AttributeList)
432

433     /** End element. */
434     public void endElement(String JavaDoc name) throws SAXException JavaDoc {
435
436         fIndent--;
437         printIndent();
438         fOut.print("endElement(");
439         fOut.print("name=");
440         printQuotedString(name);
441         fOut.println(')');
442         fOut.flush();
443
444     } // endElement(String)
445

446     //
447
// DTDHandler methods
448
//
449

450     /** Notation declaration. */
451     public void notationDecl(String JavaDoc name, String JavaDoc publicId, String JavaDoc systemId)
452         throws SAXException JavaDoc {
453
454         printIndent();
455         fOut.print("notationDecl(");
456         fOut.print("name=");
457         printQuotedString(name);
458         fOut.print(',');
459         fOut.print("publicId=");
460         printQuotedString(publicId);
461         fOut.print(',');
462         fOut.print("systemId=");
463         printQuotedString(systemId);
464         fOut.println(')');
465         fOut.flush();
466
467     } // notationDecl(String,String,String)
468

469     /** Unparsed entity declaration. */
470     public void unparsedEntityDecl(String JavaDoc name,
471                                    String JavaDoc publicId, String JavaDoc systemId,
472                                    String JavaDoc notationName) throws SAXException JavaDoc {
473         printIndent();
474         fOut.print("unparsedEntityDecl(");
475         fOut.print("name=");
476         printQuotedString(name);
477         fOut.print(',');
478         fOut.print("publicId=");
479         printQuotedString(publicId);
480         fOut.print(',');
481         fOut.print("systemId=");
482         printQuotedString(systemId);
483         fOut.print(',');
484         fOut.print("notationName=");
485         printQuotedString(notationName);
486         fOut.println(')');
487         fOut.flush();
488
489     } // unparsedEntityDecl(String,String,String,String)
490

491     //
492
// LexicalHandler methods
493
//
494

495     /** Start DTD. */
496     public void startDTD(String JavaDoc name, String JavaDoc publicId, String JavaDoc systemId)
497         throws SAXException JavaDoc {
498
499         printIndent();
500         fOut.print("startDTD(");
501         fOut.print("name=");
502         printQuotedString(name);
503         fOut.print(',');
504         fOut.print("publicId=");
505         printQuotedString(publicId);
506         fOut.print(',');
507         fOut.print("systemId=");
508         printQuotedString(systemId);
509         fOut.println(')');
510         fOut.flush();
511         fIndent++;
512
513     } // startDTD(String,String,String)
514

515     /** Start entity. */
516     public void startEntity(String JavaDoc name) throws SAXException JavaDoc {
517
518         printIndent();
519         fOut.print("startEntity(");
520         fOut.print("name=");
521         printQuotedString(name);
522         fOut.println(')');
523         fOut.flush();
524         fIndent++;
525
526     } // startEntity(String)
527

528     /** Start CDATA section. */
529     public void startCDATA() throws SAXException JavaDoc {
530
531         printIndent();
532         fOut.println("startCDATA()");
533         fOut.flush();
534         fIndent++;
535
536     } // startCDATA()
537

538     /** End CDATA section. */
539     public void endCDATA() throws SAXException JavaDoc {
540
541         fIndent--;
542         printIndent();
543         fOut.println("endCDATA()");
544         fOut.flush();
545
546     } // endCDATA()
547

548     /** Comment. */
549     public void comment(char[] ch, int offset, int length)
550         throws SAXException JavaDoc {
551
552         printIndent();
553         fOut.print("comment(");
554         fOut.print("text=");
555         printQuotedString(ch, offset, length);
556         fOut.println(')');
557         fOut.flush();
558
559     } // comment(char[],int,int)
560

561     /** End entity. */
562     public void endEntity(String JavaDoc name) throws SAXException JavaDoc {
563
564         fIndent--;
565         printIndent();
566         fOut.print("endEntity(");
567         fOut.print("name=");
568         printQuotedString(name);
569         fOut.println(')');
570
571     } // endEntity(String)
572

573     /** End DTD. */
574     public void endDTD() throws SAXException JavaDoc {
575
576         fIndent--;
577         printIndent();
578         fOut.println("endDTD()");
579         fOut.flush();
580
581     } // endDTD()
582

583     //
584
// DeclHandler methods
585
//
586

587     /** Element declaration. */
588     public void elementDecl(String JavaDoc name, String JavaDoc contentModel)
589         throws SAXException JavaDoc {
590
591         printIndent();
592         fOut.print("elementDecl(");
593         fOut.print("name=");
594         printQuotedString(name);
595         fOut.print(',');
596         fOut.print("contentModel=");
597         printQuotedString(contentModel);
598         fOut.println(')');
599         fOut.flush();
600
601     } // elementDecl(String,String)
602

603     /** Attribute declaration. */
604     public void attributeDecl(String JavaDoc elementName, String JavaDoc attributeName,
605                               String JavaDoc type, String JavaDoc valueDefault,
606                               String JavaDoc value) throws SAXException JavaDoc {
607
608         printIndent();
609         fOut.print("attributeDecl(");
610         fOut.print("elementName=");
611         printQuotedString(elementName);
612         fOut.print(',');
613         fOut.print("attributeName=");
614         printQuotedString(attributeName);
615         fOut.print(',');
616         fOut.print("type=");
617         printQuotedString(type);
618         fOut.print(',');
619         fOut.print("valueDefault=");
620         printQuotedString(valueDefault);
621         fOut.print(',');
622         fOut.print("value=");
623         printQuotedString(value);
624         fOut.println(')');
625         fOut.flush();
626
627     } // attributeDecl(String,String,String,String,String)
628

629     /** Internal entity declaration. */
630     public void internalEntityDecl(String JavaDoc name, String JavaDoc text)
631         throws SAXException JavaDoc {
632
633         printIndent();
634         fOut.print("internalEntityDecl(");
635         fOut.print("name=");
636         printQuotedString(name);
637         fOut.print(',');
638         fOut.print("text=");
639         printQuotedString(text);
640         fOut.println(')');
641         fOut.flush();
642
643     } // internalEntityDecl(String,String)
644

645     /** External entity declaration. */
646     public void externalEntityDecl(String JavaDoc name,
647                                    String JavaDoc publicId, String JavaDoc systemId)
648         throws SAXException JavaDoc {
649
650         printIndent();
651         fOut.print("externalEntityDecl(");
652         fOut.print("name=");
653         printQuotedString(name);
654         fOut.print(',');
655         fOut.print("publicId=");
656         printQuotedString(publicId);
657         fOut.print(',');
658         fOut.print("systemId=");
659         printQuotedString(systemId);
660         fOut.println(')');
661         fOut.flush();
662
663     } // externalEntityDecl(String,String,String)
664

665     //
666
// ErrorHandler methods
667
//
668

669     /** Warning. */
670     public void warning(SAXParseException JavaDoc ex) throws SAXException JavaDoc {
671         printError("Warning", ex);
672     } // warning(SAXParseException)
673

674     /** Error. */
675     public void error(SAXParseException JavaDoc ex) throws SAXException JavaDoc {
676         printError("Error", ex);
677     } // error(SAXParseException)
678

679     /** Fatal error. */
680     public void fatalError(SAXParseException JavaDoc ex) throws SAXException JavaDoc {
681         printError("Fatal Error", ex);
682         throw ex;
683     } // fatalError(SAXParseException)
684

685     //
686
// Protected methods
687
//
688

689     /** Print quoted string. */
690     protected void printQuotedString(String JavaDoc s) {
691
692         if (s == null) {
693             fOut.print("null");
694             return;
695         }
696
697         fOut.print('"');
698         int length = s.length();
699         for (int i = 0; i < length; i++) {
700             char c = s.charAt(i);
701             normalizeAndPrint(c);
702         }
703         fOut.print('"');
704
705     } // printQuotedString(String)
706

707     /** Print quoted string. */
708     protected void printQuotedString(char[] ch, int offset, int length) {
709
710         fOut.print('"');
711         for (int i = 0; i < length; i++) {
712             normalizeAndPrint(ch[offset + i]);
713         }
714         fOut.print('"');
715
716     } // printQuotedString(char[],int,int)
717

718     /** Normalize and print. */
719     protected void normalizeAndPrint(char c) {
720
721         switch (c) {
722             case '\n': {
723                 fOut.print("\\n");
724                 break;
725             }
726             case '\r': {
727                 fOut.print("\\r");
728                 break;
729             }
730             case '\t': {
731                 fOut.print("\\t");
732                 break;
733             }
734             case '\\': {
735                 fOut.print("\\\\");
736                 break;
737             }
738             case '"': {
739                 fOut.print("\\\"");
740                 break;
741             }
742             default: {
743                 fOut.print(c);
744             }
745         }
746
747     } // normalizeAndPrint(char)
748

749     /** Prints the error message. */
750     protected void printError(String JavaDoc type, SAXParseException JavaDoc ex) {
751
752         System.err.print("[");
753         System.err.print(type);
754         System.err.print("] ");
755         String JavaDoc systemId = ex.getSystemId();
756         if (systemId != null) {
757             int index = systemId.lastIndexOf('/');
758             if (index != -1)
759                 systemId = systemId.substring(index + 1);
760             System.err.print(systemId);
761         }
762         System.err.print(':');
763         System.err.print(ex.getLineNumber());
764         System.err.print(':');
765         System.err.print(ex.getColumnNumber());
766         System.err.print(": ");
767         System.err.print(ex.getMessage());
768         System.err.println();
769         System.err.flush();
770
771     } // printError(String,SAXParseException)
772

773     /** Prints the indent. */
774     protected void printIndent() {
775         for (int i = 0; i < fIndent; i++) {
776             fOut.print(' ');
777         }
778     }
779
780     //
781
// MAIN
782
//
783

784     /** Main. */
785     public static void main(String JavaDoc[] argv) throws Exception JavaDoc {
786
787         // is there anything to do?
788
if (argv.length == 0) {
789             printUsage();
790             System.exit(1);
791         }
792
793         // variables
794
DocumentTracer tracer = new DocumentTracer();
795         PrintWriter JavaDoc out = new PrintWriter JavaDoc(System.out);
796         XMLReader JavaDoc parser = null;
797         boolean namespaces = DEFAULT_NAMESPACES;
798         boolean namespacePrefixes = DEFAULT_NAMESPACE_PREFIXES;
799         boolean validation = DEFAULT_VALIDATION;
800         boolean externalDTD = DEFAULT_LOAD_EXTERNAL_DTD;
801         boolean schemaValidation = DEFAULT_SCHEMA_VALIDATION;
802         boolean schemaFullChecking = DEFAULT_SCHEMA_FULL_CHECKING;
803         boolean validateAnnotations = DEFAULT_VALIDATE_ANNOTATIONS;
804         boolean dynamicValidation = DEFAULT_DYNAMIC_VALIDATION;
805         boolean xincludeProcessing = DEFAULT_XINCLUDE;
806         boolean xincludeFixupBaseURIs = DEFAULT_XINCLUDE_FIXUP_BASE_URIS;
807         boolean xincludeFixupLanguage = DEFAULT_XINCLUDE_FIXUP_LANGUAGE;
808
809         // process arguments
810
for (int i = 0; i < argv.length; i++) {
811             String JavaDoc arg = argv[i];
812             if (arg.startsWith("-")) {
813                 String JavaDoc option = arg.substring(1);
814                 if (option.equals("p")) {
815                     // get parser name
816
if (++i == argv.length) {
817                         System.err.println("error: Missing argument to -p option.");
818                     }
819                     String JavaDoc parserName = argv[i];
820
821                     // create parser
822
try {
823                         parser = XMLReaderFactory.createXMLReader(parserName);
824                     }
825                     catch (Exception JavaDoc e) {
826                         try {
827                             Parser JavaDoc sax1Parser = ParserFactory.makeParser(parserName);
828                             parser = new ParserAdapter JavaDoc(sax1Parser);
829                             System.err.println("warning: Features and properties not supported on SAX1 parsers.");
830                         }
831                         catch (Exception JavaDoc ex) {
832                             parser = null;
833                             System.err.println("error: Unable to instantiate parser ("+parserName+")");
834                         }
835                     }
836                     continue;
837                 }
838                 if (option.equalsIgnoreCase("n")) {
839                     namespaces = option.equals("n");
840                     continue;
841                 }
842                 if (option.equalsIgnoreCase("np")) {
843                     namespacePrefixes = option.equals("np");
844                     continue;
845                 }
846                 if (option.equalsIgnoreCase("v")) {
847                     validation = option.equals("v");
848                     continue;
849                 }
850                 if (option.equalsIgnoreCase("xd")) {
851                     externalDTD = option.equals("xd");
852                     continue;
853                 }
854                 if (option.equalsIgnoreCase("s")) {
855                     schemaValidation = option.equals("s");
856                     continue;
857                 }
858                 if (option.equalsIgnoreCase("f")) {
859                     schemaFullChecking = option.equals("f");
860                     continue;
861                 }
862                 if (option.equalsIgnoreCase("va")) {
863                     validateAnnotations = option.equals("va");
864                     continue;
865                 }
866                 if (option.equalsIgnoreCase("dv")) {
867                     dynamicValidation = option.equals("dv");
868                     continue;
869                 }
870                 if (option.equalsIgnoreCase("xi")) {
871                     xincludeProcessing = option.equals("xi");
872                     continue;
873                 }
874                 if (option.equalsIgnoreCase("xb")) {
875                     xincludeFixupBaseURIs = option.equals("xb");
876                     continue;
877                 }
878                 if (option.equalsIgnoreCase("xl")) {
879                     xincludeFixupLanguage = option.equals("xl");
880                     continue;
881                 }
882                 if (option.equals("h")) {
883                     printUsage();
884                     continue;
885                 }
886             }
887
888             // use default parser?
889
if (parser == null) {
890
891                 // create parser
892
try {
893                     parser = XMLReaderFactory.createXMLReader(DEFAULT_PARSER_NAME);
894                 }
895                 catch (Exception JavaDoc e) {
896                     System.err.println("error: Unable to instantiate parser ("+DEFAULT_PARSER_NAME+")");
897                     continue;
898                 }
899             }
900
901             // set parser features
902
try {
903                 parser.setFeature(NAMESPACES_FEATURE_ID, namespaces);
904             }
905             catch (SAXException JavaDoc e) {
906                 System.err.println("warning: Parser does not support feature ("+NAMESPACES_FEATURE_ID+")");
907             }
908             try {
909                 parser.setFeature(NAMESPACE_PREFIXES_FEATURE_ID, namespacePrefixes);
910             }
911             catch (SAXException JavaDoc e) {
912                 System.err.println("warning: Parser does not support feature ("+NAMESPACE_PREFIXES_FEATURE_ID+")");
913             }
914             try {
915                 parser.setFeature(VALIDATION_FEATURE_ID, validation);
916             }
917             catch (SAXException JavaDoc e) {
918                 System.err.println("warning: Parser does not support feature ("+VALIDATION_FEATURE_ID+")");
919             }
920             try {
921                 parser.setFeature(LOAD_EXTERNAL_DTD_FEATURE_ID, externalDTD);
922             }
923             catch (SAXNotRecognizedException JavaDoc e) {
924                 System.err.println("warning: Parser does not recognize feature ("+LOAD_EXTERNAL_DTD_FEATURE_ID+")");
925             }
926             catch (SAXNotSupportedException JavaDoc e) {
927                 System.err.println("warning: Parser does not support feature ("+LOAD_EXTERNAL_DTD_FEATURE_ID+")");
928             }
929             try {
930                 parser.setFeature(SCHEMA_VALIDATION_FEATURE_ID, schemaValidation);
931             }
932             catch (SAXNotRecognizedException JavaDoc e) {
933                 System.err.println("warning: Parser does not recognize feature ("+SCHEMA_VALIDATION_FEATURE_ID+")");
934             }
935             catch (SAXNotSupportedException JavaDoc e) {
936                 System.err.println("warning: Parser does not support feature ("+SCHEMA_VALIDATION_FEATURE_ID+")");
937             }
938             try {
939                 parser.setFeature(SCHEMA_FULL_CHECKING_FEATURE_ID, schemaFullChecking);
940             }
941             catch (SAXNotRecognizedException JavaDoc e) {
942                 System.err.println("warning: Parser does not recognize feature ("+SCHEMA_FULL_CHECKING_FEATURE_ID+")");
943             }
944             catch (SAXNotSupportedException JavaDoc e) {
945                 System.err.println("warning: Parser does not support feature ("+SCHEMA_FULL_CHECKING_FEATURE_ID+")");
946             }
947             try {
948                 parser.setFeature(VALIDATE_ANNOTATIONS_ID, validateAnnotations);
949             }
950             catch (SAXNotRecognizedException JavaDoc e) {
951                 System.err.println("warning: Parser does not recognize feature ("+VALIDATE_ANNOTATIONS_ID+")");
952             }
953             catch (SAXNotSupportedException JavaDoc e) {
954                 System.err.println("warning: Parser does not support feature ("+VALIDATE_ANNOTATIONS_ID+")");
955             }
956             try {
957                 parser.setFeature(DYNAMIC_VALIDATION_FEATURE_ID, dynamicValidation);
958             }
959             catch (SAXNotRecognizedException JavaDoc e) {
960                 System.err.println("warning: Parser does not recognize feature ("+DYNAMIC_VALIDATION_FEATURE_ID+")");
961             }
962             catch (SAXNotSupportedException JavaDoc e) {
963                 System.err.println("warning: Parser does not support feature ("+DYNAMIC_VALIDATION_FEATURE_ID+")");
964             }
965             try {
966                 parser.setFeature(XINCLUDE_FEATURE_ID, xincludeProcessing);
967             }
968             catch (SAXNotRecognizedException JavaDoc e) {
969                 System.err.println("warning: Parser does not recognize feature ("+XINCLUDE_FEATURE_ID+")");
970             }
971             catch (SAXNotSupportedException JavaDoc e) {
972                 System.err.println("warning: Parser does not support feature ("+XINCLUDE_FEATURE_ID+")");
973             }
974             try {
975                 parser.setFeature(XINCLUDE_FIXUP_BASE_URIS_FEATURE_ID, xincludeFixupBaseURIs);
976             }
977             catch (SAXNotRecognizedException JavaDoc e) {
978                 System.err.println("warning: Parser does not recognize feature ("+XINCLUDE_FIXUP_BASE_URIS_FEATURE_ID+")");
979             }
980             catch (SAXNotSupportedException JavaDoc e) {
981                 System.err.println("warning: Parser does not support feature ("+XINCLUDE_FIXUP_BASE_URIS_FEATURE_ID+")");
982             }
983             try {
984                 parser.setFeature(XINCLUDE_FIXUP_LANGUAGE_FEATURE_ID, xincludeFixupLanguage);
985             }
986             catch (SAXNotRecognizedException JavaDoc e) {
987                 System.err.println("warning: Parser does not recognize feature ("+XINCLUDE_FIXUP_LANGUAGE_FEATURE_ID+")");
988             }
989             catch (SAXNotSupportedException JavaDoc e) {
990                 System.err.println("warning: Parser does not support feature ("+XINCLUDE_FIXUP_LANGUAGE_FEATURE_ID+")");
991             }
992
993             // set handlers
994
parser.setDTDHandler(tracer);
995             parser.setErrorHandler(tracer);
996             if (parser instanceof XMLReader JavaDoc) {
997                 parser.setContentHandler(tracer);
998                 try {
999                     parser.setProperty("http://xml.org/sax/properties/declaration-handler", tracer);
1000                }
1001                catch (SAXException JavaDoc e) {
1002                    e.printStackTrace(System.err);
1003                }
1004                try {
1005                    parser.setProperty("http://xml.org/sax/properties/lexical-handler", tracer);
1006                }
1007                catch (SAXException JavaDoc e) {
1008                    e.printStackTrace(System.err);
1009                }
1010            }
1011            else {
1012                ((Parser JavaDoc)parser).setDocumentHandler(tracer);
1013            }
1014
1015            // parse file
1016
try {
1017                parser.parse(arg);
1018            }
1019            catch (SAXParseException JavaDoc e) {
1020                // ignore
1021
}
1022            catch (Exception JavaDoc e) {
1023                System.err.println("error: Parse error occurred - "+e.getMessage());
1024                if (e instanceof SAXException JavaDoc) {
1025                    Exception JavaDoc nested = ((SAXException JavaDoc)e).getException();
1026                    if (nested != null) {
1027                       e = nested;
1028                    }
1029                }
1030                e.printStackTrace(System.err);
1031            }
1032        }
1033
1034    } // main(String[])
1035

1036    //
1037
// Private static methods
1038
//
1039

1040    /** Prints the usage. */
1041    private static void printUsage() {
1042
1043        System.err.println("usage: java sax.DocumentTracer (options) uri ...");
1044        System.err.println();
1045
1046        System.err.println("options:");
1047        System.err.println(" -p name Select parser by name.");
1048        System.err.println(" -n | -N Turn on/off namespace processing.");
1049        System.err.println(" -np | -NP Turn on/off namespace prefixes.");
1050        System.err.println(" NOTE: Requires use of -n.");
1051        System.err.println(" -v | -V Turn on/off validation.");
1052        System.err.println(" -xd | -XD Turn on/off loading of external DTDs.");
1053        System.err.println(" NOTE: Always on when -v in use and not supported by all parsers.");
1054        System.err.println(" -s | -S Turn on/off Schema validation support.");
1055        System.err.println(" NOTE: Not supported by all parsers.");
1056        System.err.println(" -f | -F Turn on/off Schema full checking.");
1057        System.err.println(" NOTE: Requires use of -s and not supported by all parsers.");
1058        System.err.println(" -va | -VA Turn on/off validation of schema annotations.");
1059        System.err.println(" NOTE: Requires use of -s and not supported by all parsers.");
1060        System.err.println(" -dv | -DV Turn on/off dynamic validation.");
1061        System.err.println(" NOTE: Not supported by all parsers.");
1062        System.err.println(" -xi | -XI Turn on/off XInclude processing.");
1063        System.err.println(" NOTE: Not supported by all parsers.");
1064        System.err.println(" -xb | -XB Turn on/off base URI fixup during XInclude processing.");
1065        System.err.println(" NOTE: Requires use of -xi and not supported by all parsers.");
1066        System.err.println(" -xl | -XL Turn on/off language fixup during XInclude processing.");
1067        System.err.println(" NOTE: Requires use of -xi and not supported by all parsers.");
1068        System.err.println(" -h This help screen.");
1069        System.err.println();
1070
1071        System.err.println("defaults:");
1072        System.err.println(" Parser: "+DEFAULT_PARSER_NAME);
1073        System.err.print(" Namespaces: ");
1074        System.err.println(DEFAULT_NAMESPACES ? "on" : "off");
1075        System.err.print(" Prefixes: ");
1076        System.err.println(DEFAULT_NAMESPACE_PREFIXES ? "on" : "off");
1077        System.err.print(" Validation: ");
1078        System.err.println(DEFAULT_VALIDATION ? "on" : "off");
1079        System.err.print(" Load External DTD: ");
1080        System.err.println(DEFAULT_LOAD_EXTERNAL_DTD ? "on" : "off");
1081        System.err.print(" Schema: ");
1082        System.err.println(DEFAULT_SCHEMA_VALIDATION ? "on" : "off");
1083        System.err.print(" Schema full checking: ");
1084        System.err.println(DEFAULT_SCHEMA_FULL_CHECKING ? "on" : "off");
1085        System.err.print(" Dynamic: ");
1086        System.err.println(DEFAULT_DYNAMIC_VALIDATION ? "on" : "off");
1087        System.err.print(" XInclude: ");
1088        System.err.println(DEFAULT_XINCLUDE ? "on" : "off");
1089        System.err.print(" XInclude base URI fixup: ");
1090        System.err.println(DEFAULT_XINCLUDE_FIXUP_BASE_URIS ? "on" : "off");
1091        System.err.print(" XInclude language fixup: ");
1092        System.err.println(DEFAULT_XINCLUDE_FIXUP_LANGUAGE ? "on" : "off");
1093
1094    } // printUsage()
1095

1096} // class DocumentTracer
1097
Popular Tags