01: /*
02: * Copyright 2006 the original author or authors.
03: *
04: * Licensed under the Apache License, Version 2.0 (the "License");
05: * you may not use this file except in compliance with the License.
06: * You may obtain a copy of the License at
07: *
08: * http://www.apache.org/licenses/LICENSE-2.0
09: *
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 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: * Internal class that uses JAXP 1.0 features to create <code>XmlValidator</code> instances.
32: *
33: * @author Arjen Poutsma
34: * @since 1.0.0
35: */
36: abstract class Jaxp13ValidatorFactory {
37:
38: static XmlValidator createValidator(Resource[] resources,
39: String schemaLanguage) throws IOException {
40: try {
41: Schema schema = SchemaLoaderUtils.loadSchema(resources,
42: schemaLanguage);
43: return new Jaxp13Validator(schema);
44: } catch (SAXException ex) {
45: throw new XmlValidationException(
46: "Could not create Schema: " + ex.getMessage(), ex);
47: }
48: }
49:
50: private static class Jaxp13Validator implements XmlValidator {
51:
52: private Schema schema;
53:
54: public Jaxp13Validator(Schema schema) {
55: this .schema = schema;
56: }
57:
58: public SAXParseException[] validate(Source source)
59: throws IOException {
60: javax.xml.validation.Validator validator = schema
61: .newValidator();
62: ValidationErrorHandler errorHandler = new ValidationErrorHandler();
63: validator.setErrorHandler(errorHandler);
64: try {
65: validator.validate(source);
66: return errorHandler.getErrors();
67: } catch (SAXException ex) {
68: throw new XmlValidationException(
69: "Could not validate source: " + ex.getMessage(),
70: ex);
71: }
72: }
73: }
74:
75: /** <code>ErrorHandler</code> implementation that stores errors and fatal errors in a list. */
76: private static class ValidationErrorHandler implements ErrorHandler {
77:
78: private List errors = new ArrayList();
79:
80: private SAXParseException[] getErrors() {
81: return (SAXParseException[]) errors
82: .toArray(new SAXParseException[errors.size()]);
83: }
84:
85: public void warning(SAXParseException ex) throws SAXException {
86: }
87:
88: public void error(SAXParseException ex) throws SAXException {
89: errors.add(ex);
90: }
91:
92: public void fatalError(SAXParseException ex)
93: throws SAXException {
94: errors.add(ex);
95: }
96: }
97: }
|