Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
364 views
in Technique[技术] by (71.8m points)

java - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...