Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Injecting a custom response header in RESTEasy JAX-RS

I have RESTEasy (JAX-RS) server with about 60 services (so far). I would like to automatically inject a custom response header to provider callers with the server build time: X-BuildTime: 20100335.1130.

Is there an easy way to do this without modifying each of my services?

I am trying to use a class that implements org.jboss.resteasy.spi.interception.PostProcessInterceptor with annotations @Provider and @ServerInterceptor, but I can't figure out how to modify the ServerResponse that is passed into my postProcess() method.

like image 669
Ralph Avatar asked Mar 25 '11 15:03

Ralph


1 Answers

Although MessageBodyWriterInterceptor does the trick, it is better to use PostProcessInterceptor, as it will intercept responses that do not call MessageBodyWriters (such as Response.created(URI.create("/rest/justcreated")).build()).

For more info, see the official documentation.

import java.util.ArrayList;
import java.util.List;

import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.Provider;

import org.jboss.resteasy.annotations.interception.ServerInterceptor;
import org.jboss.resteasy.core.ServerResponse;
import org.jboss.resteasy.spi.interception.PostProcessInterceptor;

@Provider
@ServerInterceptor
public class MyPostProcessInterceptor implements PostProcessInterceptor {

    @Override
    public void postProcess(ServerResponse response) {
        MultivaluedMap<String, Object> headers = response.getMetadata();
        List<Object> domains = headers.get("X-BuildTime");
        if (domains == null) { domains = new ArrayList<Object>(); }
        domains.add("20100335.1130");
        headers.put("X-BuildTime", domains);
    }

}
like image 169
acdcjunior Avatar answered Sep 21 '22 05:09

acdcjunior