JAXB XMLAdapter method does not throws Exception
Asked Answered
D

1

19

I am using JAXB XMLadapter to marshal and unmarshal Boolean values. The application's XML file will be accessed by C# application also. We have to validate this XML file and this is done using XSD. C# application writes "True" value for Boolean nodes. But the same does get validated by our XSD as it only allows "true/false" or "1/0". So we have kept String for boolean values in XSD and that string will be validated by XMLAdapter to marshal and unmarshal on our side. The XML Adapter is as follows:

public class BooleanAdapter extends XmlAdapter<String, Boolean> {

    @Override
    public Boolean unmarshal(String v) throws Exception {

        if(v.equalsIgnoreCase("true") || v.equals("1")) {
            return true;
        } else if(v.equalsIgnoreCase("false") || v.equals("0")) {
            return false;
        } else {
            throw new Exception("Boolean Value from XML File is Wrong.");
        }
    }

    @Override
    public String marshal(Boolean v) throws Exception {
        return v.toString();        
    }
}

The code above works in normal conditions, but when invalid data(eg: "abcd" or "") is read from xml file then the "throw new Exception();" is not getting propagated and the Unmarshal process moves on to read next node. I want the application to stop as soon as an exception is thrown. It seems my Exception is getting eaten away. Any help is much appreciated.

How to resolve this problem?

Dawes answered 20/6, 2012 at 7:2 Comment(0)
L
29

From the JavaDoc of XMLAdapter#unmarshal(ValueType):

Throws: java.lang.Exception - if there's an error during the conversion. The caller is responsible for reporting the error to the user through ValidationEventHandler.

So, yes - the exception is eaten and then reported using ValidationEventHandler, not thrown to the top of your stack.

Check if you are already using any (custom, perhaps) ValidationEventHandler that groups your exceptions, or use DefaultValidationEventHandler, like this:

unmarshaller.setEventHandler(new DefaultValidationEventHandler());

It will cause unmarshalling failure on first error.

Leclaire answered 20/6, 2012 at 7:13 Comment(1)
Thank you @npe: That worked..! :) did not knew much about ValidationEventHandler() but your pointers to JavaDoc helped a lot. Just setting unmarshaller.setEventHandler(new DefaultValidationEventHandler()); did the work.. Marking your solution as an answer.. Cheers..!Dawes

© 2022 - 2024 — McMap. All rights reserved.