KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > jaxp > SourceValidator


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.PrintWriter JavaDoc;
20 import java.util.Vector JavaDoc;
21
22 import javax.xml.XMLConstants JavaDoc;
23 import javax.xml.parsers.DocumentBuilder JavaDoc;
24 import javax.xml.parsers.DocumentBuilderFactory JavaDoc;
25 import javax.xml.transform.Source JavaDoc;
26 import javax.xml.transform.dom.DOMSource JavaDoc;
27 import javax.xml.transform.sax.SAXSource JavaDoc;
28 import javax.xml.transform.stream.StreamSource JavaDoc;
29 import javax.xml.validation.Schema JavaDoc;
30 import javax.xml.validation.SchemaFactory JavaDoc;
31 import javax.xml.validation.Validator JavaDoc;
32
33 import org.w3c.dom.Document JavaDoc;
34 import org.xml.sax.ErrorHandler JavaDoc;
35 import org.xml.sax.InputSource JavaDoc;
36 import org.xml.sax.SAXException JavaDoc;
37 import org.xml.sax.SAXNotRecognizedException JavaDoc;
38 import org.xml.sax.SAXNotSupportedException JavaDoc;
39 import org.xml.sax.SAXParseException JavaDoc;
40 import org.xml.sax.XMLReader JavaDoc;
41 import org.xml.sax.helpers.XMLReaderFactory JavaDoc;
42
43 /**
44  * <p>A sample demonstrating how to use the JAXP 1.3 Validation API
45  * to create a validator and use the validator to validate input
46  * from SAX, DOM or a stream. The output of this program shows the
47  * time spent executing the Validator.validate(Source) method.</p>
48  *
49  * <p>This class is useful as a "poor-man's" performance tester to
50  * compare the speed of various JAXP 1.3 validators with different
51  * input sources. However, it is important to note that the first
52  * validation time of a validator will include both VM class load time
53  * and validator initialization that would not be present in subsequent
54  * validations with the same document. Also note that when the source for
55  * validation is SAX or a stream, the validation time will also include
56  * the time to parse the document, whereas the DOM validation is
57  * completely in memory.</p>
58  *
59  * <p><strong>Note:</strong> The results produced by this program
60  * should never be accepted as true performance measurements.</p>
61  *
62  * @author Michael Glavassevich, IBM
63  *
64  * @version $Id: SourceValidator.java,v 1.1 2005/06/01 04:48:36 mrglavas Exp $
65  */

