JAXB 'forgets' to add nil='true' when attribute value is set, but element value is not - soap

We use Jaxb (jaxb-api 2.2.5) to generate a Java class from an XSD. The 'someField' element has a nillable='true' attribute and an (implicit) minoccurs='1'. There is also an optional 'order' attribute.
When we set the order attribute on someField, but no value, JAXB will generate the XML element in the request without nill='true' and this is not accepted by the XSD and results in a SOAP fault.
The XSD for the field:
<xs:element name="someField" nillable="true">
<xs:complexType>
<xs:simpleContent>
<xs:extension base="iata:AlphaNumericStringLength1to19">
<xs:attribute name="order" type="xs:integer" use="optional"/>
</xs:extension>
</xs:simpleContent>
</xs:complexType>
</xs:element>
Jaxb translates this to the following field on our Java class:
#XmlElement(required = true, nillable = true)
protected SomeParentType.SomeField someField;
The SomeField class looks like this:
public static class SomeField{
#XmlValue
protected String value;
#XmlAttribute
protected BigInteger order;
// getters + setters
}
When we set the order ATTRIBUTE to 2 (for example), and set nothing for the value, JAXB will generate this:
<pay1:someField order="2"/>
This is not valid according to the XSD and it results in a SOAP fault when we send it.
This does work:
<pay1:someField xsi:nil="true" order="2"/>
Do you know how we can get JAXB be to generate the latter? And is JAXB actually wrong in generating the nil-less version?

And is JAXB actually wrong in generating the nil-less version?
Let me get back to you on this.
Do you know how we can get JAXB be to generate the latter?
Below is what you can do
Java Model
SomeParentType
To get the behaviour you are looking for with existing JAXB libraries the domain model needs to be of the following form:
import java.math.BigInteger;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.*;
#XmlRootElement
public class SomeParentType {
#XmlElementRef(name="someField")
protected JAXBElement<SomeParentType.SomeField> someField;
public static class SomeField{
#XmlValue
protected String value;
#XmlAttribute
protected BigInteger order;
// getters + setters
}
}
Registry
To go along with the #XmlElementRef we need to have an #XmlElementDecl on a class annotated with #XmlRegistry.
import javax.xml.namespace.QName;
import javax.xml.bind.*;
import javax.xml.bind.annotation.*;
#XmlRegistry
public class Registry {
#XmlElementDecl(name="someField")
public JAXBElement<SomeParentType.SomeField> createSomeField(SomeParentType.SomeField someField) {
return new JAXBElement(new QName("someField"), SomeParentType.SomeField.class, someField);
}
}
Demo Code
Below is some demo code to exercise your use case:
import javax.xml.bind.*;
import java.math.BigInteger;
public class Demo {
public static void main(String[] args) throws Exception {
// Create the JAXBContext to bring in the Registry
JAXBContext jc = JAXBContext.newInstance(SomeParentType.class, Registry.class);
// Create the instance of SomeField
SomeParentType.SomeField sf = new SomeParentType.SomeField();
sf.order = new BigInteger("1");
// Wrap the SomeField in a JAXBElement & specify the nil aspect
Registry registry = new Registry();
JAXBElement<SomeParentType.SomeField> jaxbElement = registry.createSomeField(sf);
jaxbElement.setNil(true);
SomeParentType spt = new SomeParentType();
spt.someField = jaxbElement;
// Marshal the domain model to XML
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(spt, System.out);
}
}
Output
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<someParentType>
<someField xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" order="1" xsi:nil="true"/>
</someParentType>

Related

Sending and Receiving a xml object (unmarshall)

