How to configure JAXB / Moxy to throw an error on potential lost data in XML

491 views Asked by At

Is it possible to configure JAXB to throw an exception if the supplied data is not unmarshalable into the expected data type?

We have a Integer XmlElement and sometimes get values like "1.1" as input - Jaxb / Moxy just silently ignores these values and sets them to null. We solved it for the known cases by using a @XmlJavaTypeAdapter that rounds those values, but we won't know if any other fields get silently ignored on wrong data and would prefer a exception for clear feedback.

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Wrapper
{
    @XmlNullPolicy(emptyNodeRepresentsNull = true, nullRepresentationForXml = XmlMarshalNullRepresentation.EMPTY_NODE)
    private Integer emptyNodeOnNull;

    @XmlElement
    private Integer ignoredOnNull;
}

The following test should throw some kind of exception..

@Test(expected = IllegalArgumentException.class)
public void testUnmarshallWithInvalidValue() throws Exception
{
    JAXBContext context = JAXBContext.newInstance(Wrapper.class);
    StreamSource source = new StreamSource(
            new StringReader(
                    "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><wrapper><emptyNodeOnNull>1.1</emptyNodeOnNull><ignoredOnNull>2.2</ignoredOnNull></wrapper>"));
    context.createUnmarshaller().unmarshal(source, Wrapper.class);

    fail("Should have thrown some kind of exception due to lost data.");
}

We use Moxy 2.5.2 for JAXB right now, as we need the @XmlNullPolicy(emptyNodeRepresentsNull = true, nullRepresentationForXml = XmlMarshalNullRepresentation.EMPTY_NODE).

1

There are 1 answers

2
bdoughan On BEST ANSWER

You can set an instance of ValidationEventHandler on the Unmarshaller to collect of fail on this type of issue.

public class DeserializationEventHandler implements ValidationEventHandler
{
private static final Logger LOG = LoggerFactory.getLogger(DeserializationEventHandler.class);

@Override
public boolean handleEvent(ValidationEvent event)
{
    LOG.warn("Error during XML conversion: {}", event);

    if (event.getLinkedException() instanceof NumberFormatException)
        return false;

    return true;
}

}