Feeding marshalled JAXB data to Jersey

Although Jersey supports eating JAXB’ed classes fine, sometimes you want to manually alter the data, such as including a processing instruction for XSL stylesheets. There probably should be a less verbose way to do this.

The object should be an @XMLRootElement annotated object.

public static StreamingOutput outputXMLwithXSL() {
  return new StreamingOutput() {
    public void write(OutputStream output) throws IOException,
    WebApplicationException {
      Object object = yourJAXBObject();

      JAXBContext jc = null;
      try { jc = JAXBContext.newInstance(object.getClass()); } 
      catch (JAXBException e) { e.printStackTrace(); }

      Marshaller m = null;
      try { m = jc.createMarshaller(); }
      catch (JAXBException e) { e.printStackTrace(); }

      PrintStream ps = new PrintStream(output);
      ps.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
      ps.println("<?xml-stylesheet type=\"text/xsl\" href=\"your.xsl\"?>"); 

      try { m.setProperty(Marshaller.JAXB_FRAGMENT, true); }
      catch (PropertyException e) { e.printStackTrace(); }

      try { m.marshal(object, output); }
      catch (JAXBException e) { e.printStackTrace(); }
Written by
Open Source software architect and technologist. He's just this guy, you know? Follow him him on Google+.
Published in
Transmissions from the Little Blue Marble

Published August 20th, 2009


Leave a Reply