September 30, 2011

Mixing Nesting and References with JAXB's XmlAdapter

Recently I came across a question on Stack Overflow asking if JAXB could marshal the first occurrence of an object as containment and all subsequent occurrences as a reference.  Below is an expanded version of my answer (up votes appreciated) demonstrating how this can be achieved by leveraging JAXB's XmlAdapter.


input.xml

The following is the XML document I will use for this example. The 2nd "other-phone-number" element refers to the same data as the "primary-phone-number" element, and the 3rd "other-phone-number" element refers to the same data as the 1st "other-phone-number" element.

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<customer>
    <primary-phone-number id="B">555-BBBB</primary-phone-number>
    <other-phone-number id="A">555-AAAA</other-phone-number>
    <other-phone-number reference="B"/>
    <other-phone-number reference="A"/>
</customer>

Customer

The Customer class maintains references to PhoneNumber objects. The same instance of PhoneNumber may be referenced multiple times.
package package blog.xmladapter.stateful;

import java.util.List;
import javax.xml.bind.annotation.*;

@XmlRootElement
@XmlType(propOrder={"primaryPhoneNumber", "otherPhoneNumbers"})
public class Customer {

    private PhoneNumber primaryPhoneNumber; 
    private List<PhoneNumber> otherPhoneNumbers;

    @XmlElement(name="primary-phone-number")
    public PhoneNumber getPrimaryPhoneNumber() {
        return primaryPhoneNumber;
    }

    public void setPrimaryPhoneNumber(PhoneNumber primaryPhoneNumber) {
        this.primaryPhoneNumber = primaryPhoneNumber;
    }

    @XmlElement(name="other-phone-number")
    public List<PhoneNumber> getOtherPhoneNumbers() {
        return otherPhoneNumbers;
    }

    public void setOtherPhoneNumbers(List<PhoneNumber> phoneNumbers) {
        this.otherPhoneNumbers = phoneNumbers;
    }

}

PhoneNumber

This is a class that can either appear in the document itself or as a reference. This will be handled using an XmlAdapter. An XmlAdapter is configured using the @XmlJavaTypeAdapter annotation. Since we have specified this adapter at the type/class level it will apply to all properties referencing the PhoneNumber class:

package blog.xmladapter.stateful;

import javax.xml.bind.annotation.*;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;

@XmlJavaTypeAdapter(PhoneNumberAdapter.class)
public class PhoneNumber {

    private String id;
    private String number;

    @XmlAttribute
    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    @XmlValue
    public String getNumber() {
        return number;
    }

    public void setNumber(String number) {
        this.number = number;
    }

    @Override
    public boolean equals(Object object) {
        if(null == object || object.getClass() != this.getClass()) {
            return false;
        }
        PhoneNumber test = (PhoneNumber) object;
        if(!equals(id, test.getId())) {
            return false;
        }
        return equals(number, test.getNumber());
    }

    private boolean equals(String control, String test) {
        if(null == control) {
            return null == test;
        } else {
            return control.equals(test);
        }
    }

    @Override
    public int hashCode() {
        return id.hashCode();
    }

}

PhoneNumberAdapter

Below is the implementation of the XmlAdapter. Note that we must maintain if the PhoneNumber object has been seen before. If it has we only populate the id portion of the AdaptedPhoneNumber object.

package blog.xmladapter.stateful;

import java.util.*;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.adapters.XmlAdapter;

public class PhoneNumberAdapter extends XmlAdapter<PhoneNumberAdapter.AdaptedPhoneNumber, PhoneNumber>{

    private List<PhoneNumber> phoneNumberList = new ArrayList<PhoneNumber>();
    private Map<String, PhoneNumber> phoneNumberMap = new HashMap<String, PhoneNumber>();

    public static class AdaptedPhoneNumber extends PhoneNumber {
        @XmlAttribute
        public String reference;
    }

    @Override
    public AdaptedPhoneNumber marshal(PhoneNumber phoneNumber) throws Exception {
        AdaptedPhoneNumber adaptedPhoneNumber = new AdaptedPhoneNumber();
        if(phoneNumberList.contains(phoneNumber)) {
            adaptedPhoneNumber.reference = phoneNumber.getId();
        } else {
            adaptedPhoneNumber.setId(phoneNumber.getId());
            adaptedPhoneNumber.setNumber(phoneNumber.getNumber());
            phoneNumberList.add(phoneNumber);
        }
        return adaptedPhoneNumber;
    }

