KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > SchemaValidatorHandlerExample


1
2 import org.w3c.dom.TypeInfo JavaDoc;
3 import org.w3c.dom.ls.LSInput JavaDoc;
4 import org.w3c.dom.ls.LSResourceResolver JavaDoc;
5 import org.xml.sax.*;
6 import org.xml.sax.helpers.DefaultHandler JavaDoc;
7
8 import javax.xml.parsers.SAXParser JavaDoc;
9 import javax.xml.parsers.SAXParserFactory JavaDoc;
10 import javax.xml.validation.Schema JavaDoc;
11 import javax.xml.validation.SchemaFactory JavaDoc;
12 import javax.xml.validation.TypeInfoProvider JavaDoc;
13 import javax.xml.validation.ValidatorHandler JavaDoc;
14 import java.io.File JavaDoc;
15
16 /**
17  * SchemaValidatorHandlerExample demonstrates the use of jaxp validation apis.
18  *
19  * This version was modified by Michael Kay from the sample application named SchemaValidator
20  * issued with the JAXP 1.3 distribution. It has been changed to use a ValidatorHandler
21  * and to display the types of elements and attributes as reported.
22  *
23  * The original file contained no explicit terms and conditions or copyright statement,
24  * but it should be assumed that it is subject to the usual Apache rules.
25  */

