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
25 import org.springframework.core.io.Resource;
26 import org.xml.sax.ErrorHandler;
27 import org.xml.sax.SAXException;
28 import org.xml.sax.SAXParseException;
29
30
31
32
33
34
35
36 abstract class Jaxp13ValidatorFactory {
37
38 static XmlValidator createValidator(Resource[] resources, String schemaLanguage) throws IOException {
39 try {
40 Schema schema = SchemaLoaderUtils.loadSchema(resources, schemaLanguage);
41 return new Jaxp13Validator(schema);
42 }
43 catch (SAXException ex) {
44 throw new XmlValidationException("Could not create Schema: " + ex.getMessage(), ex);
45 }
46 }
47
48 private static class Jaxp13Validator implements XmlValidator {
49
50 private Schema schema;
51
52 public Jaxp13Validator(Schema schema) {
53 this.schema = schema;
54 }
55
56 public SAXParseException[] validate(Source source) throws IOException {
57 javax.xml.validation.Validator validator = schema.newValidator();
58 ValidationErrorHandler errorHandler = new ValidationErrorHandler();
59 validator.setErrorHandler(errorHandler);
60 try {
61 validator.validate(source);
62 return errorHandler.getErrors();
63 }
64 catch (SAXException ex) {
65 throw new XmlValidationException("Could not validate source: " + ex.getMessage(), ex);
66 }
67 }
68 }
69
70
71 private static class ValidationErrorHandler implements ErrorHandler {
72
73 private List errors = new ArrayList();
74
75 private SAXParseException[] getErrors() {
76 return (SAXParseException[]) errors.toArray(new SAXParseException[errors.size()]);
77 }
78
79 public void warning(SAXParseException ex) throws SAXException {
80 }
81
82 public void error(SAXParseException ex) throws SAXException {
83 errors.add(ex);
84 }
85
86 public void fatalError(SAXParseException ex) throws SAXException {
87 errors.add(ex);
88 }
89 }
90 }