On Dec 30, 2010, at 8:35 PM, zzantozz wrote:
>
> I'm puzzled by the lack of any mechanism in Jersey for applying a
> response
> filter after the marshalling of the response. In
> com
> .sun
> .jersey.server.impl.application.WebApplicationImpl._handleRequest(),
> all ContainerResponseFilters are applied before the call to
> ContainerResponse.write(). I can see the usefulness of this, but I
> really
> need an "around" filter or specific "before" and "after" filters here
> instead of just a "before". My specific case is a need for the
> open-session-in-view pattern in a Jersey app, but I'd think this
> would have
> more general uses, too.
>
Yes, the response filters are designed to modify the response
information before the response has been written, also the response
filter "stack" may be broken by a response filter throwing an
exception (which is then mapped to a response).
Do you need to return a response if the "after" processing fails?
> My problem in more detail: I can open a Session (Hibernate) in a
> ContainerRequestFilter for use by the application, but if I close it
> in a
> ContainerResponseFilter, then it's closed before the "view" is
> rendered
> (object is marshalled), and so there was no point in even opening it
> to
> begin with. The only other thing I've come up with is that I could
> perhaps
> use a ContainerResponseFilter to wrap the ContainerResponse's
> responseWriter
> with a ContainerResponseWriter whose finish() method would close the
> Session, but I haven't yet checked whether finish() is guaranteed to
> always
> be called.
>
> Any advice? Comments on my potential solution?
As currently implemented the finish() method is not guaranteed to
always be called. If an exception occurs in the process of writing out
the entity body when some bytes have already been written (i.e. the
response s committed) then finish() will not be called. Which i think
reflects a bug in the design as we need a way to report to the writer
that things failed so it can clean up if necessary.
Perhaps the CloseableService will work for you:
http://jersey.java.net/nonav/apidocs/latest/jersey/com/sun/jersey/spi/CloseableService.html
You can inject the CloseableService in your filter:
@Context CloseableService cs;
and then you can add an instance of Closeable. The close method of
those instances will be guaranteed to be called when the request goes
out of scope.
Paul.