2

I have REST services that respond with unmarshalled domain entities. For example:

Request:
GET http://someAddress.com/customer/001

Response:
<customer>
    <id>001</id>
    <name>Some Guy</name>
    ...
</customer>

I would like to add some links to the response for discovering services. For example:

<customer>
    <id>001</id>
    <name>Some Guy</name>
    ...
    <link xml:link="delete" href="http://someAddress.com/customer/001"/>
</customer>

The concern I have is if this will cause marshalling problems. I want the links discoverable, but I want consumers to use the domain schema easily, which does not contain elements for links.

Is it better to put the links elsewhere in the reply? If so, where?

TERACytE
  • 7,553
  • 13
  • 75
  • 111

2 Answers2

1

Assuming you are using JAXB for the object-to-XML layer you could do something like the following with an XmlAdapter, but instead of a String you will need an object for Link:

import java.net.HttpURLConnection;
import java.net.URL;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.annotation.adapters.XmlAdapter;

public class CustomerAdapter  extends XmlAdapter<String, Customer>{

    private JAXBContext jaxbContext;

    public CustomerAdapter() {
        try {
            jaxbContext = JAXBContext.newInstance(Customer.class);
        } catch(JAXBException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public String marshal(Customer v) throws Exception {
        if(null == v) {
            return null;
        }
        return "http://someAddress.com/customer/" + v.getId();
    }

    @Override
    public Customer unmarshal(String v) throws Exception {
        if(null == v) {
            return null;
        }

        URL url = new URL(v);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.setRequestProperty("Accept", "application/xml");

        Customer customer = (Customer) jaxbContext.createUnmarshaller().unmarshal(connection.getInputStream());
        connection.disconnect();
        return product;
    }

}

For more information on XmlAdapter see:

bdoughan
  • 147,609
  • 23
  • 300
  • 400
0

If you really don't want to change your schemas to support the link element then you could use Link headers. https://www.rfc-editor.org/rfc/rfc5988

Community
  • 1
  • 1
Darrel Miller
  • 139,164
  • 32
  • 194
  • 243