dol: initial dol commit
[jump.git] / dol / src / dol / helper / validator / XMLValidator.java
1 /* $Id: XMLValidator.java 1 2010-02-24 13:03:05Z haidw $ */
2 package dol.helper.validator;
3
4 import java.io.IOException;
5
6 import org.jdom.JDOMException;
7 import org.jdom.input.SAXBuilder;
8
9 /**
10  * Class to check well-formedness and validity of XML documents.
11  */
12 public class XMLValidator {
13
14     /**
15      * Check the well-formedness and validity of an XML document.
16      * The file is checked against the schema which is referenced from
17      * within the file. When the document is an XML schema, it is checked
18      * against <a href="http://www.w3.org/2001/XMLSchema.xsd"
19      * target="_blank">http://www.w3.org/2001/XMLSchema.xsd</a>.
20      *
21      * @param filename filename of the file to be checked
22      */
23     public static boolean isValid(String filename) {
24         SAXBuilder builder = new SAXBuilder(true);
25         builder.setFeature("http://xml.org/sax/features/validation",
26                 true);
27         builder.setFeature("http://apache.org/xml/features/validation/"
28                 + "schema", true);
29         builder.setFeature("http://apache.org/xml/features/validation/"
30                 + "schema-full-checking", true);
31         builder.setProperty("http://apache.org/xml/properties/schema/"
32                 + "external-schemaLocation",
33                 "http://www.w3.org/2001/XMLSchema "
34                 + "http://www.w3.org/2001/XMLSchema.xsd "
35                 + dol.util.SchemaLocation.getExternalSchemaLocation());
36         try {
37             builder.build(filename);
38         }
39         catch (JDOMException e) {
40             System.out.println("Found an error in " + filename + ".");
41             System.out.println(e.getMessage());
42             System.out.println("");
43             return false;
44         }
45         catch (IOException e) {
46             System.out.println("Found an error in " + filename + ".");
47             System.out.println(e.getMessage());
48             System.out.println("");
49             return false;
50         }
51
52         return true;
53     }
54
55     /**
56      * Main function. We might extend the validator to validate different
57      * kind of XMLs based on different schemas.
58      *
59      * @param args The command line argument.
60      */
61     public static void main(String[] args) {
62
63         /* Check command line parameters */
64         /* maybe add options to check both external/internal schema */
65         if (args.length != 1) {
66             System.out.println("Usage: XMLValidator <file>");
67             System.out.println();
68             return;
69         }
70
71         if (XMLValidator.isValid(args[0])){
72             System.out.println(args[0] + " is valid.");
73         } else {
74             System.exit(1);
75         }
76     }
77 }