Search code examples
javaftpapache-camelcamel-ftp

Move files based on exception class to a different folder with camel


How to move a File in a FTP route to a different directory based on the error?

from("sftp://XXX@safsdf.de/dir/?delay=2s&move=done&moveFailed=failImport")
        .split()
        .body()
        .process(e -> {
            String fileName = (String) e.getIn().getHeader(Exchange.FILE_NAME);
             // do some magic which could throw a exception
        })
        .log("Imported file ${file:name} completely.");

Solution

  • It my be archived with a onException, try-catch-finally or Custom file processing strategy but none of it is really handy.

    I came up with this simple code:

    @Override
    public void configure() throws Exception {
        errorHandler(loggingErrorHandler(logger));
        from("sftp://XXX@safsdf.de/dir/?delay=2s&move=${in.header.outDirectory}&moveFailed=failImport")
                .process(exchange -> exchange.setProperty(originalMessage, exchange.getIn()))
                .split()
                .body()
                .process(e -> {
                    String fileName = (String) e.getIn().getHeader(Exchange.FILE_NAME);
                    Message origMsg = (Message) e.getProperty(originalMessage);
                    try {
                        // do what ever
                        origMsg.setHeader(outDirectory, "done/" + fileName);
                    } catch (KaboomException ex) {
                        origMsg.setHeader(outDirectory, "retry/" + fileName);
                    }
                })
                .log("Imported file ${file:name} completely.");
    
    }
    

    Its important to set the header on the original message.