1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.springframework.xml.validation;
18
19 import java.io.IOException;
20 import java.util.ArrayList;
21 import java.util.List;
22 import javax.xml.transform.Source;
23 import javax.xml.validation.Schema;
24 import javax.xml.validation.Validator;
25
26 import org.springframework.core.io.Resource;
27
28 import org.xml.sax.SAXException;
29 import org.xml.sax.SAXParseException;
30
31
32
33
34
35
36
37 abstract class Jaxp13ValidatorFactory {
38
39 static XmlValidator createValidator(Resource[] resources, String schemaLanguage) throws IOException {
40 try {
41 Schema schema = SchemaLoaderUtils.loadSchema(resources, schemaLanguage);
42 return new Jaxp13Validator(schema);
43 }
44 catch (SAXException ex) {
45 throw new XmlValidationException("Could not create Schema: " + ex.getMessage(), ex);
46 }
47 }
48
49 private static class Jaxp13Validator implements XmlValidator {
50
51 private Schema schema;
52
53 public Jaxp13Validator(Schema schema) {
54 this.schema = schema;
55 }
56
57 public SAXParseException[] validate(Source source) throws IOException {
58 return validate(source, null);
59 }
60
61 public SAXParseException[] validate(Source source, ValidationErrorHandler errorHandler) throws IOException {
62 if (errorHandler == null) {
63 errorHandler = new DefaultValidationErrorHandler();
64 }
65 Validator validator = schema.newValidator();
66 validator.setErrorHandler(errorHandler);
67 try {
68 validator.validate(source);
69 return errorHandler.getErrors();
70 }
71 catch (SAXException ex) {
72 throw new XmlValidationException("Could not validate source: " + ex.getMessage(), ex);
73 }
74 }
75 }
76
77
78 private static class DefaultValidationErrorHandler implements ValidationErrorHandler {
79
80 private List<SAXParseException> errors = new ArrayList<SAXParseException>();
81
82 public SAXParseException[] getErrors() {
83 return errors.toArray(new SAXParseException[errors.size()]);
84 }
85
86 public void warning(SAXParseException ex) throws SAXException {
87 }
88
89 public void error(SAXParseException ex) throws SAXException {
90 errors.add(ex);
91 }
92
93 public void fatalError(SAXParseException ex) throws SAXException {
94 errors.add(ex);
95 }
96 }
97 }