How to get error information from JAXB Validator?

I have several classes with JAXB annotations, I created several instances, and I need to test them on my XSD files. I should be able to get information about what is wrong when objects are invalid.

So far I have not been lucky, I know about this ValidationEventHandler class, but I can use it with the Unmarshaller class, the problem is that I have to check objects, not 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 check the object and throw an exception with a message, something like this:

cvc-pattern-valid: The value "12345678901" is not valid, respectfully for the pattern '\ d {10}' for type 'id'.]

, , , .

+5
1

ErrorHandler Validator :

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

MyErrorHandler

ErrorHandler. , .

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();
    }

} 

0

All Articles