Spring integration move file after processing
Asked Answered
A

1

2

How to move a file after processing in spring integration after processing file ..? I have followed http://xpadro.blogspot.com/2016/07/spring-integration-polling-file.html to implement the file polling , but I need to add onSuccess and OnError transnational events (with out XML configurations)

Alti answered 16/11, 2016 at 5:57 Comment(0)
S
7

I am not sure what you mean by "transaction", file systems are generally not transactional, but you can add an advice to the final consumer in the flow...

@SpringBootApplication
public class So40625031Application {

    public static void main(String[] args) {
        SpringApplication.run(So40625031Application.class, args);
    }

    @Bean
    public IntegrationFlow flow() {
        return IntegrationFlows.from(
                    Files.inboundAdapter(new File("/tmp/foo")), e -> e.poller(Pollers.fixedDelay(1000)))
                .transform(Transformers.fileToString())
                .handle("processor", "process", e -> e.advice(advice()))
                .get();
    }

    @Bean
    public Processor processor() {
        return new Processor();
    }

    @Bean
    public AbstractRequestHandlerAdvice advice() {
        return new AbstractRequestHandlerAdvice() {

            @Override
            protected Object doInvoke(ExecutionCallback callback, Object target, Message<?> message) throws Exception {
                File file = message.getHeaders().get(FileHeaders.ORIGINAL_FILE, File.class);
                try {
                    Object result = callback.execute();
                    file.renameTo(new File("/tmp/bar", file.getName()));
                    System.out.println("File renamed after success");
                    return result;
                }
                catch (Exception e) {
                    file.renameTo(new File("/tmp/baz", file.getName()));
                    System.out.println("File renamed after failure");
                    throw e;
                }
            }
        };
    }

    public static class Processor {

        public void process(String in) {
            System.out.println(in);
        }

    }

}
Sharleensharlene answered 16/11, 2016 at 13:51 Comment(3)
This exactly what I am looking for . Thank you for the solution.Alti
It didn't work when I replaced Transformers.fileToString() with Transformers.fromJson(My.class) in order to read directly a JSON object from a file. The JSON transformer lost the file name header. Added .enrichHeaders(h -> h.headerExpression(FileHeaders.ORIGINAL_FILE, "payload")) just after from(Files...) to make it work.Fuji
This is awesome. ThanksMylor

© 2022 - 2024 — McMap. All rights reserved.