I have an application that needs to download files from sftp.
I’m currently using apache commons-vfs2
I have a scheduler that runs every 1 minute.
1. Get the list of files that’s on remote (open connection, get the list, then close connection)
2. Download the files from step 1 (open connection, download each files, then close connection)
How can I keep the connections to minimum?
Is there a way to limit how many connections I have with commons-vfs2?
Here is my code
private List<FileObject> getRemoteFilesList() throws FileSystemException {
FileObject[] remoteFiles;
try {
manager.init();
final @Cleanup FileObject remoteDirectoryObject = manager.resolveFile(uri, fileSystemOptions);
remoteFiles = remoteDirectoryObject.getChildren();
} finally {
manager.freeUnusedResources();
manager.close();
}
return Arrays.stream(remoteFiles)
.collect(Collectors.toList());
}
private List<File> downloadRemoteFiles(final List<FileObject> remoteFiles) {
if(remoteFiles.isEmpty()) {
return Collections.emptyList();
}
final List<File> myCollection = new ArrayList<>();
try {
manager.init();
for (final FileObject myfile : remoteFiles) {
final File localFile = downloadFile(myfile);
myCollection.add(localFile);
myfile.delete();
}
} catch (final IOException exception) {
log.warn("Unable to download because ", exception);
} finally {
manager.freeUnusedResources();
manager.close();
}
return myCollection;
}
2
Answers
The apache commons wiki for VFS (https://wiki.apache.org/commons/VfsFaq) says to use the following when closing an SFTP connection in certain circumstances:
This forces the
close
method on theDefaultFileSystemManager
to be called, rather than theclose
method on theFileSystemManager
class.It may not be your issue, but it’s something that may be related.
You can try this alternative method to clean up any temporary files and close all providers.
More details can be found on: https://cwiki.apache.org/confluence/display/COMMONS/SimpleSftpFileDownload