Java Reference
In-Depth Information
public interface
interface WriterInterceptor
WriterInterceptor {
void aroundWriteTo ( WriterInterceptorContext context )
throws java . io . IOException , javax . ws . rs . WebApplicationException ;
These interceptors are only triggered when a MessageBodyReader or MessageBodyWriter is
needed to unmarshal or marshal a Java object to and from the HTTP message body. They
also are invoked in the same Java call stack. In other words, a ReaderInterceptor wraps
around the invocation of MessageBodyReader.readFrom() and a WriterInterceptor
wraps around the invocation of MessageBodyWWriter.writeTo() .
A simple example that illustrates these interfaces in action is adding compression to your in-
put and output streams through content encoding. While most JAX-RS implementations sup-
port GZIP encoding, let's look at how you might add support for it using a ReaderInter-
ceptor and WriterInterceptor :
public class
class GZIPEncoder
GZIPEncoder implements
implements WriterInterceptor {
public void
void aroundWriteTo ( WriterInterceptorContext ctx )
throws IOException , WebApplicationException {
GZIPOutputStream os = new
new GZIPOutputStream ( ctx . getOutputStream ());
ctx . getHeaders (). putSingle ( "Content-Encoding" , "gzip" );
ctx . setOutputStream ( os );
ctx . proceed ();
return ;
The WriterInterceptorContext parameter allows you to view and modify the HTTP
headers associated with this invocation. Since interceptors can be used on both the client and
server side, these headers represent either a client request or a server response. In the ex-
ample, our aroundWriteTo() method uses the WriterInterceptorContext to get and re-
place the OutputStream of the HTTP message body with a GZipOutputStream . We also use
it to add a Content-Encoding header. The call to WriterInterceptorContext.proceed()
will either invoke the next registered WriterInterceptor , or if there aren't any, invoke the
underlying MessageBodyWriter.writeTo() method.
Let's now implement the ReaderInterceptor counterpart to this encoding example:
public class
class GZIPDecoder
GZIPDecoder implements
implements ReaderInterceptor {
public Object aroundReadFrom ( ReaderInterceptorContext ctx )
Search WWH ::

Custom Search