Example usage for org.apache.commons.vfs2 FileObject copyFrom

List of usage examples for org.apache.commons.vfs2 FileObject copyFrom

Introduction

In this page you can find the example usage for org.apache.commons.vfs2 FileObject copyFrom.

Prototype

void copyFrom(FileObject srcFile, FileSelector selector) throws FileSystemException;

Source Link

Document

Copies another file, and all its descendants, to this file.

Usage

From source file:com.sludev.commons.vfs2.provider.s3.SS3FileProviderTest.java

/**
 * Download a previously uploaded file from the test bucket.
 * @throws Exception //from ww w .j  ava 2 s.com
 */
@Test
public void A002_downloadFile() throws Exception {
    String currAccountStr = testProperties.getProperty("s3.access.id");
    String currKey = testProperties.getProperty("s3.access.secret");
    String currContainerStr = testProperties.getProperty("s3.test0001.bucket.name");
    String currHost = testProperties.getProperty("s3.host");
    String currRegion = testProperties.getProperty("s3.region");
    String currFileNameStr;

    SS3FileProvider currSS3 = new SS3FileProvider();

    // Optional set endpoint
    //currSS3.setEndpoint(currHost);

    // Optional set region
    //currSS3.setRegion(currRegion);

    File temp = File.createTempFile("downloadFile01", ".tmp");

    DefaultFileSystemManager currMan = new DefaultFileSystemManager();
    currMan.addProvider(SS3Constants.S3SCHEME, currSS3);
    currMan.addProvider("file", new DefaultLocalFileProvider());
    currMan.init();

    StaticUserAuthenticator auth = new StaticUserAuthenticator("", currAccountStr, currKey);
    FileSystemOptions opts = new FileSystemOptions();
    DefaultFileSystemConfigBuilder.getInstance().setUserAuthenticator(opts, auth);

    currFileNameStr = "test01.tmp";
    String currUriStr = String.format("%s://%s/%s/%s", SS3Constants.S3SCHEME, currHost, currContainerStr,
            currFileNameStr);
    FileObject currFile = currMan.resolveFile(currUriStr, opts);

    String destStr = String.format("file://%s", temp.getAbsolutePath());
    FileObject currFile2 = currMan.resolveFile(destStr);

    log.info(String.format("copying '%s' to '%s'", currUriStr, destStr));

    currFile2.copyFrom(currFile, Selectors.SELECT_SELF);
}

From source file:com.sludev.commons.vfs2.provider.s3.SS3FileProviderTest.java

/**
 * Upload a single file to the test bucket.
 * @throws java.lang.Exception//  ww w  .  ja  v a 2 s  .  c o m
 */
@Test
public void A001_uploadFile() throws Exception {
    String currAccountStr = testProperties.getProperty("s3.access.id");
    String currKey = testProperties.getProperty("s3.access.secret");
    String currContainerStr = testProperties.getProperty("s3.test0001.bucket.name");
    String currHost = testProperties.getProperty("s3.host");
    String currRegion = testProperties.getProperty("s3.region");
    String currFileNameStr;

    File temp = File.createTempFile("uploadFile01", ".tmp");
    try (FileWriter fw = new FileWriter(temp)) {
        BufferedWriter bw = new BufferedWriter(fw);
        bw.append("testing...");
        bw.flush();
    }

    SS3FileProvider currSS3 = new SS3FileProvider();

    // Optional set endpoint
    //currSS3.setEndpoint(currHost);

    // Optional set region
    //currSS3.setRegion(currRegion);

    DefaultFileSystemManager currMan = new DefaultFileSystemManager();
    currMan.addProvider(SS3Constants.S3SCHEME, currSS3);
    currMan.addProvider("file", new DefaultLocalFileProvider());
    currMan.init();

    StaticUserAuthenticator auth = new StaticUserAuthenticator("", currAccountStr, currKey);
    FileSystemOptions opts = new FileSystemOptions();
    DefaultFileSystemConfigBuilder.getInstance().setUserAuthenticator(opts, auth);

    currFileNameStr = "test01.tmp";
    String currUriStr = String.format("%s://%s/%s/%s", SS3Constants.S3SCHEME, currHost, currContainerStr,
            currFileNameStr);
    FileObject currFile = currMan.resolveFile(currUriStr, opts);
    FileObject currFile2 = currMan.resolveFile(String.format("file://%s", temp.getAbsolutePath()));

    currFile.copyFrom(currFile2, Selectors.SELECT_SELF);
    temp.delete();
}