I am trying to receive this object in my web service from a html page. In the browser opened by eclipse works fine but when i try the same thing in firefox i get the fallowing problem:
Caused by: javax.xml.bind.UnmarshalException: unexpected element (uri:"http://www.w3.org/1999/xhtml", local:"userclient"). Expected elements are <{}userclient>
#XmlRootElement
public class Userclient {
#XmlElement
private String first_name;
#XmlElement
private String last_name;
#XmlElement
private String email;
public Userclient() {
}
//....
}
//Reciving
#PUT
#Consumes("application/xml")
public Response addUser(Userclient user,
#CookieParam("sessionId") String sessionCookie) {
}
//Sending
<script>
RestServlet.addUser({
$entity : userclient
});
</script>
Here are a couple of options for solving your problem based on what your XML looks like:
Option #1 - elementFormDefault="unqualified"
Input XML
If in your XML only the global (top level) elements are namespace qualified:
<ns:userclient xmlns:ns="http://www.w3.org/1999/xhtml">
<first_name>Jane</first_name>
<ns:userclient>
Userclient.java
Then you could just specify the namespace parameter on the #XmlRootElement annotation.
#XmlRootElement(namespace="http://www.w3.org/1999/xhtml"
public class Userclient {
Option #2 - elementFormDefault="qualified"
Input XML
If all the elements are namespace qualified like:
<userclient xmlns="http://www.w3.org/1999/xhtml">
<first_name>Jane</first_name>
<userclient>
package-info.java
You can use the package level #XmlSchema annotation to apply namespace qualification to your model.
#XmlSchema(
namespace = "http://www.w3.org/1999/xhtml",
elementFormDefault = XmlNsForm.QUALIFIED)
package example;
import javax.xml.bind.annotation.XmlNsForm;
import javax.xml.bind.annotation.XmlSchema;
For More Information
Below is a link to an article on my blog that covers more about JAXB and namespace qualification:
http://blog.bdoughan.com/2010/08/jaxb-namespaces.html
Note
You are currently adding more annotations than are necessary. JAXB is configuration by exception so you only need to add annotations where you want the XML representation to differ from the default.
For More Information
Below is a link to an article on my blog that covers more about JAXB's default XML representation:
http://blog.bdoughan.com/2012/07/jaxb-no-annotations-required.html
#XmlRootElement
#XmlAccessorType(XmlAccessType.FIELD)
public class Userclient {
private String first_name;
private String last_name;
private String email;
public Userclient() {
}
//....
}

How to add additional classes to JAXBContext in CXF

