public class ValidatorBootstrapTest {
private static final String VALIDATION_XML_FILE = "META-INF/validation.xml";
@Test
public void assertValidatorInstanceCanBeCreatedWithValidationXml() {
Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
assertNotNull( validator );
}
@Test
public void assertLookaheadParsingWorksWithStax() throws Exception {
InputStream in = null;
try {
in = getValidationXmlInputStream();
if ( !in.markSupported() ) {
in = new BufferedInputStream( in );
}
String actualVersion = getSchemaVersion( in );
assertEquals( "1.1", actualVersion );
}
finally {
if ( in != null ) {
in.close();
}
}
}
@Test
public void assertBufferedInputstreamSupportsMarkAndReset() throws Exception {
String s = "Say it twice";
byte bytes[] = s.getBytes();
assertEquals( "Unexpected number of bytes", 12, bytes.length );
ByteArrayInputStream in = new ByteArrayInputStream( bytes );
StringBuilder actual = new StringBuilder();
int read = 0;
int c;
boolean reset = false;
try (BufferedInputStream f = new BufferedInputStream( in )) {
f.mark( 1024 * 1024 );
while ( read < bytes.length ) {
c = f.read();
actual.append( (char) c );
read++;
if ( read == 12 ) {
if ( reset ) {
break;
}
else {
f.reset();
read = 0;
reset = true;
}
}
}
}
assertEquals( "Say it twiceSay it twice", actual.toString() );
}
private String getSchemaVersion(InputStream xmlInputStream) throws Exception {
xmlInputStream.mark( 1024 * 1024 );
try {
XMLEventReader xmlEventReader = createXmlEventReader( xmlInputStream );
StartElement rootElement = getRootElement( xmlEventReader );
return getVersionValue( rootElement );
}
finally {
xmlInputStream.reset();
}
}
private XMLEventReader createXmlEventReader(InputStream xmlStream) throws XMLStreamException {
return XMLInputFactory.newInstance().createXMLEventReader( xmlStream );
}
private StartElement getRootElement(XMLEventReader xmlEventReader) throws XMLStreamException {
while ( xmlEventReader.hasNext() ) {
XMLEvent nextEvent = xmlEventReader.nextEvent();
if ( nextEvent.isStartElement() ) {
return nextEvent.asStartElement();
}
}
return null;
}
private String getVersionValue(StartElement startElement) {
if ( startElement == null ) {
return null;
}
Attribute versionAttribute = startElement.getAttributeByName( new QName( "version" ) );
return versionAttribute.getValue();
}
private InputStream getValidationXmlInputStream() {
ClassLoader loader = this.getClass().getClassLoader();
return loader.getResourceAsStream( VALIDATION_XML_FILE );
}
}