Search code examples
spring-integrationspring-integration-http

Can I get original message after response


Can you help me with spring integration.

I have Integration flow for send post request to other system with http.

Can I get original message after sending it, because I wanna do other operations on success and error.

ErrorHandler just has HttpClientResponse, but response body is empty and I need originalMessage to handle this situation.

The same situation with success response. I don't have original message information to do next operation.

@Configuration
public class IntegrationConfiguration {

    @Bean
    public IntegrationFlow incChannel(HeaderEnricher enrichHeaders,
                                      HttpRequestExecutingMessageHandler notifyOnArrival) {
        return IntegrationFlows
                .from("send_notify_to")
                .transform(enrichHeaders)
                .handle(notifyOnArrival)
                .channel("save_success_status_original")
                .get();
    }

    @Bean
    public HeaderEnricher enrichHeaders() {
        Map<String, ? extends HeaderValueMessageProcessor<?>> headersToAdd =
                Collections.singletonMap("Content-Type", new StaticHeaderValueMessageProcessor<>(APPLICATION_JSON_VALUE));
        HeaderEnricher enricher = new HeaderEnricher(headersToAdd);
        return enricher;
    }

    @Bean
    HttpRequestExecutingMessageHandler notifyOnArrival(@Value("${uri}") String uri,
                                                          MappingJackson2HttpMessageConverter messageConverter) {

        HttpRequestExecutingMessageHandler handler =
                new HttpRequestExecutingMessageHandler(uri + "/api/notify");
        handler.setHttpMethod(HttpMethod.POST);
        handler.setExpectReply(false);
        handler.setMessageConverters(Arrays.asList(messageConverter));
        return handler;
    }

}

Solution

  • The .handle(notifyOnArrival) is just a Service Activator with all the state carrying from the request to reply. Only what we need is to ensure that we really provide that state. the best place to keep a state in the context of the message is to store the request message into headers and then restore it from there in the reply afterward or from the ErrorMessage.

    headersToAdd.put("originalMesasge", new ExpressionEvaluatingHeaderValueMessageProcessor("#root", Message.class));
    

    So, you add that originalMesasge from the request message and this one is going to be copying by the Service Activator logic into the reply message.