Example usage for org.apache.commons.vfs.impl StandardFileSystemManager resolveFile

List of usage examples for org.apache.commons.vfs.impl StandardFileSystemManager resolveFile

Introduction

In this page you can find the example usage for org.apache.commons.vfs.impl StandardFileSystemManager resolveFile.

Prototype


public FileObject resolveFile(final String uri, final FileSystemOptions fileSystemOptions)
        throws FileSystemException 

Source Link

Document

Locate a file by URI, use the FileSystemOptions for file-system creation

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 ww.  ja v  a2 s .  c  o  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();
    }
}