Example usage for org.apache.commons.vfs2.provider.sftp SftpFileSystemConfigBuilder getInstance

List of usage examples for org.apache.commons.vfs2.provider.sftp SftpFileSystemConfigBuilder getInstance

Introduction

In this page you can find the example usage for org.apache.commons.vfs2.provider.sftp SftpFileSystemConfigBuilder getInstance.

Prototype

public static SftpFileSystemConfigBuilder getInstance() 

Source Link

Document

Gets the singleton builder.

Usage

From source file:SftpClientFactory.java

public static void main(String args[]) throws FileSystemException {
    String hostName = "commentpool-baggio000.rhcloud.com";
    String username = "529ddb964382eca06f0004b0";
    String password = "1026wu";

    // Create SFTP options
    FileSystemOptions opts = new FileSystemOptions();

    //        // SSH Key checking
    //        SftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking(
    //                opts, "yes");
    ////from w  ww.j a v  a  2 s  .  co m
    //        // Root directory set to user home
    //        SftpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(opts, true);
    //
    //        // Timeout is count by Milliseconds
    //        SftpFileSystemConfigBuilder.getInstance().setTimeout(opts, 10000);

    SftpFileSystemConfigBuilder.getInstance().setIdentities(opts,
            new File[] { new File("baggio_openssh.ppk") });

    createConnection(hostName, 22, username.toCharArray(), password.toCharArray(), opts);
}

From source file:hpmonitoringaudit.sftp.java

public boolean startFTP(String propertiesFilename, String fileToDownload) {

    props = new Properties();
    StandardFileSystemManager manager = new StandardFileSystemManager();

    try {/*from w w w  .j  av a  2 s .c om*/

        props.load(new FileInputStream("properties/" + propertiesFilename));
        String serverAddress = props.getProperty("serverAddress").trim();
        String userId = props.getProperty("userId").trim();
        String password = props.getProperty("password").trim();
        String remoteDirectory = props.getProperty("remoteDirectory").trim();
        String localDirectory = props.getProperty("localDirectory").trim();

        //Initializes the file manager
        manager.init();

        //Setup our SFTP configuration
        FileSystemOptions opts = new FileSystemOptions();
        SftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking(opts, "no");
        SftpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(opts, true);
        SftpFileSystemConfigBuilder.getInstance().setTimeout(opts, 10000);

        //Create the SFTP URI using the host name, userid, password,  remote path and file name
        String sftpUri = "sftp://" + userId + ":" + password + "@" + serverAddress + "/" + remoteDirectory
                + fileToDownload;

        // Create local file object
        String filepath = localDirectory + fileToDownload;
        File file = new File(filepath);
        FileObject localFile = manager.resolveFile(file.getAbsolutePath());

        // Create remote file object
        FileObject remoteFile = manager.resolveFile(sftpUri, opts);

        // Copy local file to sftp server
        localFile.copyFrom(remoteFile, Selectors.SELECT_SELF);
        System.out.println("File download successful");

    } catch (Exception ex) {
        ex.printStackTrace();
        return false;
    } finally {
        manager.close();
    }

    return true;
}

From source file:com.ewcms.publication.deploy.provider.SftpDeployOperator.java

@Override
protected FileObject getRootFileObject(FileSystemOptions opts, BuilderBase builder, FileSystemManager manager)
        throws FileSystemException {

    SftpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(opts, false);
    SftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking(opts, "no");

    String port = StringUtils.isBlank(builder.getPort()) ? DEFAULT_PORT : builder.getPort();

    StringBuilder connBuilder = new StringBuilder();
    connBuilder.append("sftp://");
    connBuilder.append(builder.getHostname()).append(":").append(port);
    connBuilder.append(builder.getPath());

    String conn = connBuilder.toString();
    logger.debug("uri is  {}", conn);

    return manager.resolveFile(conn, opts);
}

From source file:com.connection.factory.SftpConnectionApacheLib.java

@Override
public boolean getConnection() {
    if (command != null) {
        closeConnection();/*from   w ww.  j ava2  s  . c o m*/
    }
    FileSystemOptions fso = new FileSystemOptions();
    try {
        SftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking(fso, "no");
        SftpFileSystemConfigBuilder.getInstance().setTimeout(fso, 5000);

        session = SftpClientFactory.createConnection(_ipAdress, _port, _userName.toCharArray(),
                _passWord.toCharArray(), fso);
        Channel channel = session.openChannel("sftp");
        command = (ChannelSftp) channel;
        channel.connect();
        System.out.println("Connected to " + _ipAdress + " via sFTP");
        return true;

    } catch (FileSystemException | JSchException e) {
        System.out.println("Connection Failed to " + _ipAdress);
        return false;
    }
}

From source file:com.collective.celos.ci.deploy.JScpWorker.java

