Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JBoss7 setting Cache-Control, Pragma to no-cache for all responses from RESTEasy

I'm trying to add Cache-Control headers to the responses generated in JBoss 7 using the RESTEasy framework. However, all the responses end up getting multiple Cache-Control headers due to JBoss adding a no-cache header by default.

I can't find any setting to remove it and adding interceptors is also not working since a no-cache header is being added later.

Can someone tell me how to disable the default pragma and cache-control headers in JBoss 7?

Note: I'm using resteasy with Stateless EJBs.

@Path("/api")
@Local
public interface UCSRestServiceInterface
{
    @GET
    @Path("/token")
    @Produces("application/json")
    @Cache(maxAge = 3600, noTransform = true)
    public Response getToken();
}

Getting the response headers as,

{
  "pragma": "No-cache",
  "date": "Thu, 11 Feb 2016 20:16:30 GMT",
  "content-encoding": "gzip",
  "server": "Apache-Coyote/1.1",
  "x-frame-options": "SAMEORIGIN",
  "vary": "Accept-Encoding,User-Agent",
  "content-type": "application/json",
  "cache-control": "no-cache, no-transform, max-age=3600",
  "transfer-encoding": "chunked",
  "connection": "Keep-Alive",
  "keep-alive": "timeout=15, max=100",
  "expires": "Wed, 31 Dec 1969 19:00:00 EST"
}
like image 778
Gary Avatar asked Jan 30 '16 02:01

Gary


1 Answers

A Filter resource in a web-app basically lets you intercept requests and response and mainly designed for some use cases which work by altering request/response headers. More details here

Since you are using RESTEasy you can make use of ContainerResponseFilter; a filter interface provided by JAX-RS. You can write your custom filter by implementing this interface. The filter class(add one to your web app source code) will look like below:-

@Provider
public class YourCustomFilter implements ContainerResponseFilter{

// you can check the actual string value by using method "getStringHeaders" on 'resp' below
private static final String CACHE_CONTROL = "cache-control";

@Override
public void filter(ContainerRequestContext req,
        ContainerResponseContext resp) throws IOException {

    if(resp.getHeaders().containsKey(CACHE_CONTROL)){
       resp.getHeaders().remove(CACHE_CONTROL);
       resp.getHeaders().add(CACHE_CONTROL, "no-transform, max-age=3600");
    }
    resp.getHeaders().add(CACHE_CONTROL, "no-transform, max-age=3600");

  }

}

Here you basically check for the prescense of Cache-Control header and if present remove the existing one and add one of your own. Please dont forget the @Provider annotation which is needed by the jax rs runtime to discover your custom filter.

Note that with this filter all requests to your webapp will be intercepted. If you want a certain resource or a resource method to be intercepted you can explore the use of @NameBinding

Let me know if that works.

like image 52
M.. Avatar answered Oct 06 '22 16:10

M..