DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
docBuilderFactory.setNamespaceAware( true );
final Schema v2Schema = SchemaFactory.newInstance( javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI )
.newSchema( new StreamSource( getStreamFromClasspath( "persistence_2_0.xsd" ) ) );
final Validator v2Validator = v2Schema.newValidator();
final Schema v1Schema = SchemaFactory.newInstance( javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI )
.newSchema( new StreamSource( getStreamFromClasspath( "persistence_1_0.xsd" ) ) );
final Validator v1Validator = v1Schema.newValidator();
InputSource source = new InputSource( is );
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
docBuilder.setEntityResolver( resolver );
List<SAXParseException> errors = new ArrayList<SAXParseException>();
Document doc = null;
//first sparse document and collect syntaxic errors
try {
doc = docBuilder.parse( source );
}
catch ( SAXParseException e ) {
errors.add( e );
}
if (errors.size() == 0) {
v2Validator.setErrorHandler( new ErrorLogger( errors ) );
log.trace("Validate with persistence_2_0.xsd schema on file {}", configURL);
v2Validator.validate( new DOMSource( doc ) );
boolean isV1Schema = false;
if ( errors.size() != 0 ) {
//v2 fails, it could be because the file is v1.
log.trace("Found error with persistence_2_0.xsd schema on file {}", configURL);
SAXParseException exception = errors.get( 0 );
final String errorMessage = exception.getMessage();
//is it a validation error due to a v1 schema validated by a v2
isV1Schema = errorMessage.contains("1.0")
&& errorMessage.contains("2.0")
&& errorMessage.contains("version");
}
if (isV1Schema) {
log.trace("Validate with persistence_1_0.xsd schema on file {}", configURL);
errors.clear();
v1Validator.setErrorHandler( new ErrorLogger( errors ) );
v1Validator.validate( new DOMSource( doc ) );
}
}
if ( errors.size() != 0 ) {
//report all errors in the exception
StringBuilder errorMessage = new StringBuilder( );