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

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

Introduction

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

Prototype

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

Source Link

Document

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

Usage

From source file:org.jclouds.vfs.tools.blobstore.BlobStoreShell.java

/**
 * Does a 'get' command./*from   ww w .j  a  v  a 2  s. c  om*/
 */
private void get(final String[] cmd) throws Exception {
    if (cmd.length < 3) {
        throw new Exception("USAGE: get <src> <dest>");
    }

    FileObject src = remoteMgr.resolveFile(remoteCwd, cmd[1]);
    FileObject dest = mgr.resolveFile(cwd, cmd[2]);
    if (dest.exists() && dest.getType() == FileType.FOLDER) {
        dest = dest.resolveFile(src.getName().getBaseName());
    }

    dest.copyFrom(src, Selectors.SELECT_ALL);
}

From source file:org.jclouds.vfs.tools.blobstore.BlobStoreShell.java

/**
 * Does a 'put' command.//from  w w  w .  j a  v  a  2 s. c o  m
 */
private void put(final String[] cmd) throws Exception {
    if (cmd.length < 3) {
        throw new Exception("USAGE: put <src> <dest>");
    }

    FileObject src = mgr.resolveFile(cwd, cmd[2]);
    FileObject dest = remoteMgr.resolveFile(remoteCwd, cmd[1]);
    if (dest.exists() && dest.getType() == FileType.FOLDER) {
        dest = dest.resolveFile(src.getName().getBaseName());
    }

    dest.copyFrom(src, Selectors.SELECT_ALL);
}

From source file:org.josso.tooling.gshell.install.installer.VFSInstaller.java

protected boolean backupFile(FileObject src, FileObject targetDir) {

    try {//w w w. ja  va  2 s .  c  o m
        int attempt = 1;
        FileObject bkp = targetDir.resolveFile(src.getName().getBaseName() + ".bkp." + attempt);

        while (bkp.exists() && attempt < 99) {
            attempt++;
            bkp = targetDir.resolveFile(src.getName().getBaseName() + ".bkp." + attempt);
        }

        if (bkp.exists()) {
            getPrinter().printActionErrStatus("Backup", src.getName().getBaseName(),
                    "Too many backups already");
            return false;
        }

        bkp.copyFrom(src, Selectors.SELECT_SELF);
        getPrinter().printActionOkStatus("Backup", src.getName().getBaseName(), bkp.getName().getFriendlyURI());

        return true;

    } catch (IOException e) {
        getPrinter().printActionErrStatus("Backup", src.getName().getBaseName(), e.getMessage());
        return false;
    }
}

From source file:org.josso.tooling.gshell.install.installer.VFSInstaller.java

/**
 * @param srcFolder//from   w ww  .  j  a  v a2  s  .com
 * @param destDir
 * @param replace
 * @throws java.io.IOException
 */
protected void installFolder(FileObject srcFolder, FileObject destDir, String newName, boolean replace)
        throws IOException {

    // Check destination folder
    if (!destDir.exists()) {
        printInstallErrStatus(srcFolder.getName().getBaseName(),
                "Target directory not found " + destDir.getName().getBaseName());
        throw new IOException("Target directory not found " + destDir.getName().getBaseName());
    }

    // This is the new folder we're creating in destination.
    FileObject newFolder = destDir.resolveFile(newName);

    boolean exists = newFolder.exists();

    if (!replace && exists) {
        printInstallWarnStatus(newFolder.getName().getBaseName(), "Not replaced (see --replace option)");
        return;
    }

    if (exists) {
        // remove all descendents (removes old jars and other files when upgrading josso gateway)
        newFolder.delete(Selectors.EXCLUDE_SELF);
    }

    newFolder.copyFrom(srcFolder, Selectors.SELECT_ALL); // Copy ALL descendats

    printInstallOkStatus(srcFolder.getName().getBaseName(),
            (exists ? "Replaced " : "Created ") + newFolder.getName().getFriendlyURI());
}

From source file:org.josso.tooling.gshell.install.installer.WasceInstaller.java

@Override
public void performAdditionalTasks(FileObject libsDir) throws InstallException {
    try {/*from   w  w w .  j av  a 2  s .  co  m*/
        // undeploy wasce tomcat6 module if exists
        FileObject tomcatModule = targetDir.resolveFile("repository/org/apache/geronimo/configs/tomcat6");
        if (tomcatModule.exists()) {
            getPrinter().printMsg("Undeploying tomcat6 module");
            int status = undeploy("tomcat6");
            if (status == 0) {
                getPrinter().printOkStatus("Undeploy tomcat6 module", "Successful");
            } else {
                getPrinter().printErrStatus("Undeploy tomcat6 module", "Error");
                throw new InstallException("Error undeploying tomcat6 module!!!");
            }
        }

        // undeploy old josso wasce agent if exists
        FileObject jossoWasceAgentModule = targetDir.resolveFile("repository/org/josso/josso-wasce-agent");
        if (jossoWasceAgentModule.exists()) {
            getPrinter().printMsg("Undeploying old josso wasce agent");
            int status = undeploy("josso-wasce-agent");
            if (status == 0) {
                getPrinter().printOkStatus("Undeploy josso wasce agent", "Successful");
            } else {
                getPrinter().printErrStatus("Undeploy josso wasce agent", "Error");
                throw new InstallException("Error undeploying josso wasce agent!!!");
            }
        }

        // install jars to wasce repository
        try {
            getPrinter().printMsg("Installing new jars to WASCE repository");
            FileObject wasceRepo = targetDir.resolveFile("repository");
            FileObject wasceRepoFolder = libsDir.resolveFile("repository");
            wasceRepo.copyFrom(wasceRepoFolder, Selectors.SELECT_ALL);
            getPrinter().printOkStatus("Install new jars", "Successful");
        } catch (FileSystemException e) {
            getPrinter().printErrStatus("Install new jars", "Error");
            throw new InstallException("Error copying jars to wasce repository!!!");
        }

        // deploy josso wasce agent
        getPrinter().printMsg("Deploying josso wasce agent");
        FileObject jossoWasceCarFile = null;
        FileObject[] agentBins = libsDir.getChildren();
        for (int i = 0; i < agentBins.length; i++) {
            FileObject agentBin = agentBins[i];
            if (agentBin.getName().getBaseName().startsWith("josso-wasce")) {
                jossoWasceCarFile = agentBin;
                break;
            }
        }
        if (jossoWasceCarFile == null) {
            throw new InstallException("Josso wasce agent car file doesn't exist!!!");
        }
        int status = installPlugin(jossoWasceCarFile);
        if (status == 0) {
            getPrinter().printOkStatus("Install josso wasce agent", "Successful");
        } else {
            getPrinter().printErrStatus("Install josso wasce agent", "Error");
            throw new InstallException("Error installing josso wasce agent!!!");
        }

        // start stopped services
        getPrinter().printMsg("Starting tomcat related services");
        status = startTomcatRelatedServices();
        if (status == 0) {
            getPrinter().printOkStatus("Start tomcat related services", "Successful");
        } else {
            getPrinter().printErrStatus("Start tomcat related services", "Error");
            throw new InstallException("Error starting tomcat related services!!!");
        }
    } catch (IOException e) {
        throw new InstallException(e.getMessage(), e);
    }
}

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