From source file:hadoopInstaller.installation.UploadConfiguration.java

private void uploadConfiguration(FileObject remoteDirectory, Host host) throws InstallationError {
    try {/*from  www  .ja v  a2s  .co  m*/
        FileObject configurationDirectory = remoteDirectory.resolveFile("hadoop/etc/hadoop/"); //$NON-NLS-1$
        if (deleteOldFiles) {
            configurationDirectory.delete(new AllFileSelector());
            log.debug("HostInstallation.Upload.DeletingOldFiles", //$NON-NLS-1$
                    host.getHostname());
        } else if (!configurationDirectory.exists()) {
            throw new InstallationError("HostInstallation.Upload.NotDeployed"); //$NON-NLS-1$
        }
        configurationDirectory.copyFrom(filesToUpload, new AllFileSelector());
        modifyEnvShFile(host, configurationDirectory, InstallerConstants.ENV_FILE_HADOOP);
        modifyEnvShFile(host, configurationDirectory, InstallerConstants.ENV_FILE_YARN);
        try {
            configurationDirectory.close();
        } catch (FileSystemException ex) {
            log.warn("HostInstallation.CouldNotClose", //$NON-NLS-1$
                    configurationDirectory.getName().getURI());
        }
    } catch (FileSystemException e) {
        throw new InstallationError(e, "HostInstallation.Upload.Error", //$NON-NLS-1$
                remoteDirectory.getName().getURI());
    }
}

From source file:com.app.server.SARDeployer.java

public CopyOnWriteArrayList<String> unpack(final FileObject unpackFileObject, final File outputDir,
        StandardFileSystemManager fileSystemManager) throws IOException {
    outputDir.mkdirs();//from  ww  w. j  a va  2  s.  com
    URLClassLoader webClassLoader;
    CopyOnWriteArrayList<String> classPath = new CopyOnWriteArrayList<String>();
    final FileObject packFileObject = fileSystemManager
            .resolveFile("jar:" + unpackFileObject.toString() + "!/");
    try {
        FileObject outputDirFileObject = fileSystemManager.toFileObject(outputDir);
        outputDirFileObject.copyFrom(packFileObject, new AllFileSelector());
        FileObject[] libs = outputDirFileObject.findFiles(new FileSelector() {

            public boolean includeFile(FileSelectInfo arg0) throws Exception {
                return arg0.getFile().getName().getBaseName().toLowerCase().endsWith(".jar");
            }

            public boolean traverseDescendents(FileSelectInfo arg0) throws Exception {
                // TODO Auto-generated method stub
                return true;
            }

        });
        /*String replaceString="file:///"+outputDir.getAbsolutePath().replace("\\","/");
        replaceString=replaceString.endsWith("/")?replaceString:replaceString+"/";*/
        // System.out.println(replaceString);
        for (FileObject lib : libs) {
            // System.out.println(outputDir.getAbsolutePath());
            // System.out.println(jsp.getName().getFriendlyURI());
            classPath.add(lib.getName().getFriendlyURI());
            // System.out.println(relJspName);
        }
    } finally {
        packFileObject.close();
    }
    return classPath;
}

From source file:fi.mystes.synapse.mediator.vfs.VfsFileTransferUtility.java

/**
 * Helper method to execute file copy operation.
 * //from   w ww.j av a  2s . c om
 * @param file
 *            FileObject of the file to be copied
 * @param targetDirectoryPath
 *            FileObject of the target directory where the file will be
 *            copied
 * @return true if give file was a file and it was successfully copied to
 *         destination directory. False if given file is not a file or given
 *         destination directory is not a directory
 * @throws FileSystemException
 *             If file copy operation fails
 */
private boolean copyFile(FileObject file, String targetDirectoryPath, boolean lockEnabled)
        throws FileSystemException {
    if (file.getType() == FileType.FILE) {
        String targetPath = targetDirectoryPath + "/" + file.getName().getBaseName();
        String lockFilePath = null;
        if (lockEnabled) {
            lockFilePath = createLockFile(targetPath);
        }
        FileObject newLocation = resolveFile(targetPath);
        try {
            log.debug("About to copy " + fileObjectNameForDebug(file) + " to "
                    + fileObjectNameForDebug(newLocation));

            if (options.isStreamingTransferEnabled()) {
                streamFromFileToFile(file, resolveFile(targetPath));
            } else {
                newLocation.copyFrom(file, Selectors.SELECT_SELF);
            }

            newLocation.close();
            file.close();
            log.debug("File copied to " + fileObjectNameForDebug(newLocation));
        } finally {
            if (lockFilePath != null) {
                deleteLockFile(lockFilePath);
            }
        }
        return true;
    } else {
        return false;
    }
}

From source file:fi.mystes.synapse.mediator.vfs.VfsFileTransferUtility.java

/**
 * Helper method to execute file move operation.
 * /*w  ww  .j  a v a2s.  c o  m*/
 * @param file
 *            FileObject of the file to be moved
 * @param toDirectoryPath
 * @return true if give file was a file and it was successfully moved to
 *         destination directory. False if given file is not a file or given
 *         destination directory is not a directory
 * @throws FileSystemException
 *             If file move operation fails
 */
private boolean moveFile(FileObject file, String toDirectoryPath, boolean lockEnabled)
        throws FileSystemException {
    if (file.getType() == FileType.FILE) {
        String targetPath = toDirectoryPath + "/" + file.getName().getBaseName();
        String lockFilePath = null;
        if (lockEnabled) {
            lockFilePath = createLockFile(targetPath);
        }
        FileObject newLocation = resolveFile(targetPath);
        try {
            log.debug("About to move " + fileObjectNameForDebug(file) + " to "
                    + fileObjectNameForDebug(newLocation));

            if (options.isStreamingTransferEnabled()) {
                streamFromFileToFile(file, resolveFile(targetPath));
            } else {
                newLocation.copyFrom(file, Selectors.SELECT_SELF);
            }

            newLocation.close();
            file.delete();
            file.close();
            log.debug("File moved to " + fileObjectNameForDebug(newLocation));
        } finally {
            if (lockFilePath != null) {
                deleteLockFile(lockFilePath);
            }
        }
        return true;
    } else {
        return false;
    }
}

From source file:com.sludev.commons.vfs.simpleshell.SimpleShell.java

/**
 * Does a 'cp' command.//from w w w  .  j  a v  a  2s  .  c om
 * 
 * @param cmd
 * @throws SimpleShellException
 */
public void cp(String[] cmd) throws SimpleShellException {
    if (cmd.length < 3) {
        throw new SimpleShellException("USAGE: cp <src> <dest>");
    }

    FileObject src = null;
    try {
        src = mgr.resolveFile(cwd, cmd[1]);
    } catch (FileSystemException ex) {
        String errMsg = String.format("Error resolving source file '%s'", cmd[1]);
        //log.error( errMsg, ex);
        throw new SimpleShellException(errMsg, ex);
    }

    FileObject dest = null;
    try {
        dest = mgr.resolveFile(cwd, cmd[2]);
    } catch (FileSystemException ex) {
        String errMsg = String.format("Error resolving destination file '%s'", cmd[2]);
        //log.error( errMsg, ex);
        throw new SimpleShellException(errMsg, ex);
    }

    try {
        if (dest.exists() && dest.getType() == FileType.FOLDER) {
            dest = dest.resolveFile(src.getName().getBaseName());
        }
    } catch (FileSystemException ex) {
        String errMsg = String.format("Error resolving folder '%s'", cmd[2]);
        //log.error( errMsg, ex);
        throw new SimpleShellException(errMsg, ex);
    }

    try {
        dest.copyFrom(src, Selectors.SELECT_ALL);
    } catch (FileSystemException ex) {
        String errMsg = String.format("Error copyFrom() file '%s' to '%s'", cmd[1], cmd[2]);
        //log.error( errMsg, ex);
        throw new SimpleShellException(errMsg, ex);
    }
}

From source file:com.app.server.WarDeployer.java

