Search code examples
javasshj

SSHJ: How to use StatefulSFTPClient


I'm confused... I am using com/hierynomus/sshj SFTP-lib and following code gives me ClassCastException:

SSHClient ssh = new SSHClient();
//... connect etc
StatefulSFTPClient client = (StatefulSFTPClient) ssh.newSFTPClient();

I need the StatefulSFTPClient but I don't know how to use it... Do I need to extend the SSHClient class with:

public StatefulSFTPClient newStatefulSFTPClient()
        throws IOException {
    checkConnected();
    checkAuthenticated();
    return new StatefulSFTPClient(new SFTPEngine(this).init());
}

Solution

  • Oh my... not the brightest moment - it can be done like this:

    StatefulSFTPClient client = new StatefulSFTPClient(new SFTPEngine(ssh).init());
    

    And to mimic the SSHClient.newSFTPClient():

                StatefulSFTPClient client;          
                if(ssh.isConnected()){
                    if(ssh.isAuthenticated()){
                        client = new StatefulSFTPClient(new SFTPEngine(ssh).init());
                    } else {
                        throw new IllegalStateException("Not authenticated");
                    }
                } else {
                    throw new IllegalStateException("Not connected");
                }