We are deploying a Java project on Linux Server. A file is generated by the project which is then sent to a remote server.
It was earlier implemented using Jsch. However, due to its dependency on JCE and the inability to upgrade the java version (from 5) we are switching to Ganymed. I am using Ganymed build 210 (viz. is tested for java 5; http://www.ganymed.ethz.ch/ssh2)
This is the function I am using to sftp the file.
public boolean sftp_put() {
File privateKeyFile = new File(identityPath);
File rfile = new File(hostDir);
File lfile = new File(lpath);
boolean success = false;
try {
if (!lfile.exists() || lfile.isDirectory()) {
throw new IOException("Local file must be a regular file: "
+ lpath);
}
Connection ssh = new Connection(host, port);
ssh.connect();
ssh.authenticateWithPublicKey(user, privateKeyFile, password);
SFTPv3Client sftp = new SFTPv3Client(ssh);
try {
SFTPv3FileAttributes attr = sftp.lstat(hostDir);
if (attr.isDirectory()) {
rfile = new File(hostDir, lfile.getName());
}
} catch (SFTPException e) {
try {
SFTPv3FileAttributes attr = sftp.lstat(rfile.getParent());
if (!attr.isDirectory()) {
throw new IOException(
"Remote file's parent must be a directory: "
+ hostDir + "," + e);
}
} catch (SFTPException ex) {
throw new IOException(
"Remote file's parent directory must exist: "
+ hostDir + "," + ex);
}
}
SFTPv3FileHandle file = sftp.createFileTruncate(rfile
.getCanonicalPath());
long fileOffset = 0;
byte[] src = new byte[32768];
int i = 0;
FileInputStream input = new FileInputStream(lfile);
while ((i = input.read(src)) != -1) {
sftp.write(file, fileOffset, src, 0, i);
fileOffset += i;
}
input.close();
sftp.closeFile(file);
sftp.close();
success=true;
} catch (IOException e1) {
logger.warn("Exception while trying to sftp", e)
}
return success;
}
I am unable to connect to the remote server possibly due to binding issues and unsure on how to proceed? I am thinking on binding a local address before the SFTP.
So I wrote a socket function.
public Socket createSocket(String destinationHost, int destinationPort)
throws IOException, UnknownHostException {
logger.info("sftp configured bind address : " + bindAddress
+ ", bind port : " + bindPort);
Socket socket = new Socket();
socket.bind(new InetSocketAddress(bindAddress, bindPort));
socket.connect(new InetSocketAddress(destinationHost, destinationPort),
connectionTimeOut);
if (socket.isBound()) {
logger.info("sftp actual bind port : " + socket.getLocalPort());
} else {
logger.warn("sftp socket not bound to local port");
}
return socket;
}
However this is also not working, and I am getting a Socket Exception.
EDIT: So I was creating the socket in the right way but no where am I using the same socket for creating the connection. Such a method is not defined in any of the Ganymed libraries.