I need to use <any>element in my xsd for scalability. So i used xsd as like below.
<complexType name="AddInput">
<sequence>
<element name="First" type="int"></element>
<element name="Sec" type="int"></element>
<any processContents="lax" namespace="##any" minOccurs="0" maxOccurs="unbounded"></any>
</sequence>
</complexType>
I have defined a complex object to place into the <any> placeholder, with ObjectFactory (#XMLRegistry, #XmlElementDecl) But still if i run below code, i am getting
org.apache.xerces.dom.ElementNSImpl
instead of JAXBElementObject. I searched in google, i see that JAXBContext should know about the schema. But i am not sure, how to make JAXBContext know my complex object. Any idea would be helpful.
List<Object> elemList = (List<Object>)input.getAny();
for(Object elem : elemList){
System.out.println(elem.getClass());
}
If you have a JAX-RS method like the following the JAXBContext used will be equivalent to making the following call JAXBContext.newInstance(Foo)
#GET
#Produces(MediaType.APPLICATION_XML)
#Path("{id}")
public Foo read(#PathParam("id") long id) {
return entityManager.find(Foo.class, id);
}
If you want the JAXBContext to be aware of all the classes you generated from the XML schema you can associate a JAXBContext with the domain object using a ContextResolver.
import java.io.*;
import java.util.*;
import javax.ws.rs.Produces;
import javax.ws.rs.ext.*;
import javax.xml.bind.*;
import org.eclipse.persistence.jaxb.JAXBContextFactory;
#Provider
#Produces(MediaType.APPLICATION_XML)
public class FooContextResolver implements ContextResolver<JAXBContext> {
private JAXBContext jc;
public FooContextResolver() {
try {
jc = JAXBContext.newInstance("com.example.foo");
} catch(JAXBException e) {
throw new RuntimeException(e);
}
}
public JAXBContext getContext(Class<?> clazz) {
if(Foo.class == clazz) {
return jc;
}
return null;
}
}
Example
Flexible marshalling with JAXB
you need to set :
jaxb.additionalContextClasses
see : https://stackoverflow.com/a/55485843/1634131

Moxy - Creating XML element with no corresponding Java Property

I've been using Moxy to successfully marshall / unmarshall complex xml types into a more simple java Structure. In particular, I'm working with ISO Pain 20022 messages and there are a number of fields that are present in the XML that we don't care about:
<?xml version="1.0" encoding="UTF-8"?>
<iso:Document xmlns:iso="urn:iso:std:iso:20022:tech:xsd:pain.001.001.04" >
<iso:CstmrCdtTrfInitn>
<iso:GrpHdr>
<iso:MsgId>OriginalMessageID</iso:MsgId>
<iso:CreDtTm>2013-05-29T20:02:22.615</iso:CreDtTm>
<iso:NbOfTxs>1</iso:NbOfTxs>
<iso:InitgPty/>
</iso:GrpHdr>
<iso:PmtInf>
...
</iso:Document>
Here is my oxm bindings file piece:
<xml-element java-attribute="messageId" xml-path="iso:CstmrCdtTrfInitn/iso:GrpHdr/iso:MsgId/text()"/>
<xml-element java-attribute="creationDateTime" xml-path="iso:CstmrCdtTrfInitn/iso:GrpHdr/iso:CreDtTm/text()"/>
I need to generate the additional two xml elements iso:NbOfTxs and iso:InitgPty which will always be the same and there is no corresponding property for these on the java class that is generating the xml.
Is this possible?
Thanks.
I am still working on this use case. Below is the XML I am currently able to generate (I recognize that it's not correct).
Output
<?xml version="1.0" encoding="UTF-8"?>
<iso:Document xmlns:iso="urn:iso:std:iso:20022:tech:xsd:pain.001.001.04">
<iso:CstmrCdtTrfInitn>
<iso:GrpHdr>
<iso:MsgId>OriginalMessageID</iso:MsgId>
</iso:GrpHdr>
</iso:CstmrCdtTrfInitn>
<iso:CstmrCdtTrfInitn>
<iso:GrpHdr>
<iso:CreDtTm>2013-05-29T20:02:22.615</iso:CreDtTm>
<iso:NbOfTxs>1</iso:NbOfTxs>
<iso:InitgPty/>
</iso:GrpHdr>
</iso:CstmrCdtTrfInitn>
</iso:Document>
Document
Below is a simplified version of your domain model:
import java.util.Date;
public class Document {
private String messageId;
private Date creationDateTime;
}
oxm.xml
In the metadata below I'm trying to use an XmlAdapter to convert the Date property into a more complex object that can write out the other 2 XML elements.
<?xml version="1.0"?>
<xml-bindings
xmlns="http://www.eclipse.org/eclipselink/xsds/persistence/oxm"
package-name="forum16839007">
<xml-schema
namespace="urn:iso:std:iso:20022:tech:xsd:pain.001.001.04"
element-form-default="QUALIFIED">
<xml-ns prefix="iso" namespace-uri="urn:iso:std:iso:20022:tech:xsd:pain.001.001.04"/>
</xml-schema>
<java-types>
<java-type name="Document" xml-accessor-type="FIELD">
<xml-root-element name="Document"/>
<java-attributes>
<xml-element java-attribute="messageId" xml-path="iso:CstmrCdtTrfInitn/iso:GrpHdr/iso:MsgId/text()"/>
<xml-element java-attribute="creationDateTime" xml-path=".">
<xml-java-type-adapter value="forum16839007.ExtraAdapter"/>
</xml-element>
</java-attributes>
</java-type>
</java-types>
</xml-bindings>
ExtraAdapter
Here is the XmlAdapter that converts a Date into a more complex object.
import java.util.Date;
import javax.xml.bind.annotation.adapters.XmlAdapter;
import org.eclipse.persistence.oxm.annotations.XmlPath;
public class ExtraAdapter extends XmlAdapter<ExtraAdapter.Extra, Date>{
public static class Extra {
#XmlPath("iso:CstmrCdtTrfInitn/iso:GrpHdr/iso:CreDtTm/text()")
public Date creationDateTime;
#XmlPath("iso:CstmrCdtTrfInitn/iso:GrpHdr/iso:NbOfTxs/text()")
public final int NbOfTxs = 1;
#XmlPath("iso:CstmrCdtTrfInitn/iso:GrpHdr/iso:InitgPty/text()")
public final Empty initgPty = new Empty();
}
public static class Empty {
}
#Override
public Date unmarshal(Extra extra) throws Exception {
return extra.creationDateTime;
}
#Override
public Extra marshal(Date date) throws Exception {
Extra extra = new Extra();
extra.creationDateTime = date;
return extra;
}
}
Demo
import java.io.File;
import java.util.*;
import javax.xml.bind.*;
import org.eclipse.persistence.jaxb.JAXBContextProperties;
public class Demo {
public static void main(String[] args) throws Exception {
Map<String, Object> properties = new HashMap<String, Object>(1);
properties.put(JAXBContextProperties.OXM_METADATA_SOURCE, "forum16839007/oxm.xml");
JAXBContext jc = JAXBContext.newInstance(new Class[] {Document.class}, properties);
Unmarshaller unmarshaller = jc.createUnmarshaller();
File xml = new File("src/forum16839007/input.xml");
Document document = (Document) unmarshaller.unmarshal(xml);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(document, System.out);
}
}

MOXy's #XmlCDATA seems to have no affect

I would like to have the following returned to the browser (view source)
<content>
<![CDATA[Please show this inside a unescaped CDATA tag]]>
</content>
But I acutally get
<content>
Please show this inside a unescaped CDATA tag
</content>
If, I change the value of content to be
&lt ;![CDATA[Please show this inside a unescaped CDATA tag]]&gt ;
, the less than and the greater than for the tag are escaped.
Wondering how to achieve what I wanted????
Here is my code
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
#Path("/myRequest")
public class MyRestClass {
#GET
#Path("{myPathNumber}")
#Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public Object doInquiry(#PathParam("myPathNumber") String myPathNumber) {
try {
return new MyObject();
} catch (Exception e) {
return "exception " + e.getMessage();
}
}
}
package org.openengine.wink;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import org.eclipse.persistence.oxm.annotations.XmlCDATA;
#XmlRootElement
public class MyObject implements Serializable {
#XmlElement
#XmlCDATA
private String content = "Please show this inside a unescaped CDATA tag";
}
in package org.openengine.wink I have a file, jaxb.properties, with the following content
javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory
CLASSPATH
My best guess is that EclipseLink JAXB (MOXy) is not correctly configured on your classpath, and the JAXB RI is being used as the JAXB (JSR-222) provider in your environment.
METADATA
The EclipseLink JAXB (MOXy) metadata you have provided appears to be correct. This can be verified with the following standalone demo code.
MyObject
By default JAXB (JSR-222) implementations look for metadata on the property (getter/setter). Since you have annotated the field I would recommend using the #XmlAccessorType(XmlAccessType.FIELD annotation (see: http://blog.bdoughan.com/2011/06/using-jaxbs-xmlaccessortype-to.html).
package org.openengine.wink;
import java.io.Serializable;
import javax.xml.bind.annotation.*;
import org.eclipse.persistence.oxm.annotations.XmlCDATA;
#XmlRootElement
#XmlAccessorType(XmlAccessType.FIELD)
public class MyObject implements Serializable {
#XmlElement
#XmlCDATA
private String content = "Please show this inside a unescaped CDATA tag";
}
jaxb.properties
To specify MOXy as your JAXB provider you need to have the EclipseLink binaries on your classpath and have a file called jaxb.properties in the same package as your domain model with the following entry (see: http://blog.bdoughan.com/2011/05/specifying-eclipselink-moxy-as-your.html).
javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory
Demo
package org.openengine.wink;
import javax.xml.bind.*;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(MyObject.class);
MyObject myObject = new MyObject();
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(myObject, System.out);
}
}
Output
<?xml version="1.0" encoding="UTF-8"?>
<myObject>
<content><![CDATA[Please show this inside a unescaped CDATA tag]]></content>
</myObject>
For More Information
http://blog.bdoughan.com/2010/07/cdata-cdata-run-run-data-run.html

