Download a single file via FTP with Spring Integration

Viewed 10908

I was reading through the Spring Integration Documentation thinking that a file download would be pretty simple to implement. Instead, the article provided me with many different components that seem to over-qualify my needs:

The FTP Inbound Channel Adapter is a special listener that will connect to the FTP server and will listen for the remote directory events (e.g., new file created) at which point it will initiate a file transfer.

The streaming inbound channel adapter produces message with payloads of type InputStream, allowing files to be fetched without writing to the local file system.

Let's say I have a SessionFactory declared as follows:

@Bean
public SessionFactory<FTPFile> ftpSessionFactory() {
    DefaultFtpSessionFactory sf = new DefaultFtpSessionFactory();
    sf.setHost("localhost");
    sf.setPort(20);
    sf.setUsername("foo");
    sf.setPassword("foo");
    return new CachingSessionFactory<>(sf);
}

How do I go from here to downloading a single file on a given URL?

3 Answers

To add to @garyrussell's answer:

In FTPS protocol, if you are behind a firewall, you will might encounter Host attempting data connection x.x.x.x is not the same as server y.y.y.y error (as described here). The reason is the FtpSession instance returned from DefaultFtpsSessionFactory by default does remote verification test, i.e. it runs in an "active" mode.

The solution is to disable this verification on the FtpSession instance by setting the "passive mode", when you create the DefaultFtpsSessionFactory.

DefaultFtpsSessionFactory defaultFtpsSessionFactory() {

        DefaultFtpsSessionFactory defaultFtpSessionFactory = new DefaultFtpsSessionFactory(){
            @Override
            public FtpSession getSession() {
                FtpSession ftpSession = super.getSession();
                ftpSession.getClientInstance().setRemoteVerificationEnabled(false);
                return ftpSession;
            }
        };
        defaultFtpSessionFactory.setHost("host");
        defaultFtpSessionFactory.setPort(xx);
        defaultFtpSessionFactory.setUsername("username");
        defaultFtpSessionFactory.setPassword("password");
        defaultFtpSessionFactory.setFileType(2); //binary data transfer

        return defaultFtpSessionFactory;
    }
Related