KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > jaxp > TypeInfoWriter


1 /*
2  * Copyright 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 jaxp;
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.util.Vector JavaDoc;
24
25 import javax.xml.XMLConstants JavaDoc;
26 import javax.xml.transform.stream.StreamSource JavaDoc;
27 import javax.xml.validation.Schema JavaDoc;
28 import javax.xml.validation.SchemaFactory JavaDoc;
29 import javax.xml.validation.TypeInfoProvider JavaDoc;
30 import javax.xml.validation.ValidatorHandler JavaDoc;
31
32 import org.w3c.dom.TypeInfo JavaDoc;
33 import org.xml.sax.Attributes JavaDoc;
34 import org.xml.sax.DTDHandler JavaDoc;
35 import org.xml.sax.Locator JavaDoc;
36 import org.xml.sax.Parser JavaDoc;
37 import org.xml.sax.SAXException JavaDoc;
38 import org.xml.sax.SAXNotRecognizedException JavaDoc;
39 import org.xml.sax.SAXNotSupportedException JavaDoc;
40 import org.xml.sax.SAXParseException JavaDoc;
41 import org.xml.sax.XMLReader JavaDoc;
42 import org.xml.sax.helpers.DefaultHandler JavaDoc;
43 import org.xml.sax.helpers.ParserAdapter JavaDoc;
44 import org.xml.sax.helpers.ParserFactory JavaDoc;
45 import org.xml.sax.helpers.XMLReaderFactory JavaDoc;
46
47 /**
48  * <p>Provides a trace of the schema type information for elements and
49  * attributes in an XML document. This demonstrates usage of the
50  * JAXP 1.3 Validation API, particuarly how to read type information
51  * from a TypeInfoProvider.</p>
52  *
53  * @author Michael Glavassevich, IBM
54  *
55  * @version $Id: TypeInfoWriter.java,v 1.1 2005/06/01 04:48:36 mrglavas Exp $
56  */

