boolean dstExists = false, error = false;
String _dst = null;
try {
List<String> matches = globRemote(src);
if( matches.isEmpty() ) {
throw new SftpException(SSH_FX_NO_SUCH_FILE, "No such file: "+src);
}
File dstFile = new File(dst);
boolean isDstDir = dstFile.isDirectory();
StringBuffer dstsb = null;
if( isDstDir ) {
if( !dst.endsWith(File.separator) ) {
dst += File.separator;
}
dstsb = new StringBuffer(dst);
} else if( matches.size() > 1 ) {
throw new SftpException(SSH_FX_FAILURE, "Copying multiple files, but destination is missing or a file.");
}
for( String _src : matches ) {
SftpATTRS attr = _stat(_src);
if( attr.isDir() ) {
throw new SftpException(SSH_FX_FAILURE, "Not supported to get directory " + _src);
}
_dst = null;
if( isDstDir ) {
int i = _src.lastIndexOf('/');
if( i == -1 ) {
dstsb.append(_src);
} else {
dstsb.append(_src.substring(i + 1));
}
_dst = dstsb.toString();
dstsb.delete(dst.length(), _dst.length());
} else {
_dst = dst;
}
File _dstFile = new File(_dst);
if( mode == RESUME ) {
long sizeOfSrc = attr.getSize();
long sizeOfDst = _dstFile.length();
if( sizeOfDst > sizeOfSrc ) {
throw new SftpException(SSH_FX_FAILURE, "Failed to resume for " + _dst);
} else if( sizeOfDst == sizeOfSrc ) {
return; // Nothing to resume, already have full file
}
}
if( monitor != null ) {
monitor.init(SftpProgressMonitor.GET, _src, _dst, attr.getSize());
if( mode == RESUME ) {
monitor.count(_dstFile.length());
}
}
FileOutputStream fos = null;
dstExists = _dstFile.exists();
try {
fos = new FileOutputStream(_dst, mode != OVERWRITE);
_get(_src, fos, monitor, mode, new File(_dst).length());
} finally {
if( fos != null ) {
try { fos.close(); } catch(IOException ie) { /* Ignore error. */ }
}
}
}
} catch(SftpException e) {
error = true;
throw e;
} catch(Exception e) {
error = true;
throw new SftpException(SSH_FX_FAILURE, "Failed to get src: "+src, e);
} finally {
if( error && !dstExists && _dst != null ) {
File _dstFile = new File(_dst);
if( _dstFile.exists() && _dstFile.length() == 0 ) {
_dstFile.delete();