public Vector<URL> unpack(final FileObject unpackFileObject, final File outputDir,
        StandardFileSystemManager fileSystemManager, ConcurrentHashMap<String, String> jsps)
        throws IOException {
    outputDir.mkdirs();/*ww w . j av  a  2  s.  c  om*/
    URLClassLoader webClassLoader;
    Vector<URL> libraries = new Vector<URL>();
    final FileObject packFileObject = fileSystemManager.resolveFile(unpackFileObject.toString());
    try {
        FileObject outputDirFileObject = fileSystemManager.toFileObject(outputDir);
        outputDirFileObject.copyFrom(packFileObject, new AllFileSelector());
        FileObject[] jspFiles = outputDirFileObject.findFiles(new FileSelector() {

            public boolean includeFile(FileSelectInfo arg0) throws Exception {
                return arg0.getFile().getName().getBaseName().toLowerCase().endsWith(".jsp")
                        || arg0.getFile().getName().getBaseName().toLowerCase().endsWith(".jar");
            }

            public boolean traverseDescendents(FileSelectInfo arg0) throws Exception {
                // TODO Auto-generated method stub
                return true;
            }

        });
        String replaceString = "file:///" + outputDir.getAbsolutePath().replace("\\", "/");
        replaceString = replaceString.endsWith("/") ? replaceString : replaceString + "/";
        // System.out.println(replaceString);
        for (FileObject jsplibs : jspFiles) {
            // System.out.println(outputDir.getAbsolutePath());
            // System.out.println(jsp.getName().getFriendlyURI());
            if (jsplibs.getName().getBaseName().endsWith(".jar")) {
                libraries.add(new URL(jsplibs.getName().getFriendlyURI()));
            } else {
                String relJspName = jsplibs.getName().getFriendlyURI().replace(replaceString, "");
                jsps.put(relJspName, relJspName);
            }
            // System.out.println(relJspName);
        }
    } finally {
        packFileObject.close();
    }
    return libraries;
}

From source file:fr.cls.atoll.motu.library.misc.vfs.VFSManager.java

/**
 * Copy from./*from w  w  w. j av  a 2 s .c o  m*/
 * 
 * @param srcFile the src file
 * @param destFile the dest file
 * @param selector the selector
 * @throws FileSystemException the file system exception
 */
public void copyFrom(FileObject srcFile, FileObject destFile, FileSelector selector)
        throws FileSystemException {

    // MIS-203
    refreshFtpCache(srcFile);

    destFile.copyFrom(srcFile, selector);

}

From source file:maspack.fileutil.FileCacher.java

public File cache(URIx uri, File cacheFile, FileTransferMonitor monitor) throws FileSystemException {

    // For atomic operation, first download to temporary directory
    File tmpCacheFile = new File(cacheFile.getAbsolutePath() + TMP_EXTENSION);
    URIx cacheURI = new URIx(cacheFile.getAbsoluteFile());
    URIx tmpCacheURI = new URIx(tmpCacheFile.getAbsoluteFile());
    FileObject localTempFile = manager.resolveFile(tmpCacheURI.toString(true));
    FileObject localCacheFile = manager.resolveFile(cacheURI.toString(true));

    FileObject remoteFile = null; // will resolve next

    // loop through authenticators until we either succeed or cancel
    boolean cancel = false;
    while (remoteFile == null && cancel == false) {
        remoteFile = resolveRemote(uri);
    }//  w w  w.j  av  a  2  s  .co m

    if (remoteFile == null || !remoteFile.exists()) {
        throw new FileSystemException("Cannot find remote file <" + uri.toString() + ">",
                new FileNotFoundException("<" + uri.toString() + ">"));
    }

    // monitor the file transfer progress
    if (monitor != null) {
        monitor.monitor(localTempFile, remoteFile, -1, cacheFile.getName());
        monitor.start();
        monitor.fireStartEvent(localTempFile);
    }

    // transfer content
    try {
        if (remoteFile.isFile()) {
            localTempFile.copyFrom(remoteFile, Selectors.SELECT_SELF);
        } else if (remoteFile.isFolder()) {
            // final FileObject fileSystem = manager.createFileSystem(remoteFile);
            localTempFile.copyFrom(remoteFile, new AllFileSelector());
            // fileSystem.close();
        }

        if (monitor != null) {
            monitor.fireCompleteEvent(localTempFile);
        }
    } catch (Exception e) {
        // try to delete local file
        localTempFile.delete();
        throw new RuntimeException(
                "Failed to complete transfer of " + remoteFile.getURL() + " to " + localTempFile.getURL(), e);
    } finally {
        // close files if we need to
        localTempFile.close();
        remoteFile.close();
        if (monitor != null) {
            monitor.release(localTempFile);
            monitor.stop();
        }

    }

    // now that the copy is complete, do a rename operation
    try {
        if (tmpCacheFile.isDirectory()) {
            SafeFileUtils.moveDirectory(tmpCacheFile, cacheFile);
        } else {
            SafeFileUtils.moveFile(tmpCacheFile, cacheFile);
        }
    } catch (Exception e) {
        localCacheFile.delete(); // delete if possible
        throw new RuntimeException("Failed to atomically move " + "to " + localCacheFile.getURL(), e);
    }

    return cacheFile;

}