users@jersey.java.net

[Jersey] Re: How to intercept response and get original entitiy object?

From: <marceloverdijk_at_gmail.com>
Date: Thu, 22 Aug 2013 19:38:12 +0000 (UTC)

I ended up using a ContainerResponseFilter to also set response status.
I'm posting it below so other may benefit from it.


public class SuppressResponseCodesContainerResponseFilter implements
ContainerResponseFilter {

    @Override
    public void filter(ContainerRequestContext requestContext,
ContainerResponseContext responseContext) throws IOException {
        UriInfo uriInfo = requestContext.getUriInfo();
        MultivaluedMap<String, String> queryParameters =
uriInfo.getQueryParameters();
        List<String> queryParameter =
queryParameters.get("suppress_response_codes");
        boolean suppressResponseCodes = (queryParameter != null &&
!queryParameter.isEmpty()) ? new Boolean(queryParameter.get(0)) :
false;
        if (suppressResponseCodes) {
            if
(JsonValue.class.isAssignableFrom(responseContext.getEntityClass())) {
                JsonValue entity = (JsonValue)
responseContext.getEntity();
                JsonObject json = Json.createObjectBuilder()
                      .add("status", responseContext.getStatus())
                      .add("response", (JsonValue) entity)
                      .build();
               
responseContext.setStatus(Response.Status.OK.getStatusCode());
                responseContext.setEntity(json);
            }
        }
    }
}