Wednesday, September 14, 2011

Producing an HTML representation of an Atom feed with Java

Atom documents are XML documents structured according to the Atom Syndication specification. On Java, JAXB seems to be the recommended method to marshall Java object structures to XML streams. Together with a JAX-RS implementation for building RESTful web services, it can marshall and unmarshall between Atom XML documents and Java objects.

Lack of support in browsers

The content type of an Atom document is application/atom+xml, but most browsers seem to render Atom documents rather poorly. Some browsers pretend to be news aggregators, but on my quest for navigating my API all browsers come short. I've also got some resource representations of vendor specific types, take application/vnd.example+xml as an example. Trying to view content of this type, most browsers opens a "download file dialog" instead of displaying the XML structure. - I mean, come on, it's just XML!

Chrome has probably come closest to my needs with the plugin Advanced REST client Application. I want to follow the links of my Atom documents by clicking on links, for easy debugging and exploring of the API. This is where the Accept HTTP request header comes handy.

Browsers seem to favor text/html above all other content types, for humanly reasons. A simple XSL transformation from Atom documents to HTML might just do for now.

RESTeasy on JBoss

I use RESTeasy on JBoss 7 for my RESTful web-services to provide me with Atom XML document representations. It is possible to convert XML to HTML with an XSL stylesheet, either server side using XSLT in Java or on the client side by applying a xsl-stylesheet processing instruction to the XML document.

My attempt to add the xsl-stylesheet instruction failed, since the Atom JAXB provider doesn't support marshaller decorators using @XmlHeader and @Stylesheet annotations, like the regular JAXB provider in RESTeasy does.

JAX-RS allows a single resource to provide different representations based on request headers. Writing a MessageBodyWriter implementation to transform Atom XML from the Atom JAXB provider to text/html seemed like a good idea, but my attempt failed. My marshaller wasn't used at all. It seems that the JAXB provider grabs full control of output marshalling, but since JAXB does not support writing HTML it just fails miserably with an exception about not finding a ContextResolver for text/html.

Jackson did it, why can't I?

It might be possible to write a ContextResolver provider for the Atom Feed and Entry classes that can handle text/html. Maybe JAXB provider can utilize that to output HTML. My confidence in this is that the Jackson JSON Processor does the same. Looking forward till tomorrow.

No comments:

Post a Comment