schema = getSchema();
} else {
schema = createSchema();
}
Validator validator = schema.newValidator();
// the underlying input stream, which we need to close to avoid locking files or other resources
Source source = null;
InputStream is = null;
try {
Result result = null;
// only convert to input stream if really needed
if (isInputStreamNeeded(exchange)) {
is = exchange.getIn().getBody(InputStream.class);
if (is != null) {
source = getSource(exchange, is);
}
} else {
Object body = exchange.getIn().getBody();
if (body != null) {
source = getSource(exchange, body);
}
}
if (source == null && isFailOnNullBody()) {
throw new NoXmlBodyValidationException(exchange);
}
if (source instanceof DOMSource) {
result = new DOMResult();
} else if (source instanceof StreamSource) {
result = new StreamResult(new StringWriter());
} else if (source instanceof SAXSource) {
result = new SAXResult();
} else if (source instanceof StAXSource) {
result = null;
}
if (source != null) {
// create a new errorHandler and set it on the validator
// must be a local instance to avoid problems with concurrency (to be
// thread safe)
ValidatorErrorHandler handler = errorHandler.getClass().newInstance();
validator.setErrorHandler(handler);
try {
LOG.trace("Validating {}", source);
validator.validate(source, result);
handler.handleErrors(exchange, schema, result);
} catch (SAXParseException e) {
// can be thrown for non well formed XML
throw new SchemaValidationException(exchange, schema, Collections.singletonList(e),
Collections.<SAXParseException> emptyList(),