String remoteFilePath = remoteFileInfo.filePath;
String tempRemotePath = tempNameForSourceFile(remoteFilePath);
File localFile = null;
long bytesCopied = 0L;
IOException cleanupIOException = null;
JSchException cleanupJSchException = null;
boolean success = false;
// Copy file and validate result
try {
// Rename the remote file with a temporary name before copying
if(logger.isDebugEnabled()) {
logger.debug("Renaming remote file to: {}", tempRemotePath);
}
sshCommand.execShellCommand("mv " + remoteFilePath + " " + tempRemotePath);
// Copy the (renamed) remote file to local destination
remoteFileInfo.filePath = tempRemotePath; // remote file name is needed during validation
bytesCopied = sshCommand.copyFrom(tempRemotePath, localFilePath);
localFile = new File(localFilePath);
long modTime = (long) (Double.parseDouble(remoteFileInfo.fileModtime) * 1000.0);
localFile.setLastModified(modTime);
// Check integrity of copy
success = validateRemoteFileCopy(sshCommand, remoteFileInfo, localFilePath);
if (!success) {
logger.warn("Copy of file {} did not pass integrity check!", remoteFilePath);
}
} catch (IOException ex) {
// If there's been an error copying the file, we may be left with a zero-length or incomplete file
if ((localFile != null) && localFile.exists() && !success) {
if(logger.isDebugEnabled()) {
logger.debug("Deleting failed local copy of remote file: {}", localFile.getAbsolutePath());
}
localFile.delete();
}
} finally {
// Use a try-block during cleanup, but only throw exception if the
// main file-copy try-block doesn't
try {
if (deleteSource && success) {
if(logger.isDebugEnabled()) {
logger.debug("Deleting remote file: {}", tempRemotePath);
}
sshCommand.execShellCommand("rm " + tempRemotePath);
} else {
// Move source file back from temporary name
sshCommand.execShellCommand("mv " + tempRemotePath + " " + remoteFilePath);
}
} catch (JSchException ex) {
logger.warn("JSchException during remote file copy cleanup: {}", ex);
cleanupJSchException = new JSchException(ex.getMessage());
} catch (IOException ex) {
logger.warn("IOException during remote file copy cleanup: {}", ex);
cleanupIOException = new IOException(ex);
}
remoteFileInfo.filePath = remoteFilePath; // restore original file name in argument