All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.pastdev.jsch.sftp.SftpRunner Maven / Gradle / Ivy

Go to download

A set of extensions on top of JSch providing a full SCP protocol implementation, tunneling including multi-hop, a Java 7 FileSystem like implementation for Java 6 and remote command execution

There is a newer version: 0.1.11
Show newest version
package com.pastdev.jsch.sftp;


import java.io.Closeable;
import java.io.IOException;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSchException;
import com.pastdev.jsch.SessionFactory;
import com.pastdev.jsch.SessionManager;


/**
 * Provides a convenience wrapper around an sftp channel. This
 * implementation offers a simplified interface that manages the resources
 * needed to issue sftp commands.
 * 
 * @see com.jcraft.jsch.ChannelSftp
 */
public class SftpRunner implements Closeable {
    private static final Logger logger = LoggerFactory.getLogger( SftpRunner.class );
    private static final String CHANNEL_SFTP = "sftp";

    private final SessionManager sessionManager;

    /**
     * Creates a new SftpRunner that will use a {@link SessionManager} that
     * wraps the supplied sessionFactory.
     * 
     * @param sessionFactory
     *            The factory used to create a session manager
     */
    public SftpRunner( SessionFactory sessionFactory ) {
        this.sessionManager = new SessionManager( sessionFactory );
    }

    /**
     * Executes the sftp callback providing it an open
     * {@link ChannelSftp}. Sftp callback implementations should NOT
     * close the channel.
     * 
     * @param sftp A callback
     * @throws JSchException
     *             If ssh execution fails
     * @throws IOException
     *             If unable to read the result data
     */
    public void execute( Sftp sftp ) throws JSchException, IOException {
        logger.debug( "executing sftp command on {}", sessionManager );
        ChannelSftp channelSftp = null;
        try {
            channelSftp = (ChannelSftp) sessionManager.getSession()
                    .openChannel( CHANNEL_SFTP );
            channelSftp.connect();
            sftp.run( channelSftp );
        }
        finally {
            if ( channelSftp != null ) {
                channelSftp.disconnect();
            }
        }
    }

    /**
     * Closes the underlying {@link SessionManager}.
     * 
     * @see SessionManager#close()
     */
    @Override
    public void close() throws IOException {
        sessionManager.close();
    }

    /**
     * A simple callback interface for working with managed sftp channels.
     */
    public static interface Sftp {
        public void run( ChannelSftp sftp ) throws JSchException, IOException;
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy