KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > sax > Writer


1 /*
2  * Copyright 1999-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.lang.reflect.Method JavaDoc;
20
21 import java.io.OutputStream JavaDoc;
22 import java.io.OutputStreamWriter JavaDoc;
23 import java.io.PrintWriter JavaDoc;
24 import java.io.UnsupportedEncodingException JavaDoc;
25
26 import sax.helpers.AttributesImpl;
27
28 import org.xml.sax.Attributes JavaDoc;
29 import org.xml.sax.Locator JavaDoc;
30 import org.xml.sax.Parser JavaDoc;
31 import org.xml.sax.SAXException JavaDoc;
32 import org.xml.sax.SAXNotRecognizedException JavaDoc;
33 import org.xml.sax.SAXNotSupportedException JavaDoc;
34 import org.xml.sax.SAXParseException JavaDoc;
35 import org.xml.sax.XMLReader JavaDoc;
36 import org.xml.sax.ext.LexicalHandler JavaDoc;
37 import org.xml.sax.helpers.DefaultHandler JavaDoc;
38 import org.xml.sax.helpers.ParserAdapter JavaDoc;
39 import org.xml.sax.helpers.ParserFactory JavaDoc;
40 import org.xml.sax.helpers.XMLReaderFactory JavaDoc;
41
42 /**
43  * A sample SAX2 writer. This sample program illustrates how to
44  * register a SAX2 ContentHandler and receive the callbacks in
45  * order to print a document that is parsed.
46  *
47  * @author Andy Clark, IBM
48  *
49  * @version $Id: Writer.java,v 1.16 2005/05/09 00:29:47 mrglavas Exp $
50  */