protected void sendFiles() {
    if (fileInfoByTable.size() > 0) {
        try {//from  ww  w. ja  va 2 s  . c  o 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.pentaho.di.job.entries.copyfiles.JobEntryCopyFiles.java

private boolean ProcessFileFolder(String sourcefilefoldername, String destinationfilefoldername,
        String wildcard, Job parentJob, Result result) {
    boolean entrystatus = false;
    FileObject sourcefilefolder = null;
    FileObject destinationfilefolder = null;

    // Clear list files to remove after copy process
    // This list is also added to result files name
    list_files_remove.clear();/*from w  w  w . java2 s .co  m*/
    list_add_result.clear();

    // Get real source, destination file and wildcard
    String realSourceFilefoldername = environmentSubstitute(sourcefilefoldername);
    String realDestinationFilefoldername = environmentSubstitute(destinationfilefoldername);
    String realWildcard = environmentSubstitute(wildcard);

    try {
        sourcefilefolder = KettleVFS.getFileObject(realSourceFilefoldername, this);
        destinationfilefolder = KettleVFS.getFileObject(realDestinationFilefoldername, this);

        if (sourcefilefolder.exists()) {

            // Check if destination folder/parent folder exists !
            // If user wanted and if destination folder does not exist
            // PDI will create it
            if (CreateDestinationFolder(destinationfilefolder)) {

                // Basic Tests
                if (sourcefilefolder.getType().equals(FileType.FOLDER) && destination_is_a_file) {
                    // Source is a folder, destination is a file
                    // WARNING !!! CAN NOT COPY FOLDER TO FILE !!!

                    logError(BaseMessages.getString(PKG, "JobCopyFiles.Log.CanNotCopyFolderToFile",
                            realSourceFilefoldername, realDestinationFilefoldername));

                    NbrFail++;

                } else {

                    if (destinationfilefolder.getType().equals(FileType.FOLDER)
                            && sourcefilefolder.getType().equals(FileType.FILE)) {
                        // Source is a file, destination is a folder
                        // Copy the file to the destination folder

                        destinationfilefolder.copyFrom(sourcefilefolder.getParent(),
                                new TextOneFileSelector(sourcefilefolder.getParent().toString(),
                                        sourcefilefolder.getName().getBaseName(),
                                        destinationfilefolder.toString()));
                        if (isDetailed()) {
                            logDetailed(BaseMessages.getString(PKG, "JobCopyFiles.Log.FileCopied",
                                    sourcefilefolder.getName().toString(),
                                    destinationfilefolder.getName().toString()));
                        }

                    } else if (sourcefilefolder.getType().equals(FileType.FILE) && destination_is_a_file) {
                        // Source is a file, destination is a file

                        destinationfilefolder.copyFrom(sourcefilefolder,
                                new TextOneToOneFileSelector(destinationfilefolder));
                    } else {
                        // Both source and destination are folders
                        if (isDetailed()) {
                            logDetailed("  ");
                            logDetailed(BaseMessages.getString(PKG, "JobCopyFiles.Log.FetchFolder",
                                    sourcefilefolder.toString()));

                        }

                        TextFileSelector textFileSelector = new TextFileSelector(sourcefilefolder,
                                destinationfilefolder, realWildcard, parentJob);
                        try {
                            destinationfilefolder.copyFrom(sourcefilefolder, textFileSelector);
                        } finally {
                            textFileSelector.shutdown();
                        }
                    }

                    // Remove Files if needed
                    if (remove_source_files && !list_files_remove.isEmpty()) {
                        String sourceFilefoldername = sourcefilefolder.toString();
                        int trimPathLength = sourceFilefoldername.length() + 1;
                        FileObject removeFile;

                        for (Iterator<String> iter = list_files_remove.iterator(); iter.hasNext()
                                && !parentJob.isStopped();) {
                            String fileremoventry = iter.next();
                            removeFile = null; // re=null each iteration
                            // Try to get the file relative to the existing connection
                            if (fileremoventry.startsWith(sourceFilefoldername)) {
                                if (trimPathLength < fileremoventry.length()) {
                                    removeFile = sourcefilefolder
                                            .getChild(fileremoventry.substring(trimPathLength));
                                }
                            }

                            // Unable to retrieve file through existing connection; Get the file through a new VFS connection
                            if (removeFile == null) {
                                removeFile = KettleVFS.getFileObject(fileremoventry, this);
                            }

                            // Remove ONLY Files
                            if (removeFile.getType() == FileType.FILE) {
                                boolean deletefile = removeFile.delete();
                                logBasic(" ------ ");
                                if (!deletefile) {
                                    logError("      " + BaseMessages.getString(PKG,
                                            "JobCopyFiles.Error.Exception.CanRemoveFileFolder",
                                            fileremoventry));
                                } else {
                                    if (isDetailed()) {
                                        logDetailed("      " + BaseMessages.getString(PKG,
                                                "JobCopyFiles.Log.FileFolderRemoved", fileremoventry));
                                    }
                                }
                            }
                        }
                    }

                    // Add files to result files name
                    if (add_result_filesname && !list_add_result.isEmpty()) {
                        String destinationFilefoldername = destinationfilefolder.toString();
                        int trimPathLength = destinationFilefoldername.length() + 1;
                        FileObject addFile;

                        for (Iterator<String> iter = list_add_result.iterator(); iter.hasNext();) {
                            String fileaddentry = iter.next();
                            addFile = null; // re=null each iteration

                            // Try to get the file relative to the existing connection
                            if (fileaddentry.startsWith(destinationFilefoldername)) {
                                if (trimPathLength < fileaddentry.length()) {
                                    addFile = destinationfilefolder
                                            .getChild(fileaddentry.substring(trimPathLength));
                                }
                            }

                            // Unable to retrieve file through existing connection; Get the file through a new VFS connection
                            if (addFile == null) {
                                addFile = KettleVFS.getFileObject(fileaddentry, this);
                            }

                            // Add ONLY Files
                            if (addFile.getType() == FileType.FILE) {
                                ResultFile resultFile = new ResultFile(ResultFile.FILE_TYPE_GENERAL, addFile,
                                        parentJob.getJobname(), toString());
                                result.getResultFiles().put(resultFile.getFile().toString(), resultFile);
                                if (isDetailed()) {
                                    logDetailed(" ------ ");
                                    logDetailed("      " + BaseMessages.getString(PKG,
                                            "JobCopyFiles.Log.FileAddedToResultFilesName", fileaddentry));
                                }
                            }
                        }
                    }
                }
                entrystatus = true;
            } else {
                // Destination Folder or Parent folder is missing
                logError(BaseMessages.getString(PKG, "JobCopyFiles.Error.DestinationFolderNotFound",
                        realDestinationFilefoldername));
            }
        } else {
            logError(BaseMessages.getString(PKG, "JobCopyFiles.Error.SourceFileNotExists",
                    realSourceFilefoldername));

        }
    } catch (FileSystemException fse) {
        logError(BaseMessages.getString(PKG, "JobCopyFiles.Error.Exception.CopyProcessFileSystemException",
                fse.getMessage()));
        Throwable throwable = fse.getCause();
        while (throwable != null) {
            logError(BaseMessages.getString(PKG, "JobCopyFiles.Log.CausedBy", throwable.getMessage()));
            throwable = throwable.getCause();
        }
    } catch (Exception e) {
        logError(BaseMessages.getString(PKG, "JobCopyFiles.Error.Exception.CopyProcess",
                realSourceFilefoldername, realDestinationFilefoldername, e.getMessage()), e);
    } finally {
        if (sourcefilefolder != null) {
            try {
                sourcefilefolder.close();
                sourcefilefolder = null;
            } catch (IOException ex) { /* Ignore */
            }
        }
        if (destinationfilefolder != null) {
            try {
                destinationfilefolder.close();
                destinationfilefolder = null;
            } catch (IOException ex) { /* Ignore */
            }
        }
    }

    return entrystatus;
}

From source file:org.pentaho.di.job.entries.talendjobexec.JobEntryTalendJobExec.java

private URL[] prepareJarFiles(FileObject zipFile) throws Exception {

    // zip:file:///tmp/foo.zip
    FileInputList fileList = FileInputList.createFileList(this, new String[] { "zip:" + zipFile.toString(), },
            new String[] { ".*\\.jar$", }, // Include mask: only jar files
            new String[] { ".*classpath\\.jar$", }, // Exclude mask: only jar files
            new String[] { "Y", }, // File required
            new boolean[] { true, }); // Search sub-directories

    List<URL> files = new ArrayList<URL>();

    // Copy the jar files in the temp folder...
    ///*from   ww w  .j a  v  a 2 s.  c  om*/
    for (FileObject file : fileList.getFiles()) {
        FileObject jarfilecopy = KettleVFS.createTempFile(file.getName().getBaseName(), ".jar",
                environmentSubstitute("${java.io.tmpdir}"));
        jarfilecopy.copyFrom(file, new AllFileSelector());
        files.add(jarfilecopy.getURL());
    }

    return files.toArray(new URL[files.size()]);
}

From source file:org.sonatype.gshell.commands.vfs.CopyCommand.java

public Object execute(final CommandContext context) throws Exception {
    assert context != null;
    IO io = context.getIo();/*from  w ww. j  a  va  2s.  c  om*/

    FileObject source = resolveFile(context, sourcePath);
    FileObject target = resolveFile(context, targetPath);

    new FileObjectAssert(source).exists();

    // TODO: Validate more

    if (target.exists() && target.getType().hasChildren()) {
        target = target.resolveFile(source.getName().getBaseName());
    }

    log.info("Copying {} -> {}", source, target);

    target.copyFrom(source, Selectors.SELECT_ALL);

    FileObjects.close(source, target);

    return Result.SUCCESS;
}

From source file:org.sonatype.gshell.commands.vfs.EditCommand.java

public Object execute(final CommandContext context) throws Exception {
    assert context != null;

    FileObject file = resolveFile(context, path);

    new FileObjectAssert(file).exists().isReadable().isWritable();

    // TODO: Add to FileObjectAssert
    ensureFileHasContent(file);/*from  w  w  w .  ja  v  a  2s  .com*/

    FileObject tmp = file;

    // If the file is not on the local file system, then create tmp file for editing
    if (!getFileSystemAccess().isLocalFile(file)) {
        // Create a new temporary file, copy the contents for editing
        tmp = resolveFile(context, "tmp:/gshell-edit-" + System.currentTimeMillis() + ".txt");
        log.debug("Using temporary file: {} ({})", tmp, tmp.getClass());
        tmp.createFile();
        tmp.copyFrom(file, Selectors.SELECT_SELF);
    }

    // Have to dereference the VFS file into a local file so the editor can access it
    File localFile = getFileSystemAccess().getLocalFile(tmp);
    Object result = edit(context, localFile);

    // If we had to use a tmp file for editing, then copy back and clean up
    if (tmp != file) {
        log.debug("Updating original file with edited content");
        file.copyFrom(tmp, Selectors.SELECT_SELF);
        tmp.delete();
        FileObjects.close(tmp);
    }

    FileObjects.close(file);

    return result;
}