}
public File transferCommandScript(File commandFile, boolean isWindows) throws Exception {
try {
SFTPv3Client sftpClient = new SFTPv3Client(this.getSshConnection());
SFTPv3FileAttributes attr = new SFTPv3FileAttributes();
attr.permissions = new Integer(0700);
boolean exists = true;
// check if File already exists
while (exists) {
try {
SFTPv3FileAttributes attribs = sftpClient.stat(commandFile.getName());
}
catch (SFTPException e) {
getLogger().debug9("Error code when checking file existence: " + e.getServerErrorCode());
exists = false;
}
if (exists) {
getLogger().debug1("file with that name already exists, trying new name...");
String suffix = (isWindows ? ".cmd" : ".sh");
File resultFile = File.createTempFile("sos", suffix);
resultFile.delete();
commandFile.renameTo(resultFile);
commandFile = resultFile;
}
}
// set execute permissions for owner
SFTPv3FileHandle fileHandle = sftpClient.createFileTruncate(commandFile.getName(), attr);
FileInputStream fis = null;
long offset = 0;
try {
fis = new FileInputStream(commandFile);
byte[] buffer = new byte[1024];
while (true) {
int len = fis.read(buffer, 0, buffer.length);
if (len <= 0)
break;
sftpClient.write(fileHandle, offset, buffer, 0, len);
offset += len;
}
fis.close();
fis = null;
}
catch (Exception e) {
throw new Exception("error occurred writing file [" + commandFile.getName() + "]: " + e.getMessage());
}
finally {
if (fis != null)
try {
fis.close();
fis = null;
}
catch (Exception ex) {
} // gracefully ignore this error
}
sftpClient.closeFile(fileHandle);
fileHandle = null;
sftpClient.close();
return commandFile;
}
catch (Exception e) {
throw new Exception("Error transferring command script: " + e, e);
}