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

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

Introduction

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

Prototype

public static SftpFileSystemConfigBuilder getInstance() 

Source Link

Usage

From source file:gov.nih.nci.cacis.ip.mirthconnect.ftp.SFTPSender.java

public void sendDocument(InputStream file, String ftpAddress, String extension) {

    StandardFileSystemManager standardFileSystemManager = new StandardFileSystemManager();
    try {//from w w  w  .  j  a v a2s  .  co m
        final FTPInfo ftpInfo = ftpMapping.getFTPInfo(ftpAddress);
        if (ftpInfo == null) {
            throw new ApplicationRuntimeException("No server config exists for address[ " + ftpAddress + " ]");
        }

        String sftpURI = "sftp://" + ftpInfo.getUserName() + ":" + ftpInfo.getPassword() + "@"
                + ftpInfo.getSite() + "/" + ftpInfo.getRootDirectory();
        String fileName = "IHEXIPFTP-" + UUID.randomUUID() + extension;

        FileSystemOptions fileSystemOptions = new FileSystemOptions();
        SftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking(fileSystemOptions, "no");
        SftpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(fileSystemOptions, true);

        standardFileSystemManager.init();

        FileObject fileObject = standardFileSystemManager.resolveFile(sftpURI + "/" + fileName,
                fileSystemOptions);

        long timestamp = new Date().getTime();
        String tempSftpFile = sftpFileDirectory + "/" + timestamp + ".xml";
        OutputStream out = new FileOutputStream(new File(tempSftpFile));

        int read = 0;
        byte[] bytes = new byte[1024];

        while ((read = file.read(bytes)) != -1) {
            out.write(bytes, 0, read);
        }
        file.close();
        out.flush();
        out.close();

        FileObject localFileObject = standardFileSystemManager.resolveFile(tempSftpFile);

        fileObject.copyFrom(localFileObject, Selectors.SELECT_SELF);

        FileUtils.forceDelete(new File(tempSftpFile));

    } catch (Exception e) {
        throw new ApplicationRuntimeException("Error sending SFTP. " + e.getMessage());
    } finally {
        standardFileSystemManager.close();
    }
}

From source file:jfs.sync.vfs.JFSVFSFile.java

/**
 * Creates a new external root file and reads the structure from server.
 * /*from  ww w.j a  va2 s. c  o  m*/
 * @param fileProducer
 *            The assigned file producer.
 */
public JFSVFSFile(JFSVFSFileProducer fileProducer) {
    super(fileProducer, "");
    try {
        FileSystemOptions opts = new FileSystemOptions();

        // Avoid using known hosts file if SFTP is used:
        if (fileProducer.getScheme().equals("sftp")) {
            SftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking(opts, "no");
        }

        // Get user name and password, if not specified:
        try {
            URI uriObject = new URI(fileProducer.getUri());
            String userInfo = uriObject.getUserInfo();
            if (userInfo == null || !userInfo.contains(":")) {
                JFSUserAuthentication userAuth = JFSUserAuthentication.getInstance();
                userAuth.setResource(fileProducer.getUri());
                JFSUserAuthenticationInterface userInterface = userAuth.getUserInterface();

                StaticUserAuthenticator auth = new StaticUserAuthenticator(null, userInterface.getUserName(),
                        userInterface.getPassword());
                DefaultFileSystemConfigBuilder.getInstance().setUserAuthenticator(opts, auth);
            }
        } catch (URISyntaxException e) {
            JFSLog.getErr().getStream().println(e.getLocalizedMessage());
        }

        file = VFS.getManager().resolveFile(fileProducer.getUri(), opts);
    } catch (FileSystemException e) {
        JFSLog.getErr().getStream().println(e.getLocalizedMessage());
    }
}

From source file:com.learningobjects.community.abgm.logic.ControllerJob.java

