2

I have a JAX-RS web service (Jersey) that uses Eclipselink (MOXy to access some records in a DB then marshall those to XML and send back to the user in the response to the request.

The problem that I have is that the user wants a different format to the one that is being produced i.e. apply an XSLT to transform the XML before returning.

I've found this example of using XSLT with JAXB - http://blog.bdoughan.com/2012/11/using-jaxb-with-xslt-to-produce-html.html

It looks useful, but I can't see where I would intercept the XML in order to apply the XSLT before it's sent back to the user.

Adam Rice
  • 880
  • 8
  • 20

1 Answers1

1

I would implement a MessageBodyWriter for this use case. In this implementation in the writeTo method the XSLT style sheet would be applied to the JAXB model to produce the desired XML:

public void writeTo(Object object, Class<?> type, Type genericType,
    Annotation[] annotations, MediaType mediaType,
    MultivaluedMap<String, Object> httpHeaders,
    OutputStream entityStream) throws IOException,
    WebApplicationException {
    try {
        ContextResolver<JAXBContext> resolver 
            = providers.getContextResolver(JAXBContext.class, mediaType);
        JAXBContext jaxbContext;
        if(null == resolver || null == (jaxbContext = resolver.getContext(type))) {
            jaxbContext = JAXBContext.newInstance(type);
        }
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer t = tf.newTransformer(xslt);
        JAXBSource source = new JAXBSource(jaxbContext, object);
        StreamResult result = new StreamResult(entityStream);
        t.transform(source, result);
    } catch(JAXBException jaxbException) {
        throw new WebApplicationException(jaxbException);
    }
}
bdoughan
  • 147,609
  • 23
  • 300
  • 400