Search code examples
javaspring-integrationspring-integration-dsl

How to keep only some message headers and remove all others?


How do I keep only specific headers but get rid of all other headers?

I'm trying to remove irrelevant headers that were set by an upstream HttpRequestHandlingMessagingGateway.

I tried specifying a handle() function that returns a new message containing only the headers I'm interested in but it does not seem to work. The log message contains a bunch of HTTP headers that were set from the upstream HttpRequestHandlingMessagingGateway.

IntegrationFlows.from(myChannel())
                // Strip off the HTTP specific headers
                .handle((payload, headers) -> MessageBuilder
                        .withPayload(payload)
                        .setHeader("myCustomHeader1", headers.get("myCustomHeader1", String.class))
                        .setHeader("myCustomHeader2", headers.get("myCustomHeader2", String.class))
                        .build()
                )
                .log()

I see there is a HeaderFilter but it requires you to know the name of the headers you want to remove. In my case I only want to keep 2 custom headers and remove everything else.


Solution

  • class HeaderStripper {
    
        public Message<?> strip(Message<?> msg) {
            return org.springframework.integration.support.MessageBuilder.withPayload(msg.getPayload())
                    .setHeader("foo", msg.getHeaders().get("foo"))
                    .setHeader("bar", msg.getHeaders().get("bar"))
                    .build();
        }
    
    }
    

    and then

    .transform(new HeaderStripper())