users@jersey.java.net

[Jersey] Re: Overriding MediaType when using JAXB XML

From: John Lister <john.lister_at_kickstone.com>
Date: Tue, 20 Mar 2012 08:46:43 +0000

On 19/03/2012 10:07, George Sapountzis wrote:
> On Mon, Mar 19, 2012 at 3:40 AM, Graham Leggett<minfrin_at_sharp.fm> wrote:
>> I have a jersey method that returns a JAXB object, which when rendered as application/xml works fine:
>>
>> return Response.ok(plist).type("application/xml").build();
>>
>> The problem I have is that I need to override the MIME type for the application - the content is still expected to be valid XML, but the MIME type needs to be changed to "application/x-foo" (I can't change this MIME type).
>>
>> return Response.ok(plist).type("application/x-foo").build();
>>
>> This fails with the following exception:
>>
>> javax.ws.rs.WebApplicationException: com.sun.jersey.api.MessageException: A message body writer for Java class org.foo.Plist, and Java type class org.foo.Plist, and MIME media type application/x-foo was not found.
>>
>> Why the error is happening is understood - jersey is no longer recognising the JAXB object as XML, and so doesn't know what to do with it.
>>
>> My problem is that I don't know the recommended way to fix this problem - I want the JAXB to still be rendered as XML, I just want to have a MIME type that I specify. Can jersey do this, and if so, how?
>>
> I don't know what's the recommended way either, but one idea it to
> write a little wrapper around the stock XML MBW. Either extend it and
> add the appropriate @Produces annotations or write a little adapter
> MBW and delegate to it.
I would create a producer that returns your mime type, within that you
need to use the JAXB stuff to generate xml from your object and stream
it out. I've done a similar thing with JSON, IIRC there should be a
default JAXB producer for xml which you can probably get away with just
modifyng the mime type. Make sure the producer class is visible to
jersey as well as your resources (check the logs to see it has loaded)
and it should work.

John

-- 
www.pricegoblin.co.uk