1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package aigames.soccer.application;
21
22 import com.sun.msv.verifier.jarv.TheFactoryImpl;
23
24 import org.apache.log4j.Logger;
25
26 import org.dom4j.Document;
27
28 import org.dom4j.io.SAXWriter;
29
30 import org.iso_relax.verifier.Schema;
31 import org.iso_relax.verifier.Verifier;
32 import org.iso_relax.verifier.VerifierConfigurationException;
33 import org.iso_relax.verifier.VerifierFactory;
34 import org.iso_relax.verifier.VerifierHandler;
35
36 import org.xml.sax.ErrorHandler;
37 import org.xml.sax.SAXException;
38 import org.xml.sax.SAXParseException;
39
40 import java.io.FileInputStream;
41 import java.io.IOException;
42 import java.io.InputStream;
43
44
45 /***
46 * @version $Id: Validator.java,v 1.3 2004/05/08 21:55:27 mwerla Exp $
47 */
48 public class Validator {
49 private static Logger logger = Logger.getLogger(Validator.class);
50 private Verifier verifier;
51 private String status = "";
52
53 /***
54 * Validator constructor.
55 * @param schemaFileName path to the schema file
56 * @throws VerifierConfigurationException Thrown on verifier configuration error.
57 * @throws SAXException Thrown if schema is invalid.
58 * @throws IOException Thrown if schema is not found.
59 */
60 public Validator(String schemaFileName)
61 throws VerifierConfigurationException, SAXException, IOException {
62 InputStream schemaStream = null;
63
64 try {
65 schemaStream = new FileInputStream(schemaFileName);
66 } catch (IOException e) {
67 logger.error(e.getMessage(), e);
68 }
69
70
71 VerifierFactory factory = new TheFactoryImpl();
72 Schema schema = factory.compileSchema(schemaStream);
73 verifier = schema.newVerifier();
74
75
76 verifier.setErrorHandler(new ErrorHandler() {
77 public void error(SAXParseException e) {
78 status = e.getMessage();
79 logger.error("Error during validation: " + status);
80 }
81
82 public void fatalError(SAXParseException e) {
83 logger.fatal("Fatal error during validation.", e);
84 }
85
86 public void warning(SAXParseException e) {
87 logger.warn(e.getMessage());
88 }
89 });
90 logger.info("Validator created " + this);
91 }
92
93 /***
94 * Message validation.
95 * @param message
96 * @return true if message is valid
97 * @throws Exception Thrown when validation fails.
98 */
99 public boolean validate(Document message) throws Exception {
100 logger.info("Validating message.");
101
102 VerifierHandler handler = verifier.getVerifierHandler();
103 SAXWriter writer = new SAXWriter(handler);
104 writer.write(message);
105
106 return handler.isValid();
107 }
108
109 /***
110 * Get validation status.
111 * @return status
112 */
113 public String getStatus() {
114 return status;
115 }
116 }