public FileSystemOptions getSftpDefaultOptions() throws FileSystemException {
    FileSystemOptions opts = new FileSystemOptions();
    SftpFileSystemConfigBuilder.getInstance().setPreferredAuthentications(opts, DEFAULT_SECURITY_SETTINGS);
    SftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking(opts, "no");
    SftpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(opts, false);
    return opts;/*from   ww w  .  j a  va 2 s.  com*/
}

From source file:com.sonicle.webtop.vfs.sfs.SftpSFS.java

@Override
protected void configureOptions() throws FileSystemException {
    SftpFileSystemConfigBuilder builder = SftpFileSystemConfigBuilder.getInstance();
    builder.setUserDirIsRoot(fso, false);
    builder.setUserInfo(fso, new TrustEveryoneUserInfo());
}

From source file:com.codehaus.mojo.vfs.FileSystemOptionsFactory.java

public FileSystemOptions getFileSystemOptions(String url, String username, String password)
        throws FileSystemException {

    FileSystemOptions opts = new FileSystemOptions();

    String[] tokens = StringUtils.split(url, ":");

    String protocol = tokens[0];/*from  w  w  w  .  java 2 s.c  om*/

    if ("ftp".equals(protocol)) {
        FtpFileSystemConfigBuilder builder = FtpFileSystemConfigBuilder.getInstance();
        builder.setPassiveMode(opts, ftpSettings.isPassiveMode());
        builder.setUserDirIsRoot(opts, ftpSettings.isUserDirIsRoot());
    }
    if ("sftp".equals(protocol)) {
        SftpFileSystemConfigBuilder builder = SftpFileSystemConfigBuilder.getInstance();
        builder.setUserDirIsRoot(opts, sftpSettings.isUserDirIsRoot());
    }

    String domain = null;
    tokens = StringUtils.split("\\");
    if (tokens.length == 2) {
        domain = tokens[0];
        username = tokens[1];
    }

    StaticUserAuthenticator auth = new StaticUserAuthenticator(domain, username, password);

    DefaultFileSystemConfigBuilder.getInstance().setUserAuthenticator(opts, auth);

    return opts;
}

From source file:it.geosolutions.geobatch.destination.common.utils.RemoteBrowserUtils.java

/**
 * Initialize the file system manager with a specific timeout
 * // ww  w.  j  av a 2  s . c om
 * @param timeout
 * @throws FileSystemException
 */
private static void initFsManager(int timeout) throws FileSystemException {
    // init fsManager
    if (fsManager == null) {
        // we first set strict key checking off
        fsOptions = new FileSystemOptions();
        SftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking(fsOptions, "no");
        // now we create a new file system manager
        fsManager = (DefaultFileSystemManager) VFS.getManager();
        SftpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(fsOptions, false);
    }
    SftpFileSystemConfigBuilder.getInstance().setTimeout(fsOptions, timeout);
}

From source file:maspack.fileutil.FileCacher.java

public static void setDefaultFsOptions(FileSystemOptions opts) throws FileSystemException {

    // SSH Defaults
    // Don't check host key
    // Use paths relative to root (as opposed to the user's home dir)
    // 10 second timeout
    SftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking(opts, "no");
    SftpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(opts, true);
    SftpFileSystemConfigBuilder.getInstance().setTimeout(opts, 10000);

    /**//from www . ja v  a 2  s . c  o  m
     * Allow connection to silly UBC servers who don't update their credentials
     */
    TrustStrategy[] ts = { new UnsafeTrustStrategy() };
    HttpFileSystemConfigBuilder httpBuilder = HttpFileSystemConfigBuilder.getInstance();
    WebdavFileSystemConfigBuilder webdavBuilder = WebdavFileSystemConfigBuilder.getInstance();

    // allow all SSL connections
    httpBuilder.setTrustStrategies(opts, ts);
    webdavBuilder.setTrustStrategies(opts, ts);

    // silly deprecated UBC cipher suite
    String[] ciphers = httpBuilder.getDefaultSSLCipherSuites();
    ciphers = Arrays.copyOf(ciphers, ciphers.length + 1);
    ciphers[ciphers.length - 1] = "SSL_RSA_WITH_RC4_128_SHA";

    httpBuilder.setEnabledSSLCipherSuites(opts, ciphers);
    webdavBuilder.setEnabledSSLCipherSuites(opts, ciphers);

}

From source file:SftpClientFactory.java

/**
 * Creates a new connection to the server.
 * @param hostname The name of the host to connect to.
 * @param port The port to use.//from  w  ww.  j  a v  a  2  s  . c o m
 * @param username The user's id.
 * @param password The user's password.
 * @param fileSystemOptions The FileSystem options.
 * @return A Session.
 * @throws FileSystemException if an error occurs.
 */
