Validation in JAXB 2 vs JAXB 1

The release of JAXB 2 brought lot of advantages to the developer like putting annotations on the objects etc, at the same time it has given a liberty to the user about how does he/she wants to handle the validation using the JAXP validation APIs.

Validation in JAXB1
If JAXB detects error or inconsistency in the data received and it is unable to recover it throws an UnmarshalException.

eg:

JAXBContext jc = JAXBContext.newInstance( "com.thoughtclicks" );
Umarshaller u = jc.createUnmarshaller();
u.setValidating(true);


Validation in JAXB2
Developer has the choice of what and how to handle the incosistency in error validation.

eg:

JAXBContext jc = JAXBContext.newInstance( "com.thoughtclicks" );
Umarshaller u = jc.createUnmarshaller();
SchemaFactory factory = SchemaFactory.newInstance(javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = factory.newSchema(new File("order.xsd"));
u.setSchema(schema);


Either you can use the default validation handler like

u.setEventHandler(new DefaultValidationEventHandler())


or you can have your own custom validation handler and set that to the umarshaller


public class CustomValidationEventHandler implements ValidationEventHandler{
public boolean handleEvent(ValidationEvent ve) {
if (ve.getSeverity()==ve.FATAL_ERROR ||
ve .getSeverity()==ve.ERROR){
ValidationEventLocator locator = ve.getLocator();
//log the message
System.out.println("Message is " + ve.getMessage());
//log the error reference
System.out.println("Column is " +
locator.getColumnNumber() +
" at line number " + locator.getLineNumber());
}
return true;
}

}


You are all set to handle the validations.

Good luck !

0 comments:

Post a Comment