private void download(String sourceUrl, File destinationFile) throws IOException {
    logger.log(Level.INFO, "Downloading or copying file from " + sourceUrl + " to " + destinationFile);
    FileObject sourceFileObject = null;
    OutputStream outputStream = null;
    try {//w  ww  .  j av  a  2s.  co m
        // special case sftp so that new hosts work out of the box. other options could go here too
        SftpFileSystemConfigBuilder sftpFileSystemConfigBuilder = SftpFileSystemConfigBuilder.getInstance();
        FileSystemOptions fileSystemOptions = new FileSystemOptions();
        sftpFileSystemConfigBuilder.setStrictHostKeyChecking(fileSystemOptions, "no");
        // actually try to get the file
        FileSystemManager fsManager = VFS.getManager();
        sourceFileObject = fsManager.resolveFile(sourceUrl, fileSystemOptions);
        FileContent sourceFileContent = sourceFileObject.getContent();
        InputStream inputStream = sourceFileContent.getInputStream();
        outputStream = new FileOutputStream(destinationFile);
        // do the copy - this is probably a dupe of commons io, and many others
        byte[] buffer = new byte[8192];
        int length;
        while ((length = inputStream.read(buffer)) > 0) {
            outputStream.write(buffer, 0, length);
        }
    } finally {
        if (outputStream != null) {
            outputStream.close();
        }
        if (sourceFileObject != null) {
            sourceFileObject.close(); // this will close the fileContent object, too
        }
    }
}

From source file:de.ecclesia.kipeto.RepositoryResolver.java

/**
 * Ld die Config vom Default-Repository herunter.
 *///from w w w .j av a 2 s. c  om
private Properties loadVfsConfig() throws IOException {
    String configUrl = String.format("%s/%s/%s", defaultRepositoryUrl, DIST_DIR, RESOLVE_CONFIG_FILE);
    log.info("Looking for repository-config at {}", configUrl);
    Properties properties = new Properties();
    FileSystemOptions fso = new FileSystemOptions();
    if (isSftp()) {
        Assert.isTrue(this.keyFile.isFile(), "Keyfile is not a file");
        File[] files = { this.keyFile };
        SftpFileSystemConfigBuilder.getInstance().setIdentities(fso, files);
        SftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking(fso, "yes");
    }

    FileObject fo;
    try {
        fo = VFS.getManager().resolveFile(configUrl, fso);

        BufferedInputStream inputStream = new BufferedInputStream(fo.getContent().getInputStream());

        properties.load(inputStream);
    } catch (FileSystemException e) {
        log.info("No repository-config found at {}", configUrl);
        throw new RuntimeException(e);
    }

    return properties;
}

From source file:net.sf.vfsjfilechooser.utils.VFSUtils.java

/**
 * Returns a file representation//  w  ww. ja v  a 2  s.  co m
 * @param filePath The file path
 * @return a file representation
 */
public static FileObject resolveFileObject(String filePath) {
    try {
        if (filePath.startsWith("sftp://")) {
            SftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking(opts, "no");
        }

        return getFileSystemManager().resolveFile(filePath, opts);
    } catch (FileSystemException ex) {
        return null;
    }
}

From source file:org.jumpmind.symmetric.io.FtpDataWriter.java

protected void sendFiles() {
    if (fileInfoByTable.size() > 0) {
        try {// ww  w .j  av  a  2s .co  m
            String sftpUri = buildUri();
            FileSystemOptions opts = new FileSystemOptions();
            FtpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(opts, true);
            SftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking(opts, "no");
            SftpFileSystemConfigBuilder.getInstance().setTimeout(opts, 60000);

            Collection<FileInfo> fileInfos = fileInfoByTable.values();
            for (FileInfo fileInfo : fileInfos) {
                FileObject fileObject = manager.resolveFile(sftpUri + "/" + fileInfo.outputFile.getName(),
                        opts);
                FileObject localFileObject = manager.resolveFile(fileInfo.outputFile.getAbsolutePath());
                fileObject.copyFrom(localFileObject, Selectors.SELECT_SELF);
                fileObject.close();
            }
        } catch (FileSystemException e) {
            logger.warn(
                    "If you have not configured your ftp connection it should be configured in conf/ftp-extensions.xml");
            throw new IoException(e);
        } catch (Exception e) {
            throw new IoException(e);
        } finally {
            manager.close();
        }
    }
}

