Search code examples
javaspring-bootspring-integration

Dinamically param uri change in outbound gateway HttpRequestExecutingMessageHandler


I'm triggering an outbound gateway inside a for cycle. The iteration is in a range of dates and my purpose is to dinamically change the uri's param with the date in the current iteration.

My iteration:

void startIteration(LocalDate from, LocalDate to) {
    for (LocalDate date = from; date.isBefore(to); date = date.plusDays(1)) {
          produceHttpCall(date); // date is the param i want to change in each http call
    }
}

Here is the method triggering the http call:

public void produceHttpCall(LocalDate param) {

    MessageChannel gateway = context.getBean("gatewayChannel", DirectChannel.class);
    gateway.send(new GenericMessage<>("")); // should i pass it in some way as payload  ?
}

The Outbound Gateway component:

@ServiceActivator(inputChannel = "gatewayChannel")
@Bean
public HttpRequestExecutingMessageHandler outBoundGatewayCall(@Value("${ws.uri}") String uri) {
    HttpRequestExecutingMessageHandler handler = new HttpRequestExecutingMessageHandler(uri + **date param**);
    handler.setHttpMethod(HttpMethod.GET);
    handler.setExpectedResponseType(String.class);
    handler.setOutputChannel(myOutputChannel());
    return handler;
}

I'm reading something about Outbound Gateway that says the component is establishing the connection once during context initialization but i don't want to believe that it does not exist a way to change the date uri param for each iteration. Thanks for your help


Solution

  • See documentation: https://docs.spring.io/spring-integration/docs/current/reference/html/http.html#mapping-uri-variables.

    So, your URI for that HTTP Outbound Gateway may have a variable, something like https://foo.host/bars/{date}. Then you add:

    handler.setUriVariableExpressions(Map.of("date", new FunctionExpression<Message<?>>(m -> m.getPayload())));
    

    And pass your date as a payload of that message you send to the gatewayChannel.