Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get error details from JAXB Validator?

I have some classes with JAXB annotations, I have created some instances and I need to validate them against my XSD files. I should be able to get the details of what is wrong when the objects are invalid.

So far I haven't had luck, I know about this class ValidationEventHandler but apperantly I can use it with the Unmarshaller class, the problem is that I have to validate the objects not the raw XML.

I have this code:

MyClass myObject = new MyClass();
JAXBContext jaxbContext = JAXBContext.newInstance("x.y.z");
JAXBSource jaxbSource = new JAXBSource(jaxbContext, myObject);
SchemaFactory factory = SchemaFactory
                .newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Source schemaFile = new StreamSource(getClass().getClassLoader()
                .getResourceAsStream("mySchema.xsd"));
Schema schema = factory.newSchema(schemaFile);

Validator validator = schema.newValidator();

validator.validate(jaxbSource);

This code will work, it will validate the object and throw an exception with the message, something like this:

cvc-pattern-valid: Value '12345678901' is not facet-valid with respect to pattern '\d{10}' for type 'id'.]

The problem is that I need specific details, with a string like that I would have to parse all the messages.

like image 617
Rodrigo Avatar asked Jun 18 '12 04:06

Rodrigo


1 Answers

You can set an instance of ErrorHandler on the Validator to catch individual errors:

    Validator validator = schema.newValidator();
    validator.setErrorHandler(new MyErrorHandler());
    validator.validate(source);

MyErrorHandler

Below is a sample implementation of the ErrorHandler interface. If you don't rethrow the exception the validation will continue.

import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;

public class MyErrorHandler implements ErrorHandler {

    public void warning(SAXParseException exception) throws SAXException {
        System.out.println("\nWARNING");
        exception.printStackTrace();
    }

    public void error(SAXParseException exception) throws SAXException {
        System.out.println("\nERROR");
        exception.printStackTrace();
    }

    public void fatalError(SAXParseException exception) throws SAXException {
        System.out.println("\nFATAL ERROR");
        exception.printStackTrace();
    }

} 

For More Information

  • http://blog.bdoughan.com/2010/11/validate-jaxb-object-model-with-xml.html
like image 150
bdoughan Avatar answered Sep 30 '22 18:09

bdoughan