Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JAXB XMLAdapter method does not throws Exception

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?

like image 847
jatin mistry Avatar asked Jun 20 '12 07:06

jatin mistry


1 Answers

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.

like image 183
npe Avatar answered Nov 10 '22 05:11

npe