Search code examples
springspring-integration

SftpOutboundGateway - pass localDirectory dynamically


I have the below code snippet to download a file from a remote server. I would like to update it to be more generic, so a directory where the file should be downloaded (localDirectory) could be passed as a parameter. Is it possible to somehow update the gateway's method or extend the handler to configure it?

    @Bean
    @ServiceActivator(inputChannel = "channel")
    public MessageHandler handler() {
        SftpOutboundGateway handler = new SftpOutboundGateway(sftpSessionFactory(), "get", "payload");
        handler.setLocalDirectory("/folder"); //can this be pointed dynamically when downloading a file?
        return handler;
    }

    @MessagingGateway
    public interface TestGateway{
         @Gateway(requestChannel = "channel")
         File getFile(String filePath);
    }

Solution

  • For that purpose we suggest a SpEL-based options to evaluate a value from request message a runtime. See this one for your use-case:

    /**
     * Specify a SpEL expression to evaluate the directory path to which remote files will
     * be transferred.
     * @param localDirectoryExpression the SpEL to determine the local directory.
     * @since 5.0
     */
    public void setLocalDirectoryExpressionString(String localDirectoryExpression) {
    

    So, this one can be configured in your gateway like this:

    handler.setLocalDirectoryExpressionString("headers.my_local_directory");
    

    There is also a #remoteDirectory SpEL variable in present in the EvaluationContext for your convenience.

    See more info in docs:

    https://docs.spring.io/spring-integration/reference/html/spel.html#spel