users@jersey.java.net

Re: [Jersey] Chaining MessageBodyWriters?

From: Marc Hadley <marc.hadley_at_oracle.com>
Date: Tue, 13 Apr 2010 09:51:07 -0400

On Apr 13, 2010, at 9:38 AM, Laird Nelson wrote:

> Hello; forgive me for what might be an easily-answered question (though I did not find such an answer in the specification).
>
> Is there a way, from within a MessageBodyWriter implementation, to toss control back to the default, Jersey-provided MessageBodyWriters?
>
You can use an injected Providers instance to lookup installed writers:

https://jsr311.dev.java.net/nonav/releases/1.0/javax/ws/rs/ext/Providers.html

> My broader question: I would like to have my resource class return an object, say, a Foo. I then need to wrap that Foo inside another kind of object, Bar, whose sole purpose is to augment the response payload with metadata (such as number of records returned, the original request URI, etc. I don't want to pollute Foo with this information. Nor, ideally, do I want to pollute my resource class with this kind of information, as Bar is really there only to support a particular kind of caller.
>
> My thought was, write a MessageBodyWriter that takes in a Foo, wraps it in a Bar, and then--and here's my question--hands control back to Jersey to say, here, pretend you got a Bar back instead and go marshal it in the normal way you ordinarily would.
>
> What's the best approach to use here? I'm looking, I guess, for the equivalent of a servlet Filter in the JAX-RS world.
>
> One approach that occurs to me is, within my MessageBodyWriter, to take in the Foo, wrap it in a Bar, and then call the JAXB marshaling logic myself: get a Marshaller and marshal the Bar to the MessageBodyWriter's OutputStream. But I'd rather not own this process myself.
>
No need, just use Providers as shown above to get the default JAXB writer and call it from your writer once you've wrapped the Foo with the Bar.

Marc.