Links: Table of Contents | Single HTML

Chapter 4. XML Support

Table of Contents

4.1. Low level XML support
4.2. Getting started with JAXB
4.3. POJOs
4.4. Using custom JAXBContext

As you probably already know, Jersey uses MessageBodyWriters and MessageBodyReaders to parse incoming request and create outgoing responses. Every user can create its own representation but... this is not recommended way how to do things. XML is proven standard for interchanging information, especially in web services. Jerseys supports low level data types used for direct manipulation and JAXB XML entities.

4.1. Low level XML support

Jersey currently support several low level data types: StreamSource, SAXSource, DOMSource and Document. You can use these types as return type or method (resource) parameter. Lets say we want to test this feature and we have helloworld sample as starting point. All we need to do is add methods (resources) which consumes and produces XML and types mentioned above will be used.

Example 4.1. Low level XML test - methods added to HelloWorldResource.java

  1     @Path("1")
  2     @POST
  3     public StreamSource get1(StreamSource streamSource) {
  4         return streamSource;
  5     }
  6 
  7     @Path("2")
  8     @POST
  9     public SAXSource get2(SAXSource saxSource) {
 10         return saxSource;
 11     }
 12 
 13     @Path("3")
 14     @POST
 15     public DOMSource get3(DOMSource domSource) {
 16         return domSource;
 17     }
 18 
 19     @Path("4")
 20     @POST
 21     public Document get4(Document document) {
 22         return document;
 23     }

Both MessageBodyReaders and MessageBodyWriters are used in this case, all we need is do POST request with some XML document as a request entity. I want to keep this as simple as possible so I'm going to send only root element with no content: "<test />". You can create Jersey client to do that or use some other tool, for example curl as I did. (curl -v http://localhost:9998/helloworld/1 -d "<test />"). You should get exactly same XML from our service as is present in the request; in this case, XML headers are added to response but content stays. Feel free to iterate through all resources.

4.2. Getting started with JAXB

Good start for people which already have some experience with JAXB annotations is JAXB sample. You can see various usecases there. This text is mainly meant for those who don't have prior experience with JAXB. Don't expect that all possible annotations and their combinations will be covered in this chapter, JAXB (JSR 222 implementation) is pretty complex and comprehensive. But if you just want to know how you can interchange XML messages with your REST service, you are looking at right chapter.

Lets start with simple example. Lets say we have class Planet and service which produces "Planets"

Example 4.2. Planet class

  1 @XmlRootElement
  2 public class Planet {
  3     public int id;
  4     public String name;
  5     public double radius;
  6 }
  7             

Example 4.3. Resource class

  1 @Path("planet")
  2 public class Resource {
  3 
  4     @GET
  5     @Produces(MediaType.APPLICATION_XML)
  6     public Planet getPlanet() {
  7         Planet p = new Planet();
  8         p.id = 1;
  9         p.name = "Earth";
 10         p.radius = 1.0;
 11 
 12         return p;
 13     }
 14 }            

You can see there is some extra annotation declared on Planet class. Concretely XmlRootelement. What it does? This is a JAXB annotation which maps java class to XML element. We don't need specify anything else, because Planet is very simple class and all fields are public. In this case, XML element name will be derived from class name or you can set name property: @XmlRootElement(name="yourName").

Our resource class will respond to GET /planet with

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
                <planet>
                        <id>1</id>
                        <name>Earth</name>
                        <radius>1.0</radius>
                </planet>
            

which might be exactly what we want... or not. Or we might not really care, because we can use Jersey client for making requests to this resource and this is easy as: Planet planet = webResource.path("planet").accept(MediaType.APPLICATION_XML_TYPE).get(Planet.class);. There is pre-created WebResource object which points to our applications context root and we simpli add path (in our clase its "planet"), accept header (not mandatory, but service could provide different content based on this header; for example text/html can be served for web browsers) and at the end we specify that we are expecting Planet class via GET request.

There may be need for not just producing XML, we might want to consume it as well.