How do I request a subset of XMLElements using MOXy?

I have a RESTful service that needs to return only a few of the XmlElements if "selectors" are submitted with the request. The URL will take the form of:
/merchants/{merchantId}/profile?selectors=<field1|field2|....|fieldN>
The selectors are optional, and so far I have implemented the service for the full set of elements to be returned for {merchantId} without selectors specified. Now I'm trying to figure out how to add in this added functionality. I'm sure this is covered in documentation but I can't find where. Any RTFM pointers would be appreciated. Thanks.
EclipseLink JAXB (MOXy) does not currently offer a mechanism to selectively indicate which fields/properties are included on a per marshal operation. This sounds like an interesting use case. I would appreciate if you could enter this as an enhancement request using the following link:
https://bugs.eclipse.org/bugs/enter_bug.cgi?product=EclipseLink
Below is an example of how you could use a stateful XmlAdapter to implement this use case by exploiting the fact that a JAXB (JSR-222) will not marshal an element when the value is null (see: http://blog.bdoughan.com/2012/04/binding-to-json-xml-handling-null.html).
FieldAdapter
Since we are going to leverage stateful XmlAdapters we're going to need one per field. Since all our XmlAdapters will perform the same logic we can create a super class that the others can extend from.
package forum13094195;
import javax.xml.bind.annotation.adapters.XmlAdapter;
public class FieldAdapter<T> extends XmlAdapter<T, T> {
private boolean include;
public FieldAdapter() {
this.include = true;
}
public FieldAdapter(boolean include) {
this.include = include;
}
#Override
public T marshal(T value) throws Exception {
if(include) {
return value;
}
return null;
}
#Override
public T unmarshal(T value) throws Exception {
return value;
}
}
Field1Adapter
package forum13094195;
public class Field1Adapter extends FieldAdapter<String> {
public Field1Adapter() {}
public Field1Adapter(boolean include) {
super(include);
}
}
Field2Adapter
package forum13094195;
public class Field2Adapter extends FieldAdapter<Integer>{
public Field2Adapter() {}
public Field2Adapter(boolean include) {
super(include);
}
}
Field3Adapter
package forum13094195;
public class Field3Adapter extends FieldAdapter<String> {
public Field3Adapter() {}
public Field3Adapter(boolean include) {
super(include);
}
}
Merchant
The #XmlJavaTypeAdapter annotation is used to specify an XmlAdapter on a field/property.
package forum13094195;
import javax.xml.bind.annotation.*;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
#XmlRootElement
#XmlAccessorType(XmlAccessType.FIELD)
public class Merchant {
#XmlJavaTypeAdapter(Field1Adapter.class)
String field1;
#XmlJavaTypeAdapter(Field2Adapter.class)
int field2;
#XmlJavaTypeAdapter(Field3Adapter.class)
String field3;
}
Demo
The demo code below demonstrates how to set a stateful XmlAdapter on the Marshaller.
package forum13094195;
import javax.xml.bind.*;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Merchant.class);
Merchant merchant = new Merchant();
merchant.field1 = "A";
merchant.field2 = 2;
merchant.field3 = "C";
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(merchant, System.out);
marshaller.setAdapter(new Field1Adapter(false));
marshaller.setAdapter(new Field2Adapter(false));
marshaller.setAdapter(new Field3Adapter(true));
marshaller.marshal(merchant, System.out);
}
}
Output
Below is the output from running the demo code. By default the entire object is marshalled out. The second document marshalled does not contain the fields we excluded.
<?xml version="1.0" encoding="UTF-8"?>
<merchant>
<field1>A</field1>
<field2>2</field2>
<field3>C</field3>
</merchant>
<?xml version="1.0" encoding="UTF-8"?>
<merchant>
<field3>C</field3>
</merchant>
Note: I'm the EclipseLink JAXB (MOXy) lead and a member of the JAXB (JSR-222) expert group.
In EclipseLink 2.5.0 we released a new feature called Object Graphs that enables you to marshal/unmarshal a subset of mapped fields/properties.
// Create the Object Graph
ObjectGraph subset = JAXBHelper.getJAXBContext(jc).createObjectGraph(Merchant.class);
subset.addAttributeNodes("field1", "field1", "fieldN");
// Output XML - Based on Object Graph
marshaller.setProperty(MarshallerProperties.OBJECT_GRAPH, subset);
marshaller.marshal(customer, System.out);
For More Information
http://blog.bdoughan.com/2013/03/moxys-object-graphs-partial-models-on.html