Interlated
Interlated

Reputation: 5926

Java Spring SFTP connections not reconnecting?

Spring SFTP is setup with the following configuration. In some environments, it works on startup up but subsequent copies fail after 15 minutes of waiting with a 'connection timed out' error message.

The copy will work again 'most of the time' if it is rerun.

The configuration

 /**
 * Create a SFTP session factory.
 */
@Bean
public SessionFactory<ChannelSftp.LsEntry> sftpSessionFactory() {
    // TODO check isSharedSession
    DefaultSftpSessionFactory factory = new DefaultSftpSessionFactory(false);
    factory.setHost(host);
    factory.setPort(port);
    factory.setUser(user);
    if (privateKey != null) {
        factory.setPrivateKey(privateKey);
        factory.setPrivateKeyPassphrase(keyPhrase);
    } else {
        factory.setPassword(password);
    }
    factory.setAllowUnknownKeys(allowUnknownKeys);
    return new CachingSessionFactory<ChannelSftp.LsEntry>(factory);

}

The remote file template is used so that we can set the name on the remote server. Yes Spring SFTP does rename the file on the remote server as well. It might be possible to use the 'gateway' if renamed the file first.

 @SuppressWarnings("unchecked")
public void send(File sourceFilePath, File intermediateFileName, File destinationFileName, String remoteDirectory) throws PaymentsPlusSystemException {
    SftpRemoteFileTemplate sftpRemoteFileTemplate = new SftpRemoteFileTemplate(sftpSessionFactory);

    sftpRemoteFileTemplate.setAutoCreateDirectory(Boolean.TRUE);
    sftpRemoteFileTemplate.setRemoteDirectoryExpression(new LiteralExpression(remoteDirectory));
    sftpRemoteFileTemplate.setBeanFactory(context);
    try {
        sftpRemoteFileTemplate.afterPropertiesSet();
        sftpRemoteFileTemplate.send(new GenericMessage<Object>(sourceFilePath));
        String intermediateFileFull = remoteDirectory + "/" + intermediateFileName.getPath();
        String destinationFileFull = remoteDirectory + "/" + destinationFileName.getPath();
        sftpRemoteFileTemplate.rename(intermediateFileFull, destinationFileFull);
    } catch (Exception e) {
        throw new CopySystemException(String.format("Refund batch. Copying files. Failed to send file. %s. %s", e.getLocalizedMessage(), e.getClass().getName()), e);
    }
}

Upvotes: 0

Views: 866

Answers (1)

Interlated
Interlated

Reputation: 5926

The firewall in the environment causing the problem was dropping the long-running 'cached' session. It seems that it was just dropped and the SFTP connection didn't check that the connection was still active.

The fix is to remove the caching session factory. The impact of this is that the copy process logs in after every operation. For example, log in and make directory. Log in again and copy the file.

Upvotes: 1

Related Questions