57 public class TypeInfoWriter
58     extends DefaultHandler JavaDoc {
59
60     //
61
// Constants
62
//
63

64     // feature ids
65

66     /** Schema full checking feature id (http://apache.org/xml/features/validation/schema-full-checking). */
67     protected static final String JavaDoc SCHEMA_FULL_CHECKING_FEATURE_ID = "http://apache.org/xml/features/validation/schema-full-checking";
68     
69     /** Honour all schema locations feature id (http://apache.org/xml/features/honour-all-schemaLocations). */
70     protected static final String JavaDoc HONOUR_ALL_SCHEMA_LOCATIONS_ID = "http://apache.org/xml/features/honour-all-schemaLocations";
71     
72     /** Validate schema annotations feature id (http://apache.org/xml/features/validate-annotations) */
73     protected static final String JavaDoc VALIDATE_ANNOTATIONS_ID = "http://apache.org/xml/features/validate-annotations";
74     
75     /** Generate synthetic schema annotations feature id (http://apache.org/xml/features/generate-synthetic-annotations). */
76     protected static final String JavaDoc GENERATE_SYNTHETIC_ANNOTATIONS_ID = "http://apache.org/xml/features/generate-synthetic-annotations";
77     
78     // default settings
79

80     /** Default parser name. */
81     protected static final String JavaDoc DEFAULT_PARSER_NAME = "org.apache.xerces.parsers.SAXParser";
82     
83     /** Default schema full checking support (false). */
84     protected static final boolean DEFAULT_SCHEMA_FULL_CHECKING = false;
85     
86     /** Default honour all schema locations (false). */
87     protected static final boolean DEFAULT_HONOUR_ALL_SCHEMA_LOCATIONS = false;
88     
89     /** Default validate schema annotations (false). */
90     protected static final boolean DEFAULT_VALIDATE_ANNOTATIONS = false;
91     
92     /** Default generate synthetic schema annotations (false). */
93     protected static final boolean DEFAULT_GENERATE_SYNTHETIC_ANNOTATIONS = false;
94     
95     //
96
// Data
97
//
98

99     /** TypeInfo provider. */
100     protected TypeInfoProvider JavaDoc fTypeInfoProvider;
101     
102     /** Print writer. */
103     protected PrintWriter JavaDoc fOut;
104     
105     /** Indent level. */
106     protected int fIndent;
107     
108     //
109
// Constructors
110
//
111

112     /** Default constructor. */
113     public TypeInfoWriter() {}
114     
115     //
116
// ContentHandler and DocumentHandler methods
117
//
118

119     /** Set document locator. */
120     public void setDocumentLocator(Locator JavaDoc locator) {
121         
122         fIndent = 0;
123         printIndent();
124         fOut.print("setDocumentLocator(");
125         fOut.print("systemId=");
126         printQuotedString(locator.getSystemId());
127         fOut.print(", publicId=");
128         printQuotedString(locator.getPublicId());
129         fOut.println(')');
130         fOut.flush();
131
132     } // setDocumentLocator(Locator)
133

134     /** Start document. */
135     public void startDocument() throws SAXException JavaDoc {
136
137         fIndent = 0;
138         printIndent();
139         fOut.println("startDocument()");
140         fOut.flush();
141         fIndent++;
142
143     } // startDocument()
144

145     /** Start element. */
146     public void startElement(String JavaDoc uri, String JavaDoc localName, String JavaDoc qname,
147                              Attributes JavaDoc attributes) throws SAXException JavaDoc {
148
149         TypeInfo JavaDoc type;
150         printIndent();
151         fOut.print("startElement(");
152         fOut.print("name=");
153         printQName(uri, localName);
154         fOut.print(',');
155         fOut.print("type=");
156         if (fTypeInfoProvider != null && (type = fTypeInfoProvider.getElementTypeInfo()) != null) {
157             printQName(type.getTypeNamespace(), type.getTypeName());
158         }
159         else {
160             fOut.print("null");
161         }
162         fOut.print(',');
163         fOut.print("attributes=");
164         if (attributes == null) {
165             fOut.println("null");
166         }
167         else {
168             fOut.print('{');
169             int length = attributes.getLength();
170             for (int i = 0; i < length; i++) {
171                 if (i > 0) {
172                     fOut.print(',');
173                 }
174                 String JavaDoc attrURI = attributes.getURI(i);
175                 String JavaDoc attrLocalName = attributes.getLocalName(i);
176                 fOut.print('{');
177                 fOut.print("name=");
178                 printQName(attrURI, attrLocalName);
179                 fOut.print(',');
180                 fOut.print("type=");
181                 if (fTypeInfoProvider != null && (type = fTypeInfoProvider.getAttributeTypeInfo(i)) != null) {
182                     printQName(type.getTypeNamespace(), type.getTypeName());
183                 }
184                 else {
185                     fOut.print("null");
186                 }
187                 fOut.print(',');
188                 fOut.print("id=");
189                 fOut.print(fTypeInfoProvider != null && fTypeInfoProvider.isIdAttribute(i) ? "\"true\"" : "\"false\"");
190                 fOut.print(',');
191                 fOut.print("specified=");
192                 fOut.print(fTypeInfoProvider == null || fTypeInfoProvider.isSpecified(i) ? "\"true\"" : "\"false\"");
193                 fOut.print('}');
194             }
195             fOut.print('}');
196         }
197         fOut.println(')');
198         fOut.flush();
199         fIndent++;
200
201     } // startElement(String,String,String,Attributes)
202

203     /** End element. */
204     public void endElement(String JavaDoc uri, String JavaDoc localName, String JavaDoc qname)
205         throws SAXException JavaDoc {
206
207         fIndent--;
208         printIndent();
209         fOut.print("endElement(");
210         fOut.print("name=");
211         printQName(uri, localName);
212         fOut.println(')');
213         fOut.flush();
214
215     } // endElement(String,String,String)
216

217     /** End document. */
218     public void endDocument() throws SAXException JavaDoc {
219         fIndent--;
220         printIndent();
221         fOut.println("endDocument()");
222         fOut.flush();
223     } // endDocument()
224

225     //
226
// ErrorHandler methods
227
//
228

229     /** Warning. */
230     public void warning(SAXParseException JavaDoc ex) throws SAXException JavaDoc {
231         printError("Warning", ex);
232     } // warning(SAXParseException)
233

234     /** Error. */
235     public void error(SAXParseException JavaDoc ex) throws SAXException JavaDoc {
236         printError("Error", ex);
237     } // error(SAXParseException)
238

239     /** Fatal error. */
240     public void fatalError(SAXParseException JavaDoc ex) throws SAXException JavaDoc {
241         printError("Fatal Error", ex);
242         throw ex;
243     } // fatalError(SAXParseException)
244

245     //
246
// Public methods
247
//
248

249     
250     /** Sets the output stream for printing. */
251     public void setOutput(OutputStream JavaDoc stream, String JavaDoc encoding)
252         throws UnsupportedEncodingException JavaDoc {
253
254         if (encoding == null) {
255             encoding = "UTF8";
256         }
257
258         java.io.Writer JavaDoc writer = new OutputStreamWriter JavaDoc(stream, encoding);
259         fOut = new PrintWriter JavaDoc(writer);
260
261     } // setOutput(OutputStream,String)
262

263     //
264
// Protected methods
265
//
266

267     /** Sets the TypeInfoProvider used by this writer. */
268     protected void setTypeInfoProvider(TypeInfoProvider JavaDoc provider) {
269         fTypeInfoProvider = provider;
270     }
271     
272     /** Prints the error message. */
273     protected void printError(String JavaDoc type, SAXParseException JavaDoc ex) {
274
275         System.err.print("[");
276         System.err.print(type);
277         System.err.print("] ");
278         String JavaDoc systemId = ex.getSystemId();
279         if (systemId != null) {
280             int index = systemId.lastIndexOf('/');
281             if (index != -1)
282                 systemId = systemId.substring(index + 1);
283             System.err.print(systemId);
284         }
285         System.err.print(':');
286         System.err.print(ex.getLineNumber());
287         System.err.print(':');
288         System.err.print(ex.getColumnNumber());
289         System.err.print(": ");
290         System.err.print(ex.getMessage());
291         System.err.println();
292         System.err.flush();
293
294     } // printError(String,SAXParseException)
295

296     /** Prints the indent. */
297     protected void printIndent() {
298         for (int i = 0; i < fIndent; i++) {
299             fOut.print(' ');
300         }
301     } // printIndent()
302

303     protected void printQName(String JavaDoc uri, String JavaDoc localName) {
304         if (uri != null && uri.length() > 0) {
305             printQuotedString('{' + uri + "}" + localName);
306             return;
307         }
308         printQuotedString(localName);
309     }
310     
311     /** Print quoted string. */
312     protected void printQuotedString(String JavaDoc s) {
313
314         if (s == null) {
315             fOut.print("null");
316             return;
317         }
318         fOut.print('"');
319         fOut.print(s);
320         fOut.print('"');
321
322     } // printQuotedString(String)
323

324     //
325
// MAIN
326
//
327

328     /** Main program entry point. */
329     public static void main (String JavaDoc [] argv) {
330         
331         // is there anything to do?
332
if (argv.length == 0) {
333             printUsage();
334             System.exit(1);
335         }
336         
337         // variables
338
XMLReader JavaDoc parser = null;
339         Vector JavaDoc schemas = null;
340         Vector JavaDoc instances = null;
341         boolean schemaFullChecking = DEFAULT_SCHEMA_FULL_CHECKING;
342         boolean honourAllSchemaLocations = DEFAULT_HONOUR_ALL_SCHEMA_LOCATIONS;
343         boolean validateAnnotations = DEFAULT_VALIDATE_ANNOTATIONS;
344         boolean generateSyntheticAnnotations = DEFAULT_GENERATE_SYNTHETIC_ANNOTATIONS;
345         
346         // process arguments
347
for (int i = 0; i < argv.length; ++i) {
348             String JavaDoc arg = argv[i];
349             if (arg.startsWith("-")) {
350                 String JavaDoc option = arg.substring(1);
351                 if (option.equals("p")) {
352                     // get parser name
353
if (++i == argv.length) {
354                         System.err.println("error: Missing argument to -p option.");
355                     }
356                     String JavaDoc parserName = argv[i];
357                     
358                     // create parser
359
try {
360                         parser = XMLReaderFactory.createXMLReader(parserName);
361                     }
362                     catch (Exception JavaDoc e) {
363                         try {
364                             Parser JavaDoc sax1Parser = ParserFactory.makeParser(parserName);
365                             parser = new ParserAdapter JavaDoc(sax1Parser);
366                             System.err.println("warning: Features and properties not supported on SAX1 parsers.");
367                         }
368                         catch (Exception JavaDoc ex) {
369                             parser = null;
370                             System.err.println("error: Unable to instantiate parser ("+parserName+")");
371                             e.printStackTrace(System.err);
372                             System.exit(1);
373                         }
374                     }
375                     continue;
376                 }
377                 if (arg.equals("-a")) {
378                     // process -a: schema documents
379
if (schemas == null) {
380                         schemas = new Vector JavaDoc();
381                     }
382                     while (i + 1 < argv.length && !(arg = argv[i + 1]).startsWith("-")) {
383                         schemas.add(arg);
384                         ++i;
385                     }
386                     continue;
387                 }
388                 if (arg.equals("-i")) {
389                     // process -i: instance documents
390
if (instances == null) {
391                         instances = new Vector JavaDoc();
392                     }
393                     while (i + 1 < argv.length && !(arg = argv[i + 1]).startsWith("-")) {
394                         instances.add(arg);
395                         ++i;
396                     }
397                     continue;
398                 }
399                 if (option.equalsIgnoreCase("f")) {
400                     schemaFullChecking = option.equals("f");
401                     continue;
402                 }
403                 if (option.equalsIgnoreCase("hs")) {
404                     honourAllSchemaLocations = option.equals("hs");
405                     continue;
406                 }
407                 if (option.equalsIgnoreCase("va")) {
408                     validateAnnotations = option.equals("va");
409                     continue;
410                 }
411                 if (option.equalsIgnoreCase("ga")) {
412                     generateSyntheticAnnotations = option.equals("ga");
413                     continue;
414                 }
415                 if (option.equals("h")) {
416                     printUsage();
417                     continue;
418                 }
419                 System.err.println("error: unknown option ("+option+").");
420                 continue;
421             }
422         }
423         
424         // use default parser?
425
if (parser == null) {
426             // create parser
427
try {
428                 parser = XMLReaderFactory.createXMLReader(DEFAULT_PARSER_NAME);
429             }
430             catch (Exception JavaDoc e) {
431                 System.err.println("error: Unable to instantiate parser ("+DEFAULT_PARSER_NAME+")");
432                 e.printStackTrace(System.err);
433                 System.exit(1);
434             }
435         }
436         
437         try {
438             // Create writer
439
TypeInfoWriter writer = new TypeInfoWriter();
440             writer.setOutput(System.out, "UTF8");
441             
442             // Create SchemaFactory and configure
443
SchemaFactory JavaDoc factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
444             factory.setErrorHandler(writer);
445             
446             try {
447                 factory.setFeature(SCHEMA_FULL_CHECKING_FEATURE_ID, schemaFullChecking);
448             }
449             catch (SAXNotRecognizedException JavaDoc e) {
450                 System.err.println("warning: SchemaFactory does not recognize feature ("+SCHEMA_FULL_CHECKING_FEATURE_ID+")");
451             }
452             catch (SAXNotSupportedException JavaDoc e) {
453                 System.err.println("warning: SchemaFactory does not support feature ("+SCHEMA_FULL_CHECKING_FEATURE_ID+")");
454             }
455             try {
456                 factory.setFeature(HONOUR_ALL_SCHEMA_LOCATIONS_ID, honourAllSchemaLocations);
457             }
458             catch (SAXNotRecognizedException JavaDoc e) {
459                 System.err.println("warning: SchemaFactory does not recognize feature ("+HONOUR_ALL_SCHEMA_LOCATIONS_ID+")");
460             }
461             catch (SAXNotSupportedException JavaDoc e) {
462                 System.err.println("warning: SchemaFactory does not support feature ("+HONOUR_ALL_SCHEMA_LOCATIONS_ID+")");
463             }
464             try {
465                 factory.setFeature(VALIDATE_ANNOTATIONS_ID, validateAnnotations);
466             }
467             catch (SAXNotRecognizedException JavaDoc e) {
468                 System.err.println("warning: SchemaFactory does not recognize feature ("+VALIDATE_ANNOTATIONS_ID+")");
469             }
470             catch (SAXNotSupportedException JavaDoc e) {
471                 System.err.println("warning: SchemaFactory does not support feature ("+VALIDATE_ANNOTATIONS_ID+")");
472             }
473             try {
474                 factory.setFeature(GENERATE_SYNTHETIC_ANNOTATIONS_ID, generateSyntheticAnnotations);
475             }
476             catch (SAXNotRecognizedException JavaDoc e) {
477                 System.err.println("warning: SchemaFactory does not recognize feature ("+GENERATE_SYNTHETIC_ANNOTATIONS_ID+")");
478             }
479             catch (SAXNotSupportedException JavaDoc e) {
480                 System.err.println("warning: SchemaFactory does not support feature ("+GENERATE_SYNTHETIC_ANNOTATIONS_ID+")");
481             }
482             
483             // Build Schema from sources
484
Schema JavaDoc schema;
485             if (schemas != null && schemas.size() > 0) {
486                 final int length = schemas.size();
487                 StreamSource JavaDoc[] sources = new StreamSource JavaDoc[length];
488                 for (int j = 0; j < length; ++j) {
489                     sources[j] = new StreamSource JavaDoc((String JavaDoc) schemas.elementAt(j));
490                 }
491                 schema = factory.newSchema(sources);
492             }
493             else {
494                 schema = factory.newSchema();
495             }
496             
497             // Setup validator and parser
498
ValidatorHandler JavaDoc validator = schema.newValidatorHandler();
499             parser.setContentHandler(validator);
500             if (validator instanceof DTDHandler JavaDoc) {
501                 parser.setDTDHandler((DTDHandler JavaDoc) validator);
502             }
503             parser.setErrorHandler(writer);
504             validator.setContentHandler(writer);
505             validator.setErrorHandler(writer);
506             writer.setTypeInfoProvider(validator.getTypeInfoProvider());
507             
508             try {
509                 validator.setFeature(SCHEMA_FULL_CHECKING_FEATURE_ID, schemaFullChecking);
510             }
511             catch (SAXNotRecognizedException JavaDoc e) {
512                 System.err.println("warning: Validator does not recognize feature ("+SCHEMA_FULL_CHECKING_FEATURE_ID+")");
513             }
514             catch (SAXNotSupportedException JavaDoc e) {
515                 System.err.println("warning: Validator does not support feature ("+SCHEMA_FULL_CHECKING_FEATURE_ID+")");
516             }
517             try {
518                 validator.setFeature(HONOUR_ALL_SCHEMA_LOCATIONS_ID, honourAllSchemaLocations);
519             }
520             catch (SAXNotRecognizedException JavaDoc e) {
521                 System.err.println("warning: Validator does not recognize feature ("+HONOUR_ALL_SCHEMA_LOCATIONS_ID+")");
522             }
523             catch (SAXNotSupportedException JavaDoc e) {
524                 System.err.println("warning: Validator does not support feature ("+HONOUR_ALL_SCHEMA_LOCATIONS_ID+")");
525             }
526             try {
527                 validator.setFeature(VALIDATE_ANNOTATIONS_ID, validateAnnotations);
528             }
529             catch (SAXNotRecognizedException JavaDoc e) {
530                 System.err.println("warning: Validator does not recognize feature ("+VALIDATE_ANNOTATIONS_ID+")");
531             }
532             catch (SAXNotSupportedException JavaDoc e) {
533                 System.err.println("warning: Validator does not support feature ("+VALIDATE_ANNOTATIONS_ID+")");
534             }
535             try {
536                 validator.setFeature(GENERATE_SYNTHETIC_ANNOTATIONS_ID, generateSyntheticAnnotations);
537             }
538             catch (SAXNotRecognizedException JavaDoc e) {
539                 System.err.println("warning: Validator does not recognize feature ("+GENERATE_SYNTHETIC_ANNOTATIONS_ID+")");
540             }
541             catch (SAXNotSupportedException JavaDoc e) {
542                 System.err.println("warning: Validator does not support feature ("+GENERATE_SYNTHETIC_ANNOTATIONS_ID+")");
543             }
544             
545             // Validate instance documents and print type information
546
if (instances != null && instances.size() > 0) {
547                 final int length = instances.size();
548                 for (int j = 0; j < length; ++j) {
549                     parser.parse((String JavaDoc) instances.elementAt(j));
550                 }
551             }
552         }
553         catch (SAXParseException JavaDoc e) {
554             // ignore
555
}
556         catch (Exception JavaDoc e) {
557             System.err.println("error: Parse error occurred - "+e.getMessage());
558             if (e instanceof SAXException JavaDoc) {
559                 Exception JavaDoc nested = ((SAXException JavaDoc)e).getException();
560                 if (nested != null) {
561                     e = nested;
562                 }
563             }
564             e.printStackTrace(System.err);
565         }
566     } // main(String[])
567

568     //
569
// Private static methods
570
//
571

572     /** Prints the usage. */
573     private static void printUsage() {
574         
575         System.err.println("usage: java jaxp.TypeInfoWriter (options) ...");
576         System.err.println();
577         
578         System.err.println("options:");
579         System.err.println(" -a uri ... Provide a list of schema documents");
580         System.err.println(" -i uri ... Provide a list of instance documents to validate");
581         System.err.println(" -p name Select parser by name.");
582         System.err.println(" -f | -F Turn on/off Schema full checking.");
583         System.err.println(" NOTE: Not supported by all schema factories and validators.");
584         System.err.println(" -hs | -HS Turn on/off honouring of all schema locations.");
585         System.err.println(" NOTE: Not supported by all schema factories and validators.");
586         System.err.println(" -va | -VA Turn on/off validation of schema annotations.");
587         System.err.println(" NOTE: Not supported by all schema factories and validators.");
588         System.err.println(" -ga | -GA Turn on/off generation of synthetic schema annotations.");
589         System.err.println(" NOTE: Not supported by all schema factories and validators.");
590         System.err.println(" -h This help screen.");
591         
592         System.err.println();
593         System.err.println("defaults:");
594         System.err.println(" Parser: "+DEFAULT_PARSER_NAME);
595         System.err.print(" Schema full checking: ");
596         System.err.println(DEFAULT_SCHEMA_FULL_CHECKING ? "on" : "off");
597         System.err.print(" Honour all schema locations: ");
598         System.err.println(DEFAULT_HONOUR_ALL_SCHEMA_LOCATIONS ? "on" : "off");
599         System.err.print(" Validate annotations: ");
600         System.err.println(DEFAULT_VALIDATE_ANNOTATIONS ? "on" : "off");
601         System.err.print(" Generate synthetic annotations: ");
602         System.err.println(DEFAULT_GENERATE_SYNTHETIC_ANNOTATIONS ? "on" : "off");
603         
604     } // printUsage()
605

606 } // class TypeInfoWriter
607
Popular Tags