简体   繁体   中英

How can I make JAXB to fail when a mandatory element is missing?

I'm trying to add some forward compatibility to a Java application calling a Web Service at work, but JAXB seems to behave backward on the subject...

The application use the wsdl2java Maven plugin to generate a CXF Web Service client from a WSDL. It then uses that generated client to communicate with a Web Service (through SOAP over JMS). When the Web Service sends an unknown element in its response to a call, JAXB fails with an "unexpected element" error, which is understandable, and XML-compliant. To be more forward compatible, I specified a custom jaxb-reader-validation-event-handler to ignore those specific errors, which solved the problem.

But while doing some complementary tests, I discovered non-XML-compliant behaviours.
First, JAXB doesn't care about elements' order, even inside a sequence , which is not XML-compliant, but good for forward compatibility, so why not.
However, it also doesn't care if a mandatory element ( minOccurs="1" ) is not present, kindfully assigning it an arbitrary default value (which is, for elements bound to Java primitive values, their default values, like 0 for an int !).
This is both non-XML-compliant and not good for compatibility: if you need a mandatory, say, price as an integer, but the Web Service doesn't provide it for some reason, JAXB assigns the value 0 to it without a warning, making debugging really hard.
Apparently it's because if JAXB doesn't encounter an element, it simply doesn't call its setter, which means it will keep its default value.
[EDIT: I made some complementary tests, and when the application expect 1 element ( maxOccurs="1" ) but the Web Service sends 2, JAXB calls the same setter two times, overriding the first value with the second, so it seems that once the client is generated from the WSDL, minOccurs and maxOccurs are simply ignored...]

How can I make JAXB to fail when a mandatory element is missing?


We noticed that, even for an element with minOccurs="1" , the annotation of the corresponding generated attribute does not contain required = true . I tried to add it manually after the generation and before starting the application, but with no success: it seems it's simply ignored...

Maybe an additional JSR–303 validation covers what you want to achieve. You may either extend xjc's behavior with a plugin like: https://github.com/krasa/krasa-jaxb-tools to have your binding classes annotated, or use Hibernate Validator in conjunction with XML validation config as described here: https://docs.jboss.org/hibernate/validator/4.1/reference/en-US/html/validator-xmlconfiguration.html#validator-xmlconfiguration

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM