KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > thaiopensource > validate > ValidationDriver


1 package com.thaiopensource.validate;
2
3 import org.xml.sax.SAXException JavaDoc;
4 import org.xml.sax.InputSource JavaDoc;
5 import org.xml.sax.DTDHandler JavaDoc;
6 import org.xml.sax.XMLReader JavaDoc;
7 import org.xml.sax.ErrorHandler JavaDoc;
8
9 import java.io.IOException JavaDoc;
10 import java.io.File JavaDoc;
11 import java.net.MalformedURLException JavaDoc;
12
13 import com.thaiopensource.util.UriOrFile;
14 import com.thaiopensource.util.PropertyMap;
15 import com.thaiopensource.util.PropertyMapBuilder;
16 import com.thaiopensource.util.PropertyId;
17 import com.thaiopensource.xml.sax.XMLReaderCreator;
18 import com.thaiopensource.xml.sax.CountingErrorHandler;
19 import com.thaiopensource.xml.sax.Jaxp11XMLReaderCreator;
20 import com.thaiopensource.xml.sax.ErrorHandlerImpl;
21 import com.thaiopensource.validate.auto.AutoSchemaReader;
22
23 /**
24  * Provides a simplified API for validating XML documents against schemas.
25  * This class is neither reentrant nor safe for access from multiple threads.
26  *
27  * @author <a HREF="mailto:jjc@jclark.com">James Clark</a>
28  */