66 public class SourceValidator
67     implements ErrorHandler JavaDoc {
68     
69     //
70
// Constants
71
//
72

73     // feature ids
74

75     /** Schema full checking feature id (http://apache.org/xml/features/validation/schema-full-checking). */
76     protected static final String JavaDoc SCHEMA_FULL_CHECKING_FEATURE_ID = "http://apache.org/xml/features/validation/schema-full-checking";
77     
78     /** Honour all schema locations feature id (http://apache.org/xml/features/honour-all-schemaLocations). */
79     protected static final String JavaDoc HONOUR_ALL_SCHEMA_LOCATIONS_ID = "http://apache.org/xml/features/honour-all-schemaLocations";
80     
81     /** Validate schema annotations feature id (http://apache.org/xml/features/validate-annotations) */
82     protected static final String JavaDoc VALIDATE_ANNOTATIONS_ID = "http://apache.org/xml/features/validate-annotations";
83     
84     /** Generate synthetic schema annotations feature id (http://apache.org/xml/features/generate-synthetic-annotations). */
85     protected static final String JavaDoc GENERATE_SYNTHETIC_ANNOTATIONS_ID = "http://apache.org/xml/features/generate-synthetic-annotations";
86     
87     // default settings
88

89     /** Default repetition (1). */
90     protected static final int DEFAULT_REPETITION = 1;
91     
92     /** Default validation source. */
93     protected static final String JavaDoc DEFAULT_VALIDATION_SOURCE = "sax";
94     
95     /** Default schema full checking support (false). */
96     protected static final boolean DEFAULT_SCHEMA_FULL_CHECKING = false;
97     
98     /** Default honour all schema locations (false). */
99     protected static final boolean DEFAULT_HONOUR_ALL_SCHEMA_LOCATIONS = false;
100     
101     /** Default validate schema annotations (false). */
102     protected static final boolean DEFAULT_VALIDATE_ANNOTATIONS = false;
103     
104     /** Default generate synthetic schema annotations (false). */
105     protected static final boolean DEFAULT_GENERATE_SYNTHETIC_ANNOTATIONS = false;
106     
107     /** Default memory usage report (false). */
108     protected static final boolean DEFAULT_MEMORY_USAGE = false;
109     
110     //
111
// Data
112
//
113

114     protected PrintWriter JavaDoc fOut = new PrintWriter JavaDoc(System.out);
115
116     //
117
// Constructors
118
//
119

120     /** Default constructor. */
121     public SourceValidator() {
122     } // <init>()
123

124     //
125
// Public methods
126
//
127

128     public void validate(Validator JavaDoc validator,
129             Source JavaDoc source, String JavaDoc systemId,
130             int repetitions, boolean memoryUsage) {
131         try {
132             long timeBefore = System.currentTimeMillis();
133             long memoryBefore = Runtime.getRuntime().freeMemory();
134             for (int j = 0; j < repetitions; ++j) {
135                 validator.validate(source);
136             }
137             long memoryAfter = Runtime.getRuntime().freeMemory();
138             long timeAfter = System.currentTimeMillis();
139
140             long time = timeAfter - timeBefore;
141             long memory = memoryUsage
142                         ? memoryBefore - memoryAfter : Long.MIN_VALUE;
143             printResults(fOut, systemId, time, memory, repetitions);
144         }
145         catch (SAXParseException JavaDoc e) {
146             // ignore
147
}
148         catch (Exception JavaDoc e) {
149             System.err.println("error: Parse error occurred - "+e.getMessage());
150             Exception JavaDoc se = e;
151             if (e instanceof SAXException JavaDoc) {
152                 se = ((SAXException JavaDoc)e).getException();
153             }
154             if (se != null)
155               se.printStackTrace(System.err);
156             else
157               e.printStackTrace(System.err);
158
159         }
160     } // validate(Validator,Source,String,int,boolean)
161

162     /** Prints the results. */
163     public void printResults(PrintWriter JavaDoc out, String JavaDoc uri, long time,
164                              long memory, int repetition) {
165         
166         // filename.xml: 631 ms
167
out.print(uri);
168         out.print(": ");
169         if (repetition == 1) {
170             out.print(time);
171         }
172         else {
173             out.print(time);
174             out.print('/');
175             out.print(repetition);
176             out.print('=');
177             out.print(((float)time)/repetition);
178         }
179         out.print(" ms");
180         if (memory != Long.MIN_VALUE) {
181             out.print(", ");
182             out.print(memory);
183             out.print(" bytes");
184         }
185         out.println();
186         out.flush();
187
188     } // printResults(PrintWriter,String,long,long,int)
189

190     //
191
// ErrorHandler methods
192
//
193

194     /** Warning. */
195     public void warning(SAXParseException JavaDoc ex) throws SAXException JavaDoc {
196         printError("Warning", ex);
197     } // warning(SAXParseException)
198

199     /** Error. */
200     public void error(SAXParseException JavaDoc ex) throws SAXException JavaDoc {
201         printError("Error", ex);
202     } // error(SAXParseException)
203

204     /** Fatal error. */
205     public void fatalError(SAXParseException JavaDoc ex) throws SAXException JavaDoc {
206         printError("Fatal Error", ex);
207         throw ex;
208     } // fatalError(SAXParseException)
209

210     //
211
// Protected methods
212
//
213

214     /** Prints the error message. */
215     protected void printError(String JavaDoc type, SAXParseException JavaDoc ex) {
216
217         System.err.print("[");
218         System.err.print(type);
219         System.err.print("] ");
220         String JavaDoc systemId = ex.getSystemId();
221         if (systemId != null) {
222             int index = systemId.lastIndexOf('/');
223             if (index != -1)
224                 systemId = systemId.substring(index + 1);
225             System.err.print(systemId);
226         }
227         System.err.print(':');
228         System.err.print(ex.getLineNumber());
229         System.err.print(':');
230         System.err.print(ex.getColumnNumber());
231         System.err.print(": ");
232         System.err.print(ex.getMessage());
233         System.err.println();
234         System.err.flush();
235
236     } // printError(String,SAXParseException)
237

238     //
239
// MAIN
240
//
241

242     /** Main program entry point. */
243     public static void main (String JavaDoc [] argv) {
244         
245         // is there anything to do?
246
if (argv.length == 0) {
247             printUsage();
248             System.exit(1);
249         }
250         
251         // variables
252
Vector JavaDoc schemas = null;
253         Vector JavaDoc instances = null;
254         int repetition = DEFAULT_REPETITION;
255         String JavaDoc validationSource = DEFAULT_VALIDATION_SOURCE;
256         boolean schemaFullChecking = DEFAULT_SCHEMA_FULL_CHECKING;
257         boolean honourAllSchemaLocations = DEFAULT_HONOUR_ALL_SCHEMA_LOCATIONS;
258         boolean validateAnnotations = DEFAULT_VALIDATE_ANNOTATIONS;
259         boolean generateSyntheticAnnotations = DEFAULT_GENERATE_SYNTHETIC_ANNOTATIONS;
260         boolean memoryUsage = DEFAULT_MEMORY_USAGE;
261         
262         // process arguments
263
for (int i = 0; i < argv.length; ++i) {
264             String JavaDoc arg = argv[i];
265             if (arg.startsWith("-")) {
266                 String JavaDoc option = arg.substring(1);
267                 if (option.equals("x")) {
268                     if (++i == argv.length) {
269                         System.err.println("error: Missing argument to -x option.");
270                         continue;
271                     }
272                     String JavaDoc number = argv[i];
273                     try {
274                         int value = Integer.parseInt(number);
275                         if (value < 1) {
276                             System.err.println("error: Repetition must be at least 1.");
277                             continue;
278                         }
279                         repetition = value;
280                     }
281                     catch (NumberFormatException JavaDoc e) {
282                         System.err.println("error: invalid number ("+number+").");
283                     }
284                     continue;
285                 }
286                 if (arg.equals("-a")) {
287                     // process -a: schema documents
288
if (schemas == null) {
289                         schemas = new Vector JavaDoc();
290                     }
291                     while (i + 1 < argv.length && !(arg = argv[i + 1]).startsWith("-")) {
292                         schemas.add(arg);
293                         ++i;
294                     }
295                     continue;
296                 }
297                 if (arg.equals("-i")) {
298                     // process -i: instance documents
299
if (instances == null) {
300                         instances = new Vector JavaDoc();
301                     }
302                     while (i + 1 < argv.length && !(arg = argv[i + 1]).startsWith("-")) {
303                         instances.add(arg);
304                         ++i;
305                     }
306                     continue;
307                 }
308                 if (arg.equals("-vs")) {
309                     if (i + 1 < argv.length && !(arg = argv[i + 1]).startsWith("-")) {
310                         if (arg.equals("sax") || arg.equals("dom") || arg.equals("stream")) {
311                             validationSource = arg;
312                         }
313                         else {
314                             System.err.println("error: unknown source type ("+arg+").");
315                         }
316                     }
317                     continue;
318                 }
319                 if (option.equalsIgnoreCase("f")) {
320                     schemaFullChecking = option.equals("f");
321                     continue;
322                 }
323                 if (option.equalsIgnoreCase("hs")) {
324                     honourAllSchemaLocations = option.equals("hs");
325                     continue;
326                 }
327                 if (option.equalsIgnoreCase("va")) {
328                     validateAnnotations = option.equals("va");
329                     continue;
330                 }
331                 if (option.equalsIgnoreCase("ga")) {
332                     generateSyntheticAnnotations = option.equals("ga");
333                     continue;
334                 }
335                 if (option.equalsIgnoreCase("m")) {
336                     memoryUsage = option.equals("m");
337                     continue;
338                 }
339                 if (option.equals("h")) {
340                     printUsage();
341                     continue;
342                 }
343                 System.err.println("error: unknown option ("+option+").");
344                 continue;
345             }
346         }
347         
348         try {
349             // Create new instance of SourceValidator.
350
SourceValidator sourceValidator = new SourceValidator();
351             
352             // Create SchemaFactory and configure
353
SchemaFactory JavaDoc factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
354             factory.setErrorHandler(sourceValidator);
355             
356             try {
357                 factory.setFeature(SCHEMA_FULL_CHECKING_FEATURE_ID, schemaFullChecking);
358             }
359             catch (SAXNotRecognizedException JavaDoc e) {
360                 System.err.println("warning: SchemaFactory does not recognize feature ("+SCHEMA_FULL_CHECKING_FEATURE_ID+")");
361             }
362             catch (SAXNotSupportedException JavaDoc e) {
363                 System.err.println("warning: SchemaFactory does not support feature ("+SCHEMA_FULL_CHECKING_FEATURE_ID+")");
364             }
365             try {
366                 factory.setFeature(HONOUR_ALL_SCHEMA_LOCATIONS_ID, honourAllSchemaLocations);
367             }
368             catch (SAXNotRecognizedException JavaDoc e) {
369                 System.err.println("warning: SchemaFactory does not recognize feature ("+HONOUR_ALL_SCHEMA_LOCATIONS_ID+")");
370             }
371             catch (SAXNotSupportedException JavaDoc e) {
372                 System.err.println("warning: SchemaFactory does not support feature ("+HONOUR_ALL_SCHEMA_LOCATIONS_ID+")");
373             }
374             try {
375                 factory.setFeature(VALIDATE_ANNOTATIONS_ID, validateAnnotations);
376             }
377             catch (SAXNotRecognizedException JavaDoc e) {
378                 System.err.println("warning: SchemaFactory does not recognize feature ("+VALIDATE_ANNOTATIONS_ID+")");
379             }
380             catch (SAXNotSupportedException JavaDoc e) {
381                 System.err.println("warning: SchemaFactory does not support feature ("+VALIDATE_ANNOTATIONS_ID+")");
382             }
383             try {
384                 factory.setFeature(GENERATE_SYNTHETIC_ANNOTATIONS_ID, generateSyntheticAnnotations);
385             }
386             catch (SAXNotRecognizedException JavaDoc e) {
387                 System.err.println("warning: SchemaFactory does not recognize feature ("+GENERATE_SYNTHETIC_ANNOTATIONS_ID+")");
388             }
389             catch (SAXNotSupportedException JavaDoc e) {
390                 System.err.println("warning: SchemaFactory does not support feature ("+GENERATE_SYNTHETIC_ANNOTATIONS_ID+")");
391             }
392             
393             // Build Schema from sources
394
Schema JavaDoc schema;
395             if (schemas != null && schemas.size() > 0) {
396                 final int length = schemas.size();
397                 StreamSource JavaDoc[] sources = new StreamSource JavaDoc[length];
398                 for (int j = 0; j < length; ++j) {
399                     sources[j] = new StreamSource JavaDoc((String JavaDoc) schemas.elementAt(j));
400                 }
401                 schema = factory.newSchema(sources);
402             }
403             else {
404                 schema = factory.newSchema();
405             }
406             
407             // Setup validator and input source.
408
Validator JavaDoc validator = schema.newValidator();
409             validator.setErrorHandler(sourceValidator);
410             
411             try {
412                 validator.setFeature(SCHEMA_FULL_CHECKING_FEATURE_ID, schemaFullChecking);
413             }
414             catch (SAXNotRecognizedException JavaDoc e) {
415                 System.err.println("warning: Validator does not recognize feature ("+SCHEMA_FULL_CHECKING_FEATURE_ID+")");
416             }
417             catch (SAXNotSupportedException JavaDoc e) {
418                 System.err.println("warning: Validator does not support feature ("+SCHEMA_FULL_CHECKING_FEATURE_ID+")");
419             }
420             try {
421                 validator.setFeature(HONOUR_ALL_SCHEMA_LOCATIONS_ID, honourAllSchemaLocations);
422             }
423             catch (SAXNotRecognizedException JavaDoc e) {
424                 System.err.println("warning: Validator does not recognize feature ("+HONOUR_ALL_SCHEMA_LOCATIONS_ID+")");
425             }
426             catch (SAXNotSupportedException JavaDoc e) {
427                 System.err.println("warning: Validator does not support feature ("+HONOUR_ALL_SCHEMA_LOCATIONS_ID+")");
428             }
429             try {
430                 validator.setFeature(VALIDATE_ANNOTATIONS_ID, validateAnnotations);
431             }
432             catch (SAXNotRecognizedException JavaDoc e) {
433                 System.err.println("warning: Validator does not recognize feature ("+VALIDATE_ANNOTATIONS_ID+")");
434             }
435             catch (SAXNotSupportedException JavaDoc e) {
436                 System.err.println("warning: Validator does not support feature ("+VALIDATE_ANNOTATIONS_ID+")");
437             }
438             try {
439                 validator.setFeature(GENERATE_SYNTHETIC_ANNOTATIONS_ID, generateSyntheticAnnotations);
440             }
441             catch (SAXNotRecognizedException JavaDoc e) {
442                 System.err.println("warning: Validator does not recognize feature ("+GENERATE_SYNTHETIC_ANNOTATIONS_ID+")");
443             }
444             catch (SAXNotSupportedException JavaDoc e) {
445                 System.err.println("warning: Validator does not support feature ("+GENERATE_SYNTHETIC_ANNOTATIONS_ID+")");
446             }
447
448             // Validate instance documents
449
if (instances != null && instances.size() > 0) {
450                 final int length = instances.size();
451                 if (validationSource.equals("sax")) {
452                     // SAXSource
453
XMLReader JavaDoc reader = XMLReaderFactory.createXMLReader();
454                     for (int j = 0; j < length; ++j) {
455                         String JavaDoc systemId = (String JavaDoc) instances.elementAt(j);
456                         SAXSource JavaDoc source = new SAXSource JavaDoc(reader, new InputSource JavaDoc(systemId));
457                         sourceValidator.validate(validator, source, systemId, repetition, memoryUsage);
458                     }
459                 }
460                 else if (validationSource.equals("dom")) {
461                     // DOMSource
462
DocumentBuilderFactory JavaDoc dbf = DocumentBuilderFactory.newInstance();
463                     dbf.setNamespaceAware(true);
464                     DocumentBuilder JavaDoc db = dbf.newDocumentBuilder();
465                     for (int j = 0; j < length; ++j) {
466                         String JavaDoc systemId = (String JavaDoc) instances.elementAt(j);
467                         Document JavaDoc doc = db.parse(systemId);
468                         DOMSource JavaDoc source = new DOMSource JavaDoc(doc);
469                         source.setSystemId(systemId);
470                         sourceValidator.validate(validator, source, systemId, repetition, memoryUsage);
471                     }
472                 }
473                 else {
474                     // StreamSource
475
for (int j = 0; j < length; ++j) {
476                         String JavaDoc systemId = (String JavaDoc) instances.elementAt(j);
477                         StreamSource JavaDoc source = new StreamSource JavaDoc(systemId);
478                         sourceValidator.validate(validator, source, systemId, repetition, memoryUsage);
479                     }
480                 }
481             }
482         }
483         catch (SAXParseException JavaDoc e) {
484             // ignore
485
}
486         catch (Exception JavaDoc e) {
487             System.err.println("error: Parse error occurred - "+e.getMessage());
488             if (e instanceof SAXException JavaDoc) {
489                 Exception JavaDoc nested = ((SAXException JavaDoc)e).getException();
490                 if (nested != null) {
491                     e = nested;
492                 }
493             }
494             e.printStackTrace(System.err);
495         }
496     } // main(String[])
497

498     //
499
// Private static methods
500
//
501

502     /** Prints the usage. */
503     private static void printUsage() {
504         
505         System.err.println("usage: java jaxp.SourceValidator (options) ...");
506         System.err.println();
507         
508         System.err.println("options:");
509         System.err.println(" -x number Select number of repetitions.");
510         System.err.println(" -a uri ... Provide a list of schema documents");
511         System.err.println(" -i uri ... Provide a list of instance documents to validate");
512         System.err.println(" -vs source Select validation source (sax|dom|stream)");
513         System.err.println(" -f | -F Turn on/off Schema full checking.");
514         System.err.println(" NOTE: Not supported by all schema factories and validators.");
515         System.err.println(" -hs | -HS Turn on/off honouring of all schema locations.");
516         System.err.println(" NOTE: Not supported by all schema factories and validators.");
517         System.err.println(" -va | -VA Turn on/off validation of schema annotations.");
518         System.err.println(" NOTE: Not supported by all schema factories and validators.");
519         System.err.println(" -ga | -GA Turn on/off generation of synthetic schema annotations.");
520         System.err.println(" NOTE: Not supported by all schema factories and validators.");
521         System.err.println(" -m | -M Turn on/off memory usage report");
522         System.err.println(" -h This help screen.");
523         
524         System.err.println();
525         System.err.println("defaults:");
526         System.err.println(" Repetition: " + DEFAULT_REPETITION);
527         System.err.println(" Validation source: " + DEFAULT_VALIDATION_SOURCE);
528         System.err.print(" Schema full checking: ");
529         System.err.println(DEFAULT_SCHEMA_FULL_CHECKING ? "on" : "off");
530         System.err.print(" Honour all schema locations: ");
531         System.err.println(DEFAULT_HONOUR_ALL_SCHEMA_LOCATIONS ? "on" : "off");
532         System.err.print(" Validate annotations: ");
533         System.err.println(DEFAULT_VALIDATE_ANNOTATIONS ? "on" : "off");
534         System.err.print(" Generate synthetic annotations: ");
535         System.err.println(DEFAULT_GENERATE_SYNTHETIC_ANNOTATIONS ? "on" : "off");
536         System.err.print(" Memory: ");
537         System.err.println(DEFAULT_MEMORY_USAGE ? "on" : "off");
538         
539         System.err.println();
540         System.err.println("notes:");
541         System.err.println(" The speed and memory results from this program should NOT be used as the");
542         System.err.println(" basis of parser performance comparison! Real analytical methods should be");
543         System.err.println(" used. For better results, perform multiple document validations within the");
544         System.err.println(" same virtual machine to remove class loading from parse time and memory usage.");
545         
546     } // printUsage()
547

548 } // class SourceValidator
549
Popular Tags