0
点赞
收藏
分享

微信扫一扫

springintegration sftp gateway move file and then process

知年_7740 2024-09-03 阅读 16

@Configuration
@EnableIntegration
public class SftpIntegrationConfig {

    @Bean
    public SessionFactory<LsEntry> sftpSessionFactory() {
        DefaultSftpSessionFactory factory = new DefaultSftpSessionFactory(true);
        factory.setHost("sftp.server.com");
        factory.setPort(22);
        factory.setUser("username");
        factory.setPassword("password");
        factory.setAllowUnknownKeys(true);
        return new CachingSessionFactory<>(factory);
    }

    @Bean
    public IntegrationFlow sftpInboundFlow() {
        return IntegrationFlows.from(
                Sftp.inboundAdapter(sftpSessionFactory())
                    .preserveTimestamp(true)
                    .remoteDirectory("remote/dir")
                    .localDirectory(new File("local/dir"))
                    .autoCreateLocalDirectory(true)
                    .localFilter(new AcceptOnceFileListFilter<>())
                    .deleteRemoteFiles(false),  // Set to false to keep the remote file after downloading
                e -> e.poller(Pollers.fixedDelay(5000)))
            .transform(Transformers.fileToString())
            .channel("fileInputChannel")  // Send the file content to the fileInputChannel
            .get();
    }

    @Bean
    public IntegrationFlow moveAndProcessFlow() {
        return IntegrationFlows.from("fileInputChannel")
            .handle(Sftp.outboundGateway(sftpSessionFactory(),
                    Command.MV, "headers['file_remoteDirectory'] + '/' + headers['file_remoteFile']")
                .renameExpression("headers['file_rename_to']")
                .options(Option.RECURSIVE)
                .temporaryFileSuffix(".writing"),
                e -> e.advice(expressionAdvice()))
            .handle("fileProcessor", "processFile")
            .get();
    }

    @Bean
    public ExpressionEvaluatingRequestHandlerAdvice expressionAdvice() {
        ExpressionEvaluatingRequestHandlerAdvice advice = new ExpressionEvaluatingRequestHandlerAdvice();
        advice.setSuccessChannelName("moveAndProcessChannel");
        advice.setOnSuccessExpressionString("headers['file_originalFile'] + ' was successfully moved and processed'");
        return advice;
    }

    @Bean
    public MessageChannel fileInputChannel() {
        return new DirectChannel();
    }

    @Bean
    public MessageChannel moveAndProcessChannel() {
        return new DirectChannel();
    }

    @Bean
    public MessageHandler fileProcessor() {
        return new MessageHandler() {
            @Override
            public void handleMessage(Message<?> message) throws MessagingException {
                String fileContent = (String) message.getPayload();
                System.out.println("Processing file content: " + fileContent);
                // Process the file content here
            }
        };
    }
}

举报

相关推荐

0 条评论