public static Session createConnection(String hostname, int port, char[] username, char[] password,
        FileSystemOptions fileSystemOptions) throws FileSystemException {
    JSch jsch = new JSch();

    File sshDir = null;

    // new style - user passed
    File knownHostsFile = SftpFileSystemConfigBuilder.getInstance().getKnownHosts(fileSystemOptions);
    File[] identities = SftpFileSystemConfigBuilder.getInstance().getIdentities(fileSystemOptions);

    if (knownHostsFile != null) {
        try {
            jsch.setKnownHosts(knownHostsFile.getAbsolutePath());
        } catch (JSchException e) {
            throw new FileSystemException("vfs.provider.sftp/known-hosts.error",
                    knownHostsFile.getAbsolutePath(), e);
        }
    } else {
        sshDir = findSshDir();
        // Load the known hosts file
        knownHostsFile = new File(sshDir, "known_hosts");
        if (knownHostsFile.isFile() && knownHostsFile.canRead()) {
            try {
                jsch.setKnownHosts(knownHostsFile.getAbsolutePath());
            } catch (JSchException e) {
                throw new FileSystemException("vfs.provider.sftp/known-hosts.error",
                        knownHostsFile.getAbsolutePath(), e);
            }
        }
    }

    if (identities != null) {
        for (int iterIdentities = 0; iterIdentities < identities.length; iterIdentities++) {
            final File privateKeyFile = identities[iterIdentities];
            try {
                jsch.addIdentity(privateKeyFile.getAbsolutePath());
            } catch (final JSchException e) {
                throw new FileSystemException("vfs.provider.sftp/load-private-key.error", privateKeyFile, e);
            }
        }
    } else {
        if (sshDir == null) {
            sshDir = findSshDir();
        }

        // Load the private key (rsa-key only)
        final File privateKeyFile = new File(sshDir, "id_rsa");
        if (privateKeyFile.isFile() && privateKeyFile.canRead()) {
            try {
                jsch.addIdentity(privateKeyFile.getAbsolutePath());
            } catch (final JSchException e) {
                throw new FileSystemException("vfs.provider.sftp/load-private-key.error", privateKeyFile, e);
            }
        }
    }

    Session session;
    try {
        session = jsch.getSession(new String(username), hostname, port);
        if (password != null) {
            session.setPassword(new String(password));
        }

        Integer timeout = SftpFileSystemConfigBuilder.getInstance().getTimeout(fileSystemOptions);
        if (timeout != null) {
            session.setTimeout(timeout.intValue());
        }

        UserInfo userInfo = SftpFileSystemConfigBuilder.getInstance().getUserInfo(fileSystemOptions);
        if (userInfo != null) {
            session.setUserInfo(userInfo);
        }

        Properties config = new Properties();

        //set StrictHostKeyChecking property
        String strictHostKeyChecking = SftpFileSystemConfigBuilder.getInstance()
                .getStrictHostKeyChecking(fileSystemOptions);
        if (strictHostKeyChecking != null) {
            config.setProperty("StrictHostKeyChecking", strictHostKeyChecking);
        }
        //set PreferredAuthentications property
        String preferredAuthentications = SftpFileSystemConfigBuilder.getInstance()
                .getPreferredAuthentications(fileSystemOptions);
        if (preferredAuthentications != null) {
            config.setProperty("PreferredAuthentications", preferredAuthentications);
        }

        //set compression property
        String compression = SftpFileSystemConfigBuilder.getInstance().getCompression(fileSystemOptions);
        if (compression != null) {
            config.setProperty("compression.s2c", compression);
            config.setProperty("compression.c2s", compression);
        }

        String proxyHost = SftpFileSystemConfigBuilder.getInstance().getProxyHost(fileSystemOptions);
        if (proxyHost != null) {
            int proxyPort = SftpFileSystemConfigBuilder.getInstance().getProxyPort(fileSystemOptions);
            SftpFileSystemConfigBuilder.ProxyType proxyType = SftpFileSystemConfigBuilder.getInstance()
                    .getProxyType(fileSystemOptions);
            Proxy proxy = null;
            if (SftpFileSystemConfigBuilder.PROXY_HTTP.equals(proxyType)) {
                if (proxyPort != 0) {
                    proxy = new ProxyHTTP(proxyHost, proxyPort);
                } else {
                    proxy = new ProxyHTTP(proxyHost);
                }
            } else if (SftpFileSystemConfigBuilder.PROXY_SOCKS5.equals(proxyType)) {
                if (proxyPort != 0) {
                    proxy = new ProxySOCKS5(proxyHost, proxyPort);
                } else {
                    proxy = new ProxySOCKS5(proxyHost);
                }
            }

            if (proxy != null) {
                session.setProxy(proxy);
            }
        }

        //set properties for the session
        if (config.size() > 0) {
            session.setConfig(config);
        }
        session.setDaemonThread(true);
        session.connect();
    } catch (final Exception exc) {
        throw new FileSystemException("vfs.provider.sftp/connect.error", new Object[] { hostname }, exc);
    }

    return session;
}