    @Override
    public PhoneNumber unmarshal(AdaptedPhoneNumber adaptedPhoneNumber) throws Exception {
        PhoneNumber phoneNumber = phoneNumberMap.get(adaptedPhoneNumber.reference);
        if(null == phoneNumber) {
            phoneNumber = new PhoneNumber();
            phoneNumber.setId(adaptedPhoneNumber.getId());
            phoneNumber.setNumber(adaptedPhoneNumber.getNumber());
            phoneNumberMap.put(phoneNumber.getId(), phoneNumber);
        }
        return phoneNumber;
    }

}

Demo

To ensure the same instance of the XmlAdapter is used for the entire marshal and unmarshal operations we must specifically set an instance of the XmlAdapter on both the Marshaller and Unmarshaller:

package blog.xmladapter.stateful;

import java.io.File;
import javax.xml.bind.*;

public class Demo {

    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(Customer.class);

        Unmarshaller unmarshaller = jc.createUnmarshaller();
        unmarshaller.setAdapter(new PhoneNumberAdapter());
        File xml = new File("src/blog/xmladapter/stateful/input.xml");
        Customer customer = (Customer) unmarshaller.unmarshal(xml);

        PhoneNumber primaryPN = customer.getPrimaryPhoneNumber();
        PhoneNumber otherPN1 = customer.getOtherPhoneNumbers().get(0);
        PhoneNumber otherPN2 = customer.getOtherPhoneNumbers().get(1);
        PhoneNumber otherPN3 = customer.getOtherPhoneNumbers().get(2);
        System.out.println(primaryPN == otherPN2);
        System.out.println(otherPN1 == otherPN3);

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.setAdapter(new PhoneNumberAdapter());
        marshaller.marshal(customer, System.out);
    }

}

Output

Below is the output from running the demo code:

true
true
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<customer>
    <primary-phone-number id="B">555-BBBB</primary-phone-number>
    <other-phone-number id="A">555-AAAA</other-phone-number>
    <other-phone-number reference="B"/>
    <other-phone-number reference="A"/>
</customer>

Further Reading

If you enjoyed this post, then you may also be interested in:

8 comments:

  1. Hi Blaise,

    Below is the scenario :

    Node A--List(Node B, Node C)
    Node B--List(Node A, Node C)
    Node C--List(Node A, Node B)

    During the marshaling of any object give me error " Cyclic graph detected ..." .

    Is the above approach mentioned, will work.However i tried the same above tutorial but got an output as

    false
    false


    555-BBBB
    555-AAAA
    ...?
    ...?


    Seriously , don't know where i am wrong.

    Thanks
    A.Thakur

    ReplyDelete
  2. Hi Ankar (codeframe),

    I apologize for the delay in getting back to you. I was away on vacation with only sporadic internet access. If you are using EclipseLink JAXB (MOXy) then you may find the @XmlInverseReference extension useful for mapping bidirectional relationships:
    - JPA Entities to XML - Bidirectional Relationships

    If you prefer to stick with the standard JAXB APIs you could try leveraging @XmlID/@XmlIDREF:
    - JAXB and Shared References: @XmlID and @XmlIDREF

    I have also sent you my email address if you want to provide additional details.

    -Blaise

    ReplyDelete
  3. Hi Blaise,
    How to achieve the same thing using Moxy? XMLMarshaller doesn't take adapters, but only marshal listener.

    ReplyDelete
    Replies
    1. I recommend interacting with MOXy via the JAXB APIs (see: Specifying EclipseLink MOXy as Your JAXB Provider). If you need to use the MOXy's native APIs please message me through my contact page.

      Delete
  4. If there are many entities where we would like to marshal the first occurrence of the object as containment and all subsequent occurrences as a reference, would we need to write adapters for every entity. Is there a generic way of doing this?
    Tried @XmlInverseReference for bidirectional relationships, but it does not work when the relationship goes beyond 2 entities. Example - A -> B -> C -> D -> A. We have @XmlInverseReference set between A and B and @XmlInverseReference set between D and A. But still marshalling shows cycle detected error.

    Any solution?

    ReplyDelete
    Replies
    1. @XmlInverseReference is just for bidirectional relationships. There currently isn't a generic way to do this, you would need to have an XmlAdapter per class.

      Delete
  5. Can you suggest me how to solve the below problem.
    http://stackoverflow.com/questions/19834756/jaxb-unmarshalling-with-dynamic-elements

    ReplyDelete