Search code examples
jaxbmoxy

Validation with DynamicJAXBContext


How could I turn on validation during unmarshalling? [moxy 2.6.0]

First intresting thing is that I need to put schema which should be already in DynamicContext. But even with setting schema to unmarshaller again it gives me an error.

I've tried to use this one:

 final JAXBUnmarshaller unmarshaller = dynamicJAXBContext.createUnmarshaller();
        //unmarshaller.setSchema();
        final Schema schema = schemas.get(type);
        unmarshaller.setSchema(schema);
        unmarshaller.setValidating(true);

And it gives an exception. Looks like part which broke this are some elements which are put there from DynamicContext

Exception Description: An error occurred resolving the XML Schema.
Internal Exception: java.lang.NullPointerException
Exception [EclipseLink-25012] (Eclipse Persistence Services - 2.6.0.v20150309-bf26070): org.eclipse.persistence.exceptions.XMLMarshalException
Exception Description: An error occurred resolving the XML Schema.
Internal Exception: java.lang.NullPointerException
    at org.eclipse.persistence.exceptions.XMLMarshalException.errorResolvingXMLSchema(XMLMarshalException.java:186)
    at org.eclipse.persistence.oxm.schema.XMLSchemaClassPathReference.getURL(XMLSchemaClassPathReference.java:48)
    at org.eclipse.persistence.oxm.XMLUnmarshaller.initializeSchemas(XMLUnmarshaller.java:211)
    at org.eclipse.persistence.oxm.XMLUnmarshaller.setValidationMode(XMLUnmarshaller.java:155)
    at org.eclipse.persistence.jaxb.JAXBUnmarshaller.setValidating(JAXBUnmarshaller.java:756)

Solution

  • The problem here is that the schema was not found. You set null instead of Schema instance.

    Btw. method

    javax.xml.bind.Unmarshaller#setValidating
    

    is deprecated since JAXB 2.0. Using method

    javax.xml.bind.Unmarshaller#setSchema
    

    will do the job.