Example 4.4. Method for consuming Planet

  1     @POST
  2     @Consumes(MediaType.APPLICATION_XML)
  3     public void setPlanet(Planet p) {
  4         System.out.println("setPlanet " + p);
  5     }
  6                     


After valid request is made (with Jersey client you can do webResource.path("planet").post(p);), service will print out string representation of Planet, which can look like Planet{id=2, name='Mars', radius=1.51}.

If there is a need for some other (non default) XML representation, other JAXB annotations would need to be used. This process is usually simplified by generating java source from XML Schema which is done by xjc. Xjc is XML to java compiler and is part of JAXB. See JAXB home page for further details.

4.3. POJOs

Sometimes you can't / don't want to add JAXB annotations to source code and you still want to have resources consuming and producing XML representation of your classes. In this case, JAXBElement class should help you. Let's redo planet resource but this time we won't have XmlRootElement annotation on Planet class.

Example 4.5. Resource class - JAXBElement

  1 @Path("planet")
  2 public class Resource {
  3 
  4     @GET
  5     @Produces(MediaType.APPLICATION_XML)
  6     public JAXBElement<Planet> getPlanet() {
  7         Planet p = new Planet();
  8         p.id = 1;
  9         p.name = "Earth";
 10         p.radius = 1.0;
 11 
 12         return new JAXBElement<Planet>(new QName("planet"), Planet.class, p);
 13     }
 14 
 15     @POST
 16     @Consumes(MediaType.APPLICATION_XML)
 17     public void setPlanet(JAXBElement<Planet> p) {
 18         System.out.println("setPlanet " + p.getValue());
 19     }
 20 }            

As you can see, everything is little more complicated with JAXBElement. This is because now you need to explicitly set element name for Planet class XML representation. Client side is even more ugly than server side because you can't do JAXBElement<Planet>.class so Jersey client API provides way how to workaround it by declaring subclass of GenericType.

Example 4.6. Client side - JAXBElement

  1         // GET
  2         GenericType<JAXBElement<Planet>> planetType = new GenericType<JAXBElement<Planet>>() {};
  3 
  4         Planet planet = (Planet) webResource.path("planet").accept(MediaType.APPLICATION_XML_TYPE).get(planetType).getValue();
  5         System.out.println("### " + planet);
  6 
  7         // POST
  8         Planet p = new Planet();
  9         // ...
 10 
 11         webResource.path("planet").post(new JAXBElement<Planet>(new QName("planet"), Planet.class, p));           

4.4. Using custom JAXBContext

In some scenarios you can take advantage of using custom JAXBContext. Creating JAXBContext is expensive operation and if you already have one created, same instance can be used by Jersey. Other possible usecase for this is when you need to set some specific things to JAXBContext, for example set different classloader.

Example 4.7. PlanetJAXBContextProvider

  1 @Provider
  2 public class PlanetJAXBContextProvider implements ContextResolver<JAXBContext> {
  3     private JAXBContext context = null;
  4 
  5     public JAXBContext getContext(Class<?> type) {
  6         if(type != Planet.class)
  7             return null; // we don't support nothing else than Planet
  8 
  9         if(context == null) {
 10             try {
 11                 context = JAXBContext.newInstance(Planet.class);
 12             } catch (JAXBException e) {
 13                 // log warning/error; null will be returned which indicates that this
 14                 // provider won't/can't be used.
 15             }
 16         }
 17         return context;
 18     }
 19 }
 20         

Sample above shows simple JAXBContext creation, all you need to do is put this @Provider annotated class somewhere where Jersey can find it. Users sometimes have problems with using provider classes on client side, so just for reminder - you have to declare them in client config (cliend does not anything like package scanning done by server).

Example 4.8. Using Provider with Jersey client

  1                 ClientConfig cc = new DefaultClientConfig();
  2                 cc.getClasses().add(PlanetJAXBContextProvider.class);
  3                 Client c = Client.create(cc);
  4