51 public class Writer
52     extends DefaultHandler JavaDoc
53     implements LexicalHandler JavaDoc {
54
55     //
56
// Constants
57
//
58

59     // feature ids
60

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

99     /** Lexical handler property id (http://xml.org/sax/properties/lexical-handler). */
100     protected static final String JavaDoc LEXICAL_HANDLER_PROPERTY_ID = "http://xml.org/sax/properties/lexical-handler";
101
102     // default settings
103

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

150     /** Print writer. */
151     protected PrintWriter JavaDoc fOut;
152
153     /** Canonical output. */
154     protected boolean fCanonical;
155
156     /** Element depth. */
157     protected int fElementDepth;
158     
159     /** Document locator. */
160     protected Locator JavaDoc fLocator;
161     
162     /** Processing XML 1.1 document. */
163     protected boolean fXML11;
164     
165     /** In CDATA section. */
166     protected boolean fInCDATA;
167
168     //
169
// Constructors
170
//
171

172     /** Default constructor. */
173     public Writer() {
174     } // <init>()
175

176     //
177
// Public methods
178
//
179

180     /** Sets whether output is canonical. */
181     public void setCanonical(boolean canonical) {
182         fCanonical = canonical;
183     } // setCanonical(boolean)
184

185     /** Sets the output stream for printing. */
186     public void setOutput(OutputStream JavaDoc stream, String JavaDoc encoding)
187         throws UnsupportedEncodingException JavaDoc {
188
189         if (encoding == null) {
190             encoding = "UTF8";
191         }
192
193         java.io.Writer JavaDoc writer = new OutputStreamWriter JavaDoc(stream, encoding);
194         fOut = new PrintWriter JavaDoc(writer);
195
196     } // setOutput(OutputStream,String)
197

198     /** Sets the output writer. */
199     public void setOutput(java.io.Writer JavaDoc writer) {
200
201         fOut = writer instanceof PrintWriter JavaDoc
202              ? (PrintWriter JavaDoc)writer : new PrintWriter JavaDoc(writer);
203
204     } // setOutput(java.io.Writer)
205

206     //
207
// ContentHandler methods
208
//
209

210     /** Set Document Locator. */
211     public void setDocumentLocator(Locator JavaDoc locator) {
212         fLocator = locator;
213     } // setDocumentLocator(Locator)
214

215     /** Start document. */
216     public void startDocument() throws SAXException JavaDoc {
217
218         fElementDepth = 0;
219         fXML11 = false;
220         fInCDATA = false;
221         
222     } // startDocument()
223

224     /** Processing instruction. */
225     public void processingInstruction(String JavaDoc target, String JavaDoc data)
226         throws SAXException JavaDoc {
227
228         if (fElementDepth > 0) {
229             fOut.print("<?");
230             fOut.print(target);
231             if (data != null && data.length() > 0) {
232                 fOut.print(' ');
233                 fOut.print(data);
234             }
235             fOut.print("?>");
236             fOut.flush();
237         }
238
239     } // processingInstruction(String,String)
240

241     /** Start element. */
242     public void startElement(String JavaDoc uri, String JavaDoc local, String JavaDoc raw,
243                              Attributes JavaDoc attrs) throws SAXException JavaDoc {
244
245         // Root Element
246
if (fElementDepth == 0) {
247             if (fLocator != null) {
248                 fXML11 = "1.1".equals(getVersion());
249                 fLocator = null;
250             }
251
252             // The XML declaration cannot be printed in startDocument because
253
// the version reported by the Locator cannot be relied on until after
254
// the XML declaration in the instance document has been read.
255
if (!fCanonical) {
256                 if (fXML11) {
257                     fOut.println("<?xml version=\"1.1\" encoding=\"UTF-8\"?>");
258                 }
259                 else {
260                     fOut.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
261                 }
262                 fOut.flush();
263             }
264         }
265         
266         fElementDepth++;
267         fOut.print('<');
268         fOut.print(raw);
269         if (attrs != null) {
270             attrs = sortAttributes(attrs);
271             int len = attrs.getLength();
272             for (int i = 0; i < len; i++) {
273                 fOut.print(' ');
274                 fOut.print(attrs.getQName(i));
275                 fOut.print("=\"");
276                 normalizeAndPrint(attrs.getValue(i), true);
277                 fOut.print('"');
278             }
279         }
280         fOut.print('>');
281         fOut.flush();
282
283     } // startElement(String,String,String,Attributes)
284

285     /** Characters. */
286     public void characters(char ch[], int start, int length)
287         throws SAXException JavaDoc {
288
289         if (!fInCDATA) {
290             normalizeAndPrint(ch, start, length, false);
291         }
292         else {
293             for (int i = 0; i < length; ++i) {
294                 fOut.print(ch[start+i]);
295             }
296         }
297         fOut.flush();
298
299     } // characters(char[],int,int);
300

301     /** Ignorable whitespace. */
302     public void ignorableWhitespace(char ch[], int start, int length)
303         throws SAXException JavaDoc {
304
305         characters(ch, start, length);
306         fOut.flush();
307
308     } // ignorableWhitespace(char[],int,int);
309

310     /** End element. */
311     public void endElement(String JavaDoc uri, String JavaDoc local, String JavaDoc raw)
312         throws SAXException JavaDoc {
313
314         fElementDepth--;
315         fOut.print("</");
316         fOut.print(raw);
317         fOut.print('>');
318         fOut.flush();
319
320     } // endElement(String)
321

322     //
323
// ErrorHandler methods
324
//
325

326     /** Warning. */
327     public void warning(SAXParseException JavaDoc ex) throws SAXException JavaDoc {
328         printError("Warning", ex);
329     } // warning(SAXParseException)
330

331     /** Error. */
332     public void error(SAXParseException JavaDoc ex) throws SAXException JavaDoc {
333         printError("Error", ex);
334     } // error(SAXParseException)
335

336     /** Fatal error. */
337     public void fatalError(SAXParseException JavaDoc ex) throws SAXException JavaDoc {
338         printError("Fatal Error", ex);
339         throw ex;
340     } // fatalError(SAXParseException)
341

342     //
343
// LexicalHandler methods
344
//
345

346     /** Start DTD. */
347     public void startDTD(String JavaDoc name, String JavaDoc publicId, String JavaDoc systemId)
348         throws SAXException JavaDoc {
349     } // startDTD(String,String,String)
350

351     /** End DTD. */
352     public void endDTD() throws SAXException JavaDoc {
353     } // endDTD()
354

355     /** Start entity. */
356     public void startEntity(String JavaDoc name) throws SAXException JavaDoc {
357     } // startEntity(String)
358

359     /** End entity. */
360     public void endEntity(String JavaDoc name) throws SAXException JavaDoc {
361     } // endEntity(String)
362

363     /** Start CDATA section. */
364     public void startCDATA() throws SAXException JavaDoc {
365         if (!fCanonical) {
366             fOut.print("<![CDATA[");
367             fInCDATA = true;
368         }
369     } // startCDATA()
370

371     /** End CDATA section. */
372     public void endCDATA() throws SAXException JavaDoc {
373         if (!fCanonical) {
374             fInCDATA = false;
375             fOut.print("]]>");
376         }
377     } // endCDATA()
378

379     /** Comment. */
380     public void comment(char ch[], int start, int length) throws SAXException JavaDoc {
381         if (!fCanonical && fElementDepth > 0) {
382             fOut.print("<!--");
383             for (int i = 0; i < length; ++i) {
384                 fOut.print(ch[start+i]);
385             }
386             fOut.print("-->");
387             fOut.flush();
388         }
389     } // comment(char[],int,int)
390

391     //
392
// Protected methods
393
//
394

395     /** Returns a sorted list of attributes. */
396     protected Attributes JavaDoc sortAttributes(Attributes JavaDoc attrs) {
397
398         AttributesImpl attributes = new AttributesImpl();
399
400         int len = (attrs != null) ? attrs.getLength() : 0;
401         for (int i = 0; i < len; i++) {
402             String JavaDoc name = attrs.getQName(i);
403             int count = attributes.getLength();
404             int j = 0;
405             while (j < count) {
406                 if (name.compareTo(attributes.getQName(j)) < 0) {
407                     break;
408                 }
409                 j++;
410             }
411             attributes.insertAttributeAt(j, name, attrs.getType(i),
412                                          attrs.getValue(i));
413         }
414
415         return attributes;
416
417     } // sortAttributes(AttributeList):AttributeList
418

419     /** Normalizes and prints the given string. */
420     protected void normalizeAndPrint(String JavaDoc s, boolean isAttValue) {
421
422         int len = (s != null) ? s.length() : 0;
423         for (int i = 0; i < len; i++) {
424             char c = s.charAt(i);
425             normalizeAndPrint(c, isAttValue);
426         }
427
428     } // normalizeAndPrint(String,boolean)
429

430     /** Normalizes and prints the given array of characters. */
431     protected void normalizeAndPrint(char[] ch, int offset, int length, boolean isAttValue) {
432         for (int i = 0; i < length; i++) {
433             normalizeAndPrint(ch[offset + i], isAttValue);
434         }
435     } // normalizeAndPrint(char[],int,int,boolean)
436

437     /** Normalizes and print the given character. */
438     protected void normalizeAndPrint(char c, boolean isAttValue) {
439
440         switch (c) {
441             case '<': {
442                 fOut.print("&lt;");
443                 break;
444             }
445             case '>': {
446                 fOut.print("&gt;");
447                 break;
448             }
449             case '&': {
450                 fOut.print("&amp;");
451                 break;
452             }
453             case '"': {
454                 // A '"' that appears in character data
455
// does not need to be escaped.
456
if (isAttValue) {
457                     fOut.print("&quot;");
458                 }
459                 else {
460                     fOut.print("\"");
461                 }
462                 break;
463             }
464             case '\r': {
465                 // If CR is part of the document's content, it
466
// must not be printed as a literal otherwise
467
// it would be normalized to LF when the document
468
// is reparsed.
469
fOut.print("&#xD;");
470                 break;
471             }
472             case '\n': {
473                 if (fCanonical) {
474                     fOut.print("&#xA;");
475                     break;
476                 }
477                 // else, default print char
478
}
479             default: {
480             // In XML 1.1, control chars in the ranges [#x1-#x1F, #x7F-#x9F] must be escaped.
481
//
482
// Escape space characters that would be normalized to #x20 in attribute values
483
// when the document is reparsed.
484
//
485
// Escape NEL (0x85) and LSEP (0x2028) that appear in content
486
// if the document is XML 1.1, since they would be normalized to LF
487
// when the document is reparsed.
488
if (fXML11 && ((c >= 0x01 && c <= 0x1F && c != 0x09 && c != 0x0A)
489                     || (c >= 0x7F && c <= 0x9F) || c == 0x2028)
490                     || isAttValue && (c == 0x09 || c == 0x0A)) {
491                     fOut.print("&#x");
492                     fOut.print(Integer.toHexString(c).toUpperCase());
493                     fOut.print(";");
494                 }
495                 else {
496                     fOut.print(c);
497                 }
498             }
499         }
500     } // normalizeAndPrint(char,boolean)
501

502     /** Prints the error message. */
503     protected void printError(String JavaDoc type, SAXParseException JavaDoc ex) {
504
505         System.err.print("[");
506         System.err.print(type);
507         System.err.print("] ");
508         String JavaDoc systemId = ex.getSystemId();
509         if (systemId != null) {
510             int index = systemId.lastIndexOf('/');
511             if (index != -1)
512                 systemId = systemId.substring(index + 1);
513             System.err.print(systemId);
514         }
515         System.err.print(':');
516         System.err.print(ex.getLineNumber());
517         System.err.print(':');
518         System.err.print(ex.getColumnNumber());
519         System.err.print(": ");
520         System.err.print(ex.getMessage());
521         System.err.println();
522         System.err.flush();
523
524     } // printError(String,SAXParseException)
525

526     /** Extracts the XML version from the Locator. */
527     protected String JavaDoc getVersion() {
528         if (fLocator == null) {
529             return null;
530         }
531         String JavaDoc version = null;
532         Method JavaDoc getXMLVersion = null;
533         try {
534             getXMLVersion = fLocator.getClass().getMethod("getXMLVersion", new Class JavaDoc[]{});
535             // If Locator implements Locator2, this method will exist.
536
if (getXMLVersion != null) {
537                 version = (String JavaDoc) getXMLVersion.invoke(fLocator, (Object JavaDoc[]) null);
538             }
539         }
540         catch (Exception JavaDoc e) {
541             // Either this locator object doesn't have
542
// this method, or we're on an old JDK.
543
}
544         return version;
545     } // getVersion()
546

547     //
548
// Main
549
//
550

551     /** Main program entry point. */
552     public static void main(String JavaDoc argv[]) {
553
554         // is there anything to do?
555
if (argv.length == 0) {
556             printUsage();
557             System.exit(1);
558         }
559
560         // variables
561
Writer writer = null;
562         XMLReader JavaDoc parser = null;
563         boolean namespaces = DEFAULT_NAMESPACES;
564         boolean namespacePrefixes = DEFAULT_NAMESPACE_PREFIXES;
565         boolean validation = DEFAULT_VALIDATION;
566         boolean externalDTD = DEFAULT_LOAD_EXTERNAL_DTD;
567         boolean schemaValidation = DEFAULT_SCHEMA_VALIDATION;
568         boolean schemaFullChecking = DEFAULT_SCHEMA_FULL_CHECKING;
569         boolean validateAnnotations = DEFAULT_VALIDATE_ANNOTATIONS;
570         boolean generateSyntheticAnnotations = DEFAULT_GENERATE_SYNTHETIC_ANNOTATIONS;
571         boolean dynamicValidation = DEFAULT_DYNAMIC_VALIDATION;
572         boolean xincludeProcessing = DEFAULT_XINCLUDE;
573         boolean xincludeFixupBaseURIs = DEFAULT_XINCLUDE_FIXUP_BASE_URIS;
574         boolean xincludeFixupLanguage = DEFAULT_XINCLUDE_FIXUP_LANGUAGE;
575         boolean canonical = DEFAULT_CANONICAL;
576
577         // process arguments
578
for (int i = 0; i < argv.length; i++) {
579             String JavaDoc arg = argv[i];
580             if (arg.startsWith("-")) {
581                 String JavaDoc option = arg.substring(1);
582                 if (option.equals("p")) {
583                     // get parser name
584
if (++i == argv.length) {
585                         System.err.println("error: Missing argument to -p option.");
586                     }
587                     String JavaDoc parserName = argv[i];
588
589                     // create parser
590
try {
591                         parser = XMLReaderFactory.createXMLReader(parserName);
592                     }
593                     catch (Exception JavaDoc e) {
594                         try {
595                             Parser JavaDoc sax1Parser = ParserFactory.makeParser(parserName);
596                             parser = new ParserAdapter JavaDoc(sax1Parser);
597                             System.err.println("warning: Features and properties not supported on SAX1 parsers.");
598                         }
599                         catch (Exception JavaDoc ex) {
600                             parser = null;
601                             System.err.println("error: Unable to instantiate parser ("+parserName+")");
602                             e.printStackTrace(System.err);
603                         }
604                     }
605                     continue;
606                 }
607                 if (option.equalsIgnoreCase("n")) {
608                     namespaces = option.equals("n");
609                     continue;
610                 }
611                 if (option.equalsIgnoreCase("np")) {
612                     namespacePrefixes = option.equals("np");
613                     continue;
614                 }
615                 if (option.equalsIgnoreCase("v")) {
616                     validation = option.equals("v");
617                     continue;
618                 }
619                 if (option.equalsIgnoreCase("xd")) {
620                     externalDTD = option.equals("xd");
621                     continue;
622                 }
623                 if (option.equalsIgnoreCase("s")) {
624                     schemaValidation = option.equals("s");
625                     continue;
626                 }
627                 if (option.equalsIgnoreCase("f")) {
628                     schemaFullChecking = option.equals("f");
629                     continue;
630                 }
631                 if (option.equalsIgnoreCase("va")) {
632                     validateAnnotations = option.equals("va");
633                     continue;
634                 }
635                 if (option.equalsIgnoreCase("ga")) {
636                     generateSyntheticAnnotations = option.equals("ga");
637                     continue;
638                 }
639                 if (option.equalsIgnoreCase("dv")) {
640                     dynamicValidation = option.equals("dv");
641                     continue;
642                 }
643                 if (option.equalsIgnoreCase("xi")) {
644                     xincludeProcessing = option.equals("xi");
645                     continue;
646                 }
647                 if (option.equalsIgnoreCase("xb")) {
648                     xincludeFixupBaseURIs = option.equals("xb");
649                     continue;
650                 }
651                 if (option.equalsIgnoreCase("xl")) {
652                     xincludeFixupLanguage = option.equals("xl");
653                     continue;
654                 }
655                 if (option.equalsIgnoreCase("c")) {
656                     canonical = option.equals("c");
657                     continue;
658                 }
659                 if (option.equals("h")) {
660                     printUsage();
661                     continue;
662                 }
663             }
664
665             // use default parser?
666
if (parser == null) {
667
668                 // create parser
669
try {
670                     parser = XMLReaderFactory.createXMLReader(DEFAULT_PARSER_NAME);
671                 }
672                 catch (Exception JavaDoc e) {
673                     System.err.println("error: Unable to instantiate parser ("+DEFAULT_PARSER_NAME+")");
674                     e.printStackTrace(System.err);
675                     continue;
676                 }
677             }
678
679             // set parser features
680
try {
681                 parser.setFeature(NAMESPACES_FEATURE_ID, namespaces);
682             }
683             catch (SAXException JavaDoc e) {
684                 System.err.println("warning: Parser does not support feature ("+NAMESPACES_FEATURE_ID+")");
685             }
686             try {
687                 parser.setFeature(NAMESPACE_PREFIXES_FEATURE_ID, namespacePrefixes);
688             }
689             catch (SAXException JavaDoc e) {
690                 System.err.println("warning: Parser does not support feature ("+NAMESPACE_PREFIXES_FEATURE_ID+")");
691             }
692             try {
693                 parser.setFeature(VALIDATION_FEATURE_ID, validation);
694             }
695             catch (SAXException JavaDoc e) {
696                 System.err.println("warning: Parser does not support feature ("+VALIDATION_FEATURE_ID+")");
697             }
698             try {
699                 parser.setFeature(LOAD_EXTERNAL_DTD_FEATURE_ID, externalDTD);
700             }
701             catch (SAXNotRecognizedException JavaDoc e) {
702                 System.err.println("warning: Parser does not recognize feature ("+LOAD_EXTERNAL_DTD_FEATURE_ID+")");
703             }
704             catch (SAXNotSupportedException JavaDoc e) {
705                 System.err.println("warning: Parser does not support feature ("+LOAD_EXTERNAL_DTD_FEATURE_ID+")");
706             }
707             try {
708                 parser.setFeature(SCHEMA_VALIDATION_FEATURE_ID, schemaValidation);
709             }
710             catch (SAXNotRecognizedException JavaDoc e) {
711                 System.err.println("warning: Parser does not recognize feature ("+SCHEMA_VALIDATION_FEATURE_ID+")");
712             }
713             catch (SAXNotSupportedException JavaDoc e) {
714                 System.err.println("warning: Parser does not support feature ("+SCHEMA_VALIDATION_FEATURE_ID+")");
715             }
716             try {
717                 parser.setFeature(SCHEMA_FULL_CHECKING_FEATURE_ID, schemaFullChecking);
718             }
719             catch (SAXNotRecognizedException JavaDoc e) {
720                 System.err.println("warning: Parser does not recognize feature ("+SCHEMA_FULL_CHECKING_FEATURE_ID+")");
721             }
722             catch (SAXNotSupportedException JavaDoc e) {
723                 System.err.println("warning: Parser does not support feature ("+SCHEMA_FULL_CHECKING_FEATURE_ID+")");
724             }
725             try {
726                 parser.setFeature(VALIDATE_ANNOTATIONS_ID, validateAnnotations);
727             }
728             catch (SAXNotRecognizedException JavaDoc e) {
729                 System.err.println("warning: Parser does not recognize feature ("+VALIDATE_ANNOTATIONS_ID+")");
730             }
731             catch (SAXNotSupportedException JavaDoc e) {
732                 System.err.println("warning: Parser does not support feature ("+VALIDATE_ANNOTATIONS_ID+")");
733             }
734             try {
735                 parser.setFeature(GENERATE_SYNTHETIC_ANNOTATIONS_ID, generateSyntheticAnnotations);
736             }
737             catch (SAXNotRecognizedException JavaDoc e) {
738                 System.err.println("warning: Parser does not recognize feature ("+GENERATE_SYNTHETIC_ANNOTATIONS_ID+")");
739             }
740             catch (SAXNotSupportedException JavaDoc e) {
741                 System.err.println("warning: Parser does not support feature ("+GENERATE_SYNTHETIC_ANNOTATIONS_ID+")");
742             }
743             try {
744                 parser.setFeature(DYNAMIC_VALIDATION_FEATURE_ID, dynamicValidation);
745             }
746             catch (SAXNotRecognizedException JavaDoc e) {
747                 System.err.println("warning: Parser does not recognize feature ("+DYNAMIC_VALIDATION_FEATURE_ID+")");
748             }
749             catch (SAXNotSupportedException JavaDoc e) {
750                 System.err.println("warning: Parser does not support feature ("+DYNAMIC_VALIDATION_FEATURE_ID+")");
751             }
752             try {
753                 parser.setFeature(XINCLUDE_FEATURE_ID, xincludeProcessing);
754             }
755             catch (SAXNotRecognizedException JavaDoc e) {
756                 System.err.println("warning: Parser does not recognize feature ("+XINCLUDE_FEATURE_ID+")");
757             }
758             catch (SAXNotSupportedException JavaDoc e) {
759                 System.err.println("warning: Parser does not support feature ("+XINCLUDE_FEATURE_ID+")");
760             }
761             try {
762                 parser.setFeature(XINCLUDE_FIXUP_BASE_URIS_FEATURE_ID, xincludeFixupBaseURIs);
763             }
764             catch (SAXNotRecognizedException JavaDoc e) {
765                 System.err.println("warning: Parser does not recognize feature ("+XINCLUDE_FIXUP_BASE_URIS_FEATURE_ID+")");
766             }
767             catch (SAXNotSupportedException JavaDoc e) {
768                 System.err.println("warning: Parser does not support feature ("+XINCLUDE_FIXUP_BASE_URIS_FEATURE_ID+")");
769             }
770             try {
771                 parser.setFeature(XINCLUDE_FIXUP_LANGUAGE_FEATURE_ID, xincludeFixupLanguage);
772             }
773             catch (SAXNotRecognizedException JavaDoc e) {
774                 System.err.println("warning: Parser does not recognize feature ("+XINCLUDE_FIXUP_LANGUAGE_FEATURE_ID+")");
775             }
776             catch (SAXNotSupportedException JavaDoc e) {
777                 System.err.println("warning: Parser does not support feature ("+XINCLUDE_FIXUP_LANGUAGE_FEATURE_ID+")");
778             }
779             
780             // setup writer
781
if (writer == null) {
782                 writer = new Writer();
783                 try {
784                     writer.setOutput(System.out, "UTF8");
785                 }
786                 catch (UnsupportedEncodingException JavaDoc e) {
787                     System.err.println("error: Unable to set output. Exiting.");
788                     System.exit(1);
789                 }
790             }
791
792             // set parser
793
parser.setContentHandler(writer);
794             parser.setErrorHandler(writer);
795             try {
796                 parser.setProperty(LEXICAL_HANDLER_PROPERTY_ID, writer);
797             }
798             catch (SAXException JavaDoc e) {
799                 // ignore
800
}
801
802             // parse file
803
writer.setCanonical(canonical);
804             try {
805                 parser.parse(arg);
806             }
807             catch (SAXParseException JavaDoc e) {
808                 // ignore
809
}
810             catch (Exception JavaDoc e) {
811                 System.err.println("error: Parse error occurred - "+e.getMessage());
812                 if (e instanceof SAXException JavaDoc) {
813                     Exception JavaDoc nested = ((SAXException JavaDoc)e).getException();
814                     if (nested != null) {
815                         e = nested;
816                     }
817                 }
818                 e.printStackTrace(System.err);
819             }
820         }
821
822     } // main(String[])
823

824     //
825
// Private static methods
826
//
827

828     /** Prints the usage. */
829     private static void printUsage() {
830
831         System.err.println("usage: java sax.Writer (options) uri ...");
832         System.err.println();
833
834         System.err.println("options:");
835         System.err.println(" -p name Select parser by name.");
836         System.err.println(" -n | -N Turn on/off namespace processing.");
837         System.err.println(" -np | -NP Turn on/off namespace prefixes.");
838         System.err.println(" NOTE: Requires use of -n.");
839         System.err.println(" -v | -V Turn on/off validation.");
840         System.err.println(" -xd | -XD Turn on/off loading of external DTDs.");
841         System.err.println(" NOTE: Always on when -v in use and not supported by all parsers.");
842         System.err.println(" -s | -S Turn on/off Schema validation support.");
843         System.err.println(" NOTE: Not supported by all parsers.");
844         System.err.println(" -f | -F Turn on/off Schema full checking.");
845         System.err.println(" NOTE: Requires use of -s and not supported by all parsers.");
846         System.err.println(" -va | -VA Turn on/off validation of schema annotations.");
847         System.err.println(" NOTE: Requires use of -s and not supported by all parsers.");
848         System.err.println(" -ga | -GA Turn on/off generation of synthetic schema annotations.");
849         System.err.println(" NOTE: Requires use of -s and not supported by all parsers.");
850         System.err.println(" -dv | -DV Turn on/off dynamic validation.");
851         System.err.println(" NOTE: Not supported by all parsers.");
852         System.err.println(" -xi | -XI Turn on/off XInclude processing.");
853         System.err.println(" NOTE: Not supported by all parsers.");
854         System.err.println(" -xb | -XB Turn on/off base URI fixup during XInclude processing.");
855         System.err.println(" NOTE: Requires use of -xi and not supported by all parsers.");
856         System.err.println(" -xl | -XL Turn on/off language fixup during XInclude processing.");
857         System.err.println(" NOTE: Requires use of -xi and not supported by all parsers.");
858         System.err.println(" -c | -C Turn on/off Canonical XML output.");
859         System.err.println(" NOTE: This is not W3C canonical output.");
860         System.err.println(" -h This help screen.");
861         System.err.println();
862
863         System.err.println("defaults:");
864         System.err.println(" Parser: "+DEFAULT_PARSER_NAME);
865         System.err.print(" Namespaces: ");
866         System.err.println(DEFAULT_NAMESPACES ? "on" : "off");
867         System.err.print(" Prefixes: ");
868         System.err.println(DEFAULT_NAMESPACE_PREFIXES ? "on" : "off");
869         System.err.print(" Validation: ");
870         System.err.println(DEFAULT_VALIDATION ? "on" : "off");
871         System.err.print(" Load External DTD: ");
872         System.err.println(DEFAULT_LOAD_EXTERNAL_DTD ? "on" : "off");
873         System.err.print(" Schema: ");
874         System.err.println(DEFAULT_SCHEMA_VALIDATION ? "on" : "off");
875         System.err.print(" Schema full checking: ");
876         System.err.println(DEFAULT_SCHEMA_FULL_CHECKING ? "on" : "off");
877         System.err.print(" Dynamic: ");
878         System.err.println(DEFAULT_DYNAMIC_VALIDATION ? "on" : "off");
879         System.err.print(" Canonical: ");
880         System.err.println(DEFAULT_CANONICAL ? "on" : "off");
881         System.err.print(" Validate Annotations: ");
882         System.err.println(DEFAULT_VALIDATE_ANNOTATIONS ? "on" : "off");
883         System.err.print(" Generate Synthetic Annotations: ");
884         System.err.println(DEFAULT_GENERATE_SYNTHETIC_ANNOTATIONS ? "on" : "off");
885         System.err.print(" XInclude: ");
886         System.err.println(DEFAULT_XINCLUDE ? "on" : "off");
887         System.err.print(" XInclude base URI fixup: ");
888         System.err.println(DEFAULT_XINCLUDE_FIXUP_BASE_URIS ? "on" : "off");
889         System.err.print(" XInclude language fixup: ");
890         System.err.println(DEFAULT_XINCLUDE_FIXUP_LANGUAGE ? "on" : "off");
891
892     } // printUsage()
893

894 } // class Writer
895
Popular Tags