Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add custom HTTP Header to JAX-RS response?

Tags:

apache

jax-rs

cxf

I'm trying to add custom HTTP header to response in Apache CXF. I need to count MD5 from content and add it as a HTTP header. I tried to use ResponseHandler or Interceptor. My last try was

@Component
public class ResponseBPAuthFilter extends AbstractOutDatabindingInterceptor {


   public ResponseBPAuthFilter() {
       super(Phase.MARSHAL_ENDING);
   }


   @Override
   public void handleMessage(Message t) throws Fault {

       Map headers = CastUtils.cast((Map)t.get(Message.PROTOCOL_HEADERS));
       headers.put("Some-Header", Arrays.asList("test"));

   }

}

but it does nothing.

like image 300
Piotr Gwiazda Avatar asked Jul 02 '10 12:07

Piotr Gwiazda


2 Answers

Try to add Response Object as your return value where you can set Headers..

Response.ok(/* some entity */).header("CustomHeader", "CustomValue").build();

You don't need to use interceptors

like image 115
Rajesh Kumar J Avatar answered Sep 21 '22 11:09

Rajesh Kumar J


It sounds like you can accomplish this using the CXF CachedOutputStream.

public class MD5OutInterceptor extends AbstractPhaseInterceptor<Message> {

    public MD5OutInterceptor () {
        super(Phase.MARSHAL);
    }

    public final void handleMessage(Message message) {


        OutputStream os = message.getContent(OutputStream.class);
        if (os == null) {
            return;
        }

        final CachedOutputStream cos = new CachedOutputStream(os);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        cos.writeCacheTo(baos);

        // calculate MD5
        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] mdBytes = md.digest(baos);

        MultivaluedMap<String, Object> headers = (MetadataMap<String, Object>) message.get(Message.PROTOCOL_HEADERS);

        if (headers == null) {
            headers = new MetadataMap<String, Object>();
        }             

        headers.add("MD5-Header", new String(mdBytes));
        message.put(Message.PROTOCOL_HEADERS, headers);
    }
}

Don't forget to configure your interceptor in the cxf configuration file:

<jaxrs:server>
    <jaxrs:outInterceptors>
        <ref bean="md5OutInterceptor">
    </jaxrs:outInterceptors>
</jaxrs:server>

<bean id="md5OutInterceptor" class="com.whatever.MD5OutInterceptor" />
like image 25
superdave Avatar answered Sep 17 '22 11:09

superdave