26
27 public class SchemaValidatorHandlerExample {
28
29     /**
30      * Class is never instantiated
31      */

32     private SchemaValidatorHandlerExample() {}
33
34     /**
35      * A custom SAX error handler
36      */

37
38     protected static class LocalErrorHandler implements ErrorHandler {
39
40         /**
41          * Report a non-fatal error
42          * @param ex the error condition
43          */

44         public void error(SAXParseException ex) {
45             System.err.println("At line " + ex.getLineNumber() + " of " + ex.getSystemId() + ':');
46             System.err.println(ex.getMessage());
47         }
48
49         /**
50          * Report a fatal error
51          * @param ex the error condition
52          */

53
54         public void fatalError(SAXParseException ex) {
55             System.err.println("At line " + ex.getLineNumber() + " of " + ex.getSystemId() + ':');
56             System.err.println(ex.getMessage());
57         }
58
59         /**
60          * Report a warning
61          * @param ex the warning condition
62          */

63         public void warning(SAXParseException ex) {
64             System.err.println("At line " + ex.getLineNumber() + " of " + ex.getSystemId() + ':');
65             System.err.println(ex.getMessage());
66         }
67
68     }
69
70     /**
71      * Inner class to implement a resource resolver. This version always returns null, which
72      * has the same effect as not supplying a resource resolver at all. The LSResourceResolver
73      * is part of the DOM Level 3 load/save module.
74      */

75
76     protected static class Resolver implements LSResourceResolver JavaDoc{
77
78         /**
79          * Resolve a reference to a resource
80          * @param type The type of resource, for example a schema, source XML document, or query
81          * @param namespace The target namespace (in the case of a schema document)
82          * @param publicId The public ID
83          * @param systemId The system identifier (as written, possibly a relative URI)
84          * @param baseURI The base URI against which the system identifier should be resolved
85          * @return an LSInput object typically containing the character stream or byte stream identified
86          * by the supplied parameters; or null if the reference cannot be resolved or if the resolver chooses
87          * not to resolve it.
88          */

89
90         public LSInput JavaDoc resolveResource(String JavaDoc type, String JavaDoc namespace, String JavaDoc publicId, String JavaDoc systemId, String JavaDoc baseURI) {
91             return null;
92         }
93
94     }
95
96     /**
97      * A ContentHandler to receive and display the results
98      */

99
100     public static class LocalContentHandler extends DefaultHandler JavaDoc {
101
102         int indent = 0;
103         private TypeInfoProvider JavaDoc provider;
104
105         public LocalContentHandler(TypeInfoProvider JavaDoc provider) {
106             this.provider = provider;
107         }
108
109         /**
110          * Receive notification of the start of an element.
111          */

112         public void startElement(String JavaDoc uri, String JavaDoc localName, String JavaDoc qName, Attributes attributes) throws SAXException {
113             TypeInfo JavaDoc etype = provider.getElementTypeInfo();
114             StringBuffer JavaDoc sb = new StringBuffer JavaDoc(100);
115             for (int i=0; i<indent; i++) {
116                 sb.append(" ");
117             }
118             sb.append("Element " + qName);
119             sb.append(" of type {" + etype.getTypeNamespace() + '}' + etype.getTypeName());
120             System.out.println(sb.toString());
121             for (int a=0; a<attributes.getLength(); a++) {
122                 TypeInfo JavaDoc atype = provider.getAttributeTypeInfo(a);
123                 boolean spec = provider.isSpecified(a);
124                 sb.setLength(0);
125                 for (int i=0; i<indent+2; i++) {
126                     sb.append(" ");
127                 }
128                 sb.append("Attribute " + attributes.getQName(a) + (spec ? " (specified)" : (" (defaulted)")));
129                 sb.append(" of type {" + atype.getTypeNamespace() + '}' + atype.getTypeName());
130                 System.out.println(sb.toString());
131             }
132             indent++;
133         }
134
135         /**
136          * Receive notification of the end of an element.
137          */

138         public void endElement(String JavaDoc uri, String JavaDoc localName, String JavaDoc qName) throws SAXException {
139             indent--;
140         }
141     }
142
143     /**
144      * Main entry point. Expects two arguments: the schema document, and the source document.
145      * @param args
146      */

147     public static void main(String JavaDoc [] args) {
148         try {
149             if(args.length != 2){
150                 printUsage();
151                 return;
152             }
153
154             SchemaFactory JavaDoc schemaFactory;
155
156             // Set a system property to force selection of the Saxon SchemaFactory implementation
157
// This is commented out because it shouldn't be necessary if Saxon-SA is on the classpath;
158
// but in the event of configuration problems, try reinstating it.
159

160 // System.setProperty("javax.xml.validation.SchemaFactory:http://www.w3.org/2001/XMLSchema",
161
// "com.saxonica.schema.SchemaFactoryImpl");
162

163             schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
164             System.err.println("Loaded schema validation provider " + schemaFactory.getClass().getName());
165
166             schemaFactory.setErrorHandler(new LocalErrorHandler());
167             //create a grammar object.
168
Schema JavaDoc schemaGrammar = schemaFactory.newSchema(new File JavaDoc(args[0]));
169
170             System.err.println("Created Grammar object for schema : "+args[0]);
171
172             Resolver JavaDoc resolver = new Resolver JavaDoc();
173
174             //create a validator to validate against the schema.
175
ValidatorHandler JavaDoc schemaValidator = schemaGrammar.newValidatorHandler();
176             schemaValidator.setResourceResolver(resolver);
177             schemaValidator.setErrorHandler(new LocalErrorHandler());
178             schemaValidator.setContentHandler(new LocalContentHandler(schemaValidator.getTypeInfoProvider()));
179
180             System.err.println("Validating "+args[1] +" against grammar "+args[0]);
181             SAXParserFactory JavaDoc parserFactory = SAXParserFactory.newInstance();
182             parserFactory.setNamespaceAware(true);
183             SAXParser JavaDoc parser = parserFactory.newSAXParser();
184             XMLReader reader = parser.getXMLReader();
185             reader.setContentHandler(schemaValidator);
186             reader.parse(new InputSource(new File JavaDoc(args[1]).toURI().toString()));
187
188             System.err.println("Validation successful");
189         } catch (SAXException saxe) {
190             exit(1, "Error: " + saxe.getMessage());
191         } catch (Exception JavaDoc e) {
192             e.printStackTrace();
193             exit(2, "Fatal Error: " + e);
194         }
195     }
196
197     /**
198      *
199      * @param errCode
200      * @param msg
201      */

202     public static void exit(int errCode, String JavaDoc msg) {
203         System.err.println(msg);
204         System.exit(errCode);
205     }
206
207     public static void printUsage(){
208         System.err.println("Usage : java SchemaValidatorHandlerExample <schemaFile> <xmlFile>");
209     }
210 }
211
Popular Tags