apache-camelcxfrs

How to set custom response header in CXF-RS Camel?


Currently I'm struggling to set one custom header in CXF-RS endpoint in camel. I wanted to set one header with name 'apps-client'. This response header will be used by the consumer of the rest endpoint.

I did try by adding DefaultCxfRsBinding class.

<camel:route id="cxf-restful-routes">
    <camel:from uri="cxfrs:bean:cxf.restful.endpoint?binding=#CXFRestfulBindings" />
    <camel:to uri="direct:postJson" />
</camel:route>

Is there any other way to set response header?

Appreciate for your help..!!


Solution

  • I'm able to set custom header in final response. I did via adding outInterceptor in CXFEndpoint. I have added AbstractPhaseInterceptor. First I have to set the header in CamelExchange in the camel route. Than I set the same to CXFExchange in #CXFRestfulBindings.populateCxfRsResponseFromExchange() by reading it from CamelExchange. Now, this header will be available in CXFExchange and one easily get it. I read this header in one of the interceptor which I have created by extending AbstractPhaseInterceptor. Than I have added this header in PROTOCOL_HEADERS map.

    Following is the code snippet,

    public class OutResponseInterceptor extends AbstractPhaseInterceptor<Message>{
    
        public RestResponseInterceptor(String phase) {
            super(Phase.MARSHAL);
        }
    
        @Override
        public void handleMessage(Message message) throws Fault {
            try {
                @SuppressWarnings("unchecked")
                MultivaluedMap<String, Object> headers = (MetadataMap<String, Object>) message.get(Message.PROTOCOL_HEADERS);
    
                if (headers == null) {
                    headers = new MetadataMap<String, Object>();
                }
    
                headers.putSingle("apps-client", (String) message.getExchange().get("apps-client"));
                message.put(Message.PROTOCOL_HEADERS, headers);
    
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    

    Thank you..!!