JavaFX How to stop current transfer file SFTP

Viewed 196

I would like to stop my current transfer file with using method stopUpload() :

private ChannelSftp channelSftp

private ChannelSftp setupJsch() throws JSchException {
    JSch jsch = new JSch();
    jsch.setKnownHosts("/Users/john/.ssh/known_hosts");
    Session jschSession = jsch.getSession(username, remoteHost);
    jschSession.setPassword(password);
    jschSession.connect();
    return (ChannelSftp) jschSession.openChannel("sftp");
}

public void stopUpload()
{

   channelSftp.disconnect();

}

public void whenUploadFileUsingJsch_thenSuccess() throws JSchException, SftpException {
    ChannelSftp channelSftp = setupJsch();
    channelSftp.connect();
 
    String localFile = "src/main/resources/sample.txt";
    String remoteDir = "remote_sftp_test/";
 
    channelSftp.put(localFile, remoteDir + "jschFile.txt");
    channelSftp.exit();
}

When stopUpload() run I have this error : Exception in thread "JavaFX Application Thread" java.lang.RuntimeException: java.lang.reflect.InvocationTargetException

1 Answers

To cleanly cancel a JSch SFTP transfer, when you need, implement the SftpProgressMonitor interface:

public class CancellableProgressMonitor implements SftpProgressMonitor {
    private boolean cancelled;

    public CancellableProgressMonitor() {}

    public void cancel() {
        this.cancelled = true;
    }

    public bool wasCancelled() {
        return this.cancelled;
    }

    public void init(int op, java.lang.String src, java.lang.String dest, long max) {
        this.cancelled = false;
    }

    public boolean count(long bytes) {
        return !this.cancelled;
    }

    public void end() {
    }
}

And pass it to ChannelSftp.put:

CancellableProgressMonitor monitor = new CancellableProgressMonitor()
channelSftp.put(localFile, remoteDir + "jschFile.txt", monitor);

Call monitor.cancel() when you need to cancel the transfer.

public void stopUpload() {
    monitor.cancel();
}

If you want to cleanup the partially transferred file:

String remoteFile = remoteDir + "jschFile.txt";
try {
    channelSftp.put(localFile, remoteFile, monitor);
} catch (IOException e) {
    if (monitor.wasCancelled() && channelSftp.getSession().isConnected()) {
        try {
            channelSftp.rm(remoteFile);
        } catch (SftpException e) {
            if (e.id == SSH_FX_NO_SUCH_FILE) {
                // can happen if the transfer was cancelled 
                // before the file was even created
            } else {
                throw e;
            }
        }
    }

    throw e;
}
Related