From source file:org.objectweb.proactive.extensions.dataspaces.vfs.VFSFactory.java

private static FileSystemOptions createDefaultFileSystemOptions() throws FileSystemException {
    final FileSystemOptions options = new FileSystemOptions();
    // TODO or try to configure known hosts somehow (look for OpenSSH file etc.)
    SftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking(options, "no");
    return options;
}

From source file:org.ow2.proactive.scripting.helper.filetransfer.driver.SFTP_VFS_Driver.java

public void getFile(String remotePath, String destFolderPath) throws Exception {

    connect();//from  w w  w  . j a  va 2 s  .  c  o  m
    debug("Getting file " + remotePath + " to local folder " + destFolderPath);

    String fileName = (new File(remotePath).getName());
    String localPath = destFolderPath + File.separator + fileName;

    // we first set strict key checking off
    FileSystemOptions fsOptions = new FileSystemOptions();
    SftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking(fsOptions, "no");
    // now we create a new filesystem manager

    // the url is of form sftp://user:pass@host/remotepath/
    String uri = "sftp://" + _user + ":" + _pass + "@" + _host + "/" + remotePath;
    // get file object representing the local file
    FileObject fo = fsManager.resolveFile(uri, fsOptions);

    // open input stream from the remote file
    BufferedInputStream is = new BufferedInputStream(fo.getContent().getInputStream());
    // open output stream to local file
    OutputStream os = new BufferedOutputStream(new FileOutputStream(localPath));
    int c;
    // do copying
    while ((c = is.read()) != -1) {
        os.write(c);
    }
    os.close();
    is.close();
    // close the file object
    fo.close();

    debug("File copied " + remotePath + " to local folder " + destFolderPath);

    // NOTE: if you close the file system manager, you won't be able to
    // use VFS again in the same VM. If you wish to copy multiple files,
    // make the fsManager static, initialize it once, and close just
    // before exiting the process.
    // fsManager.close();
    //System.out.println("Finished copying the file");
    disconnect();
}

From source file:org.ow2.proactive.scripting.helper.filetransfer.driver.SFTP_VFS_Driver.java

public void putFile(String localPathFile, String remoteFolder) throws Exception {
    if (remoteFolder == "")
        remoteFolder = ".";

    debug("Putting file " + localPathFile + " to " + remoteFolder);

    //--Setup the SCP connection
    connect();/*  w w  w.j a va2 s. com*/

    //--Define paths
    //      String localFolder = FileTransfertUtils.getFolderFromPathfile(localPathFile);
    String fileName = new File(localPathFile).getName();

    // we first set strict key checking off
    FileSystemOptions fsOptions = new FileSystemOptions();
    SftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking(fsOptions, "no");
    // now we create a new filesystem manager

    // the url is of form sftp://user:pass@host/remotepath/
    String uri = "sftp://" + _user + ":" + _pass + "@" + _host + "/" + remoteFolder + "/" + fileName;
    // get file object representing the local file
    FileObject fo = fsManager.resolveFile(uri, fsOptions);
    fo.createFile();
    OutputStream os = fo.getContent().getOutputStream();
    BufferedInputStream is = new BufferedInputStream(new FileInputStream(new File(localPathFile)));

    int c;
    // do copying
    while ((c = is.read()) != -1) {
        os.write(c);
    }
    os.close();
    is.close();
    fo.close();

    debug("File copied :" + localPathFile + " to " + remoteFolder);

    //--Logout and disconnect
    disconnect();

}