29
30 public class ValidationDriver {
31   private static final PropertyId[] requiredProperties = {
32     ValidateProperty.XML_READER_CREATOR,
33     ValidateProperty.ERROR_HANDLER
34   };
35
36   private static final Class JavaDoc[] defaultClasses = {
37     Jaxp11XMLReaderCreator.class,
38     ErrorHandlerImpl.class
39   };
40
41   private final XMLReaderCreator xrc;
42   private XMLReader JavaDoc xr;
43   private final CountingErrorHandler eh;
44   private final SchemaReader sr;
45   private final PropertyMap schemaProperties;
46   private final PropertyMap instanceProperties;
47   private Validator validator;
48   private Schema schema;
49
50   /**
51    * Creates and initializes a ValidationDriver.
52    *
53    * @param schemaProperties a PropertyMap specifying properties controlling schema creation;
54    * must not be <code>null</code>
55    * @param instanceProperties a PropertyMap specifying properties controlling validation;
56    * must not be <code>null</code>
57    * @param schemaReader the SchemaReader to use; if this is <code>null</code>, then the schema
58    * must be in XML, and the namespace URI of the root element will be used to determine what
59    * the schema language is
60    */

61   public ValidationDriver(PropertyMap schemaProperties,
62                           PropertyMap instanceProperties,
63                           SchemaReader schemaReader) {
64     PropertyMapBuilder builder = new PropertyMapBuilder(schemaProperties);
65     for (int i = 0; i < requiredProperties.length; i++) {
66       if (!builder.contains(requiredProperties[i])) {
67         try {
68           builder.put(requiredProperties[i],
69                       defaultClasses[i].newInstance());
70         }
71         catch (InstantiationException JavaDoc e) {
72         }
73         catch (IllegalAccessException JavaDoc e) {
74         }
75       }
76     }
77     this.schemaProperties = builder.toPropertyMap();
78     builder = new PropertyMapBuilder(instanceProperties);
79     for (int i = 0; i < requiredProperties.length; i++) {
80       if (!builder.contains(requiredProperties[i]))
81         builder.put(requiredProperties[i],
82                     this.schemaProperties.get(requiredProperties[i]));
83     }
84     eh = new CountingErrorHandler((ErrorHandler JavaDoc)builder.get(ValidateProperty.ERROR_HANDLER));
85     ValidateProperty.ERROR_HANDLER.put(builder, eh);
86     this.instanceProperties = builder.toPropertyMap();
87     this.xrc = ValidateProperty.XML_READER_CREATOR.get(this.instanceProperties);
88     this.sr = schemaReader == null ? new AutoSchemaReader() : schemaReader;
89   }
90
91   /**
92    * Equivalent to ValidationDriver(schemaProperties, instanceProperties, null).
93    *
94    * @see #ValidationDriver(PropertyMap,PropertyMap,SchemaReader)
95    */

96    public ValidationDriver(PropertyMap schemaProperties, PropertyMap instanceProperties) {
97      this(schemaProperties, instanceProperties, null);
98   }
99
100   /**
101    * Equivalent to ValidationDriver(properties, properties, sr).
102    *
103    * @see #ValidationDriver(PropertyMap,PropertyMap,SchemaReader)
104    */

105    public ValidationDriver(PropertyMap properties, SchemaReader sr) {
106     this(properties, properties, sr);
107   }
108
109   /**
110    * Equivalent to ValidationDriver(properties, properties, null).
111    *
112    * @see #ValidationDriver(PropertyMap,PropertyMap,SchemaReader)
113    */

114    public ValidationDriver(PropertyMap properties) {
115     this(properties, properties, null);
116   }
117
118   /**
119    * Equivalent to ValidationDriver(PropertyMap.EMPTY, PropertyMap.EMPTY, null).
120    *
121    * @see #ValidationDriver(PropertyMap,PropertyMap,SchemaReader)
122    */

123    public ValidationDriver(SchemaReader sr) {
124     this(PropertyMap.EMPTY, sr);
125   }
126
127   /**
128    * Equivalent to ValidationDriver(PropertyMap.EMPTY, PropertyMap.EMPTY, null).
129    *
130    * @see #ValidationDriver(PropertyMap,PropertyMap,SchemaReader)
131    */

132   public ValidationDriver() {
133     this(PropertyMap.EMPTY, PropertyMap.EMPTY, null);
134   }
135
136   /**
137    * Loads a schema. Subsequent calls to <code>validate</code> will validate with
138    * respect the loaded schema. This can be called more than once to allow
139    * multiple documents to be validated against different schemas.
140    *
141    * @param in the InputSource for the schema
142    * @return <code>true</code> if the schema was loaded successfully; <code>false</code> otherwise
143    * @throws IOException if an I/O error occurred
144    * @throws SAXException if an XMLReader or ErrorHandler threw a SAXException
145    */

146   public boolean loadSchema(InputSource JavaDoc in) throws SAXException JavaDoc, IOException JavaDoc {
147     try {
148       schema = sr.createSchema(in, schemaProperties);
149       validator = null;
150       return true;
151     }
152     catch (IncorrectSchemaException e) {
153       return false;
154     }
155   }
156
157   /**
158    * Validates a document against the currently loaded schema. This can be called
159    * multiple times in order to validate multiple documents.
160    *
161    * @param in the InputSource for the document to be validated
162    * @return <code>true</code> if the document is valid; <code>false</code> otherwise
163    * @throws java.lang.IllegalStateException if there is no currently loaded schema
164    * @throws java.io.IOException if an I/O error occurred
165    * @throws org.xml.sax.SAXException if an XMLReader or ErrorHandler threw a SAXException
166    */

167   public boolean validate(InputSource JavaDoc in) throws SAXException JavaDoc, IOException JavaDoc {
168     if (schema == null)
169       throw new IllegalStateException JavaDoc("cannot validate without schema");
170     if (validator == null)
171       validator = schema.createValidator(instanceProperties);
172     if (xr == null) {
173       xr = xrc.createXMLReader();
174       xr.setErrorHandler(eh);
175     }
176     eh.reset();
177     xr.setContentHandler(validator.getContentHandler());
178     DTDHandler JavaDoc dh = validator.getDTDHandler();
179     if (dh != null)
180       xr.setDTDHandler(dh);
181     try {
182       xr.parse(in);
183       return !eh.getHadErrorOrFatalError();
184     }
185     finally {
186       validator.reset();
187     }
188   }
189
190   /**
191    * Returns an <code>InputSource</code> for a filename.
192    *
193    * @param filename a String specifying the filename
194    * @return an <code>InputSource</code> for the filename
195    */

196   static public InputSource JavaDoc fileInputSource(String JavaDoc filename) throws MalformedURLException JavaDoc {
197     return ValidationDriver.fileInputSource(new File JavaDoc(filename));
198   }
199
200   /**
201    * Returns an <code>InputSource</code> for a <code>File</code>.
202    *
203    * @param file the <code>File</code>
204    * @return an <code>InputSource</code> for the filename
205    */

206   static public InputSource JavaDoc fileInputSource(File JavaDoc file) throws MalformedURLException JavaDoc {
207     return new InputSource JavaDoc(UriOrFile.fileToUri(file));
208   }
209
210   /**
211    * Returns an <code>InputSource</code> for a string that represents either a file
212    * or an absolute URI. If the string looks like an absolute URI, it will be
213    * treated as an absolute URI, otherwise it will be treated as a filename.
214    *
215    * @param uriOrFile a <code>String</code> representing either a file or an absolute URI
216    * @return an <code>InputSource</code> for the file or absolute URI
217    */

218   static public InputSource JavaDoc uriOrFileInputSource(String JavaDoc uriOrFile) throws MalformedURLException JavaDoc {
219     return new InputSource JavaDoc(UriOrFile.toUri(uriOrFile));
220   }
221 }
222
Popular Tags