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:org.codehaus.mojo.vfs.internal.DefaultMergeVfsMavenRepositories.java

private void mergeTargetMetadataToStageMetaData(FileObject targetRepo, FileObject stagingRepo)
        throws IOException, XmlPullParserException {

    VfsFileSet fileset = new VfsFileSet();
    fileset.setSource(stagingRepo);// w w w .j  a  v a  2s .  c o m
    String[] includes = { "**/" + MAVEN_METADATA };
    fileset.setIncludes(includes);

    VfsFileSetManager fileSetManager = new DefaultVfsFileSetManager();
    List<FileObject> targetMetaFileObjects = fileSetManager.list(fileset);

    // Merge all metadata files
    for (FileObject sourceMetaFileObject : targetMetaFileObjects) {

        String relativeMetaPath = VfsUtils.getRelativePath(stagingRepo, sourceMetaFileObject);

        FileObject targetMetaFile = targetRepo.resolveFile(relativeMetaPath);
        FileObject stagingTargetMetaFileObject = stagingRepo.resolveFile(relativeMetaPath + IN_PROCESS_MARKER);

        try {
            stagingTargetMetaFileObject.copyFrom(targetMetaFile, Selectors.SELECT_ALL);
        } catch (FileSystemException e) {
            // We don't have an equivalent on the targetRepositoryUrl side because we have something
            // new on the sourceRepositoryUrl side so just skip the metadata merging.
            continue;
        }

        try {
            File targetMetaData = new File(stagingTargetMetaFileObject.getName().getPath());
            File sourceMetaData = new File(sourceMetaFileObject.getName().getPath());
            MavenMetadataUtils mavenMetadataUtils = new MavenMetadataUtils();
            mavenMetadataUtils.merge(targetMetaData, sourceMetaData);
            targetMetaData.delete();
        } catch (XmlPullParserException e) {
            throw new IOException(
                    "Metadata file is corrupt " + sourceMetaFileObject + " Reason: " + e.getMessage());
        }

    }

}

From source file:org.codehaus.mojo.vfs.internal.DefaultVfsFileSetManager.java

private void copyFile(FileObject fromFile, FileObject toFile, boolean overwrite) throws FileSystemException {
    if (overwrite || !toFile.exists()
            || fromFile.getContent().getLastModifiedTime() > toFile.getContent().getLastModifiedTime()) {
        toFile.copyFrom(fromFile, Selectors.SELECT_ALL);
    }/*from  w w w.j a  va2s  .c  o m*/
}

From source file:org.datacleaner.user.upgrade.DataCleanerHomeUpgrader.java

/**
 * Finds a folder to upgrade from based on the "newFolder" parameter -
 * upgrades are performed only within the same major version.
 * //  w  w w.  jav  a 2 s . c  o  m
 * @param newFolder
 *            The folder we want to upgrade to (the new version)
 * @return true if upgrade was successful, false otherwise
 */
public boolean upgrade(FileObject newFolder) {
    try {
        if (newFolder.getChildren().length != 0) {
            // if the folder is not new then we don't want to touch it
            return false;
        }

        final FileObject upgradeFromFolderCandidate = findUpgradeCandidate(newFolder);

        if (upgradeFromFolderCandidate == null) {
            logger.info("Did not find a suitable upgrade candidate");
            return false;
        }

        logger.info("Upgrading DATACLEANER_HOME from : {}", upgradeFromFolderCandidate);
        newFolder.copyFrom(upgradeFromFolderCandidate, new AllFileSelector());

        // special handling of userpreferences.dat - we only want to keep
        // the good parts ;-)
        final UserPreferencesUpgrader userPreferencesUpgrader = new UserPreferencesUpgrader(newFolder);
        userPreferencesUpgrader.upgrade();

        // Overwrite example jobs
        final List<String> allFilePaths = DemoConfiguration.getAllFilePaths();
        for (String filePath : allFilePaths) {
            overwriteFileWithDefaults(newFolder, filePath);
        }
        return true;
    } catch (FileSystemException e) {
        logger.warn("Exception occured during upgrading: {}", e);
        return false;
    }
}

From source file:org.esupportail.portlet.filemanager.services.vfs.VfsAccessImpl.java

@Override
public boolean moveCopyFilesIntoDirectory(String dir, List<String> filesToCopy, boolean copy,
        SharedUserPortletParameters userParameters) {
    try {/*from ww w  .j a va  2 s .co  m*/
        FileObject folder = cd(dir, userParameters);
        for (String fileToCopyPath : filesToCopy) {
            FileObject fileToCopy = cd(fileToCopyPath, userParameters);
            FileObject newFile = folder.resolveFile(fileToCopy.getName().getBaseName());
            if (copy) {
                newFile.copyFrom(fileToCopy, Selectors.SELECT_ALL);
            } else {
                fileToCopy.moveTo(newFile);
            }

        }
        return true;
    } catch (FileSystemException e) {
        log.warn("can't move/copy file because of FileSystemException : " + e.getMessage(), e);
    }
    return false;
}

From source file:org.geoserver.backuprestore.utils.BackupUtils.java

/**
 * Extracts the archive file {@code archiveFile} to {@code targetFolder}; both shall previously exist.
 *
 * @param archiveFile/*from  w  ww.  j  a va2s .  co  m*/
 * @param targetFolder
 * @throws IOException
 */
public static void extractTo(Resource archiveFile, Resource targetFolder) throws IOException {
    FileSystemManager manager = VFS.getManager();
    String sourceURI = resolveArchiveURI(archiveFile);

    FileObject source = manager.resolveFile(sourceURI);
    if (manager.canCreateFileSystem(source)) {
        source = manager.createFileSystem(source);
    }
    FileObject target = manager
            .createVirtualFileSystem(manager.resolveFile(targetFolder.dir().getAbsolutePath()));

    FileSelector selector = new AllFileSelector() {
        @Override
        public boolean includeFile(FileSelectInfo fileInfo) {
            LOGGER.fine("Uncompressing " + fileInfo.getFile().getName().getFriendlyURI());
            return true;
        }
    };
    target.copyFrom(source, selector);
    source.close();
    target.close();
    manager.closeFileSystem(source.getFileSystem());
}

From source file:org.jfunktor.common.vfs.VirtualFileSystem.java

public static boolean extractContentsTo(URL fromLocation, URL toLocation)
        throws FileNotFoundException, VFSException {
    FileObject fromFile = null;//w  ww .  j a  va2s  . c  o m
    FileObject toFile = null;
    boolean retVal = false;
    if (exists(fromLocation)) {
        log.debug(fromLocation + "Exists");
        toFile = resolveFile(toLocation);
        fromFile = resolveFile(fromLocation);
        // now extract or copy the contents and children to the destination

        try {
            log.debug("About to copy from " + fromFile + " to " + toFile);
            toFile.copyFrom(fromFile, new AllFileSelector());
            retVal = true;
        } catch (FileSystemException e) {
            e.printStackTrace();
        }
    } else {
        log.debug("From Location " + fromLocation + " does not exist. Please check if it is a valid path");
        retVal = false;
    }

    return retVal;
}

From source file:org.obiba.opal.web.FilesResource.java

private Response copyFrom(FileObject destinationFolder, Iterable<String> sourcesPath) throws IOException {
    // destination check
    String destinationPath = destinationFolder.getName().getPath();
    if (destinationFolder.getType() != FileType.FOLDER)
        return Response.status(Status.BAD_REQUEST).entity("Destination must be a folder: " + destinationPath)
                .build();//from   ww w .  jav  a2 s . co  m

    // sources check
    for (String sourcePath : sourcesPath) {
        FileObject sourceFile = resolveFileInFileSystem(sourcePath);
        if (!sourceFile.exists())
            getPathNotExistResponse(sourcePath);
        if (!sourceFile.isReadable()) {
            return Response.status(Status.FORBIDDEN).entity("Source file is not readable: " + sourcePath)
                    .build();
        }
    }

    // do action
    for (String sourcePath : sourcesPath) {
        FileObject sourceFile = resolveFileInFileSystem(sourcePath);
        FileObject destinationFile = resolveFileInFileSystem(
                destinationPath + "/" + sourceFile.getName().getBaseName());
        FileSelector selector = sourceFile.getType() == FileType.FOLDER ? Selectors.SELECT_ALL
                : Selectors.SELECT_SELF;
        destinationFile.copyFrom(sourceFile, selector);
    }

    return Response.ok().build();
}

From source file:org.ow2.proactive.scheduler.smartproxy.SmartProxyImpl.java

@Override
protected void downloadTaskOutputFiles(AwaitedJob awaitedjob, String jobId, String t_name, String localFolder)
        throws Exception {
    AwaitedTask atask = awaitedjob.getAwaitedTask(t_name);
    if (atask == null) {
        throw new IllegalArgumentException(
                "The task " + t_name + " does not belong to job " + jobId + " or has already been removed");
    }/*from   ww w.ja  va 2  s  . co m*/
    if (atask.isTransferring()) {
        log.warn("The task " + t_name + " of job " + jobId + " is already transferring its output");
        return;
    }
    String pull_URL = awaitedjob.getPullURL();

    if (awaitedjob.isIsolateTaskOutputs()) {
        pull_URL = pull_URL.replace(SchedulerConstants.TASKID_DIR_DEFAULT_NAME,
                SchedulerConstants.TASKID_DIR_DEFAULT_NAME + "/" + atask.getTaskId());
    }

    FileObject remotePullFolderFO;
    FileObject localfolderFO;

    try {
        remotePullFolderFO = jobTracker.resolveFile(pull_URL);

        localfolderFO = jobTracker.resolveFile(localFolder);
    } catch (FileSystemException e) {
        log.error("Could not retrieve data for job " + jobId, e);
        throw new IllegalStateException("Could not retrieve data for job " + jobId, e);
    }

    String sourceUrl = remotePullFolderFO.getURL().toString();
    String destUrl = localfolderFO.getURL().toString();

    org.objectweb.proactive.extensions.dataspaces.vfs.selector.FileSelector fileSelector = new org.objectweb.proactive.extensions.dataspaces.vfs.selector.FileSelector();

    List<OutputSelector> ouputFileSelectors = atask.getOutputSelectors();
    for (OutputSelector os : ouputFileSelectors) {
        org.objectweb.proactive.extensions.dataspaces.vfs.selector.FileSelector fs = os.getOutputFiles();
        if (!fs.getIncludes().isEmpty()) {
            fileSelector.addIncludes(fs.getIncludes());
        }

        if (!fs.getExcludes().isEmpty()) {
            fileSelector.addExcludes(fs.getExcludes());
        }
    }

    if (log.isDebugEnabled()) {
        log.debug("Looking at files in " + sourceUrl + " with " + fileSelector.getIncludes() + "-"
                + fileSelector.getExcludes());
        boolean goon = true;
        int cpt = 0;
        FileObject[] fos = null;
        while (goon) {
            fos = remotePullFolderFO.findFiles(fileSelector);
            goon = cpt < 50 && (fos == null || fos.length == 0);
            cpt++;
            if (goon) {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }
        }

        if (fos != null && fos.length > 0) {
            for (FileObject fo : fos) {
                log.debug("Found " + fo.getName());
            }
        } else {
            log.warn("Couldn't find " + fileSelector.getIncludes() + "-" + fileSelector.getExcludes() + " in "
                    + sourceUrl);
        }
    }
    if (awaitedjob.isAutomaticTransfer()) {
        DataTransferProcessor dtp = new DataTransferProcessor(remotePullFolderFO, localfolderFO, jobId, t_name,
                fileSelector);
        jobTracker.setTaskTransferring(jobId, t_name, true);
        threadPool.submit((Runnable) dtp);
    } else {
        log.debug("Copying files from " + sourceUrl + " to " + destUrl);

        try {
            localfolderFO.copyFrom(remotePullFolderFO, fileSelector);
        } catch (FileSystemException e) {
            log.error(e);
            throw e;
        } finally {
            jobTracker.setTaskTransferring(jobId, t_name, false);
            jobTracker.removeAwaitedTask(jobId, t_name);
        }

        log.debug("Finished copying files from " + sourceUrl + " to " + destUrl);
        // ok we can remove the task
    }
}

From source file:org.pentaho.di.job.entries.googledrive.JobEntryGoogleDriveExport.java

protected static void exportFile(Drive driveService, File driveFile, FileObject targetFile,
        GoogleDriveExportFormat exportMapping) throws KettleException {
    Exception savedException = null;
    if (exportMapping != null) {
        FileObject tempFile = KettleVFS.createTempFile(JobEntryGoogleDriveExport.class.getSimpleName(), ".tmp",
                System.getProperty("java.io.tmpdir"));
        try {/*  w w  w.  jav  a 2  s .  c  o  m*/
            OutputStream fos = tempFile.getContent().getOutputStream();
            BufferedOutputStream bos = new BufferedOutputStream(fos);
            try {
                driveService.files().export(driveFile.getId(), exportMapping.getMimeType())
                        .executeMediaAndDownloadTo(bos);
            } catch (IOException e) {
                // Throw this later, we want to close the output stream first
                savedException = new KettleException(
                        BaseMessages.getString(PKG, "GoogleDriveExport.Error.ExportingFile"), e);
            }
            try {
                bos.close();
            } catch (IOException ignore) {
                // Ignore
            }
            try {
                fos.close();
            } catch (IOException ignore) {
                // Ignore
            }
        } catch (IOException e) {
            savedException = new KettleException(
                    BaseMessages.getString(PKG, "GoogleDriveExport.Error.ExportingFile"), e);
        }
        if (tempFile != null) {
            try {
                targetFile.copyFrom(tempFile, Selectors.SELECT_SELF);
            } catch (FileSystemException e) {
                savedException = new KettleException(
                        BaseMessages.getString(PKG, "GoogleDriveExport.Error.MovingFileFromTemp"), e);
            }
        }
        if (savedException != null) {
            try {
                if (targetFile.exists()) {
                    targetFile.delete();
                }
            } catch (FileSystemException ignore) {
                // Ignore, couldn't delete a bad output file
            }
            throw new KettleException(savedException);
        }
    }
}

From source file:org.pentaho.di.plugins.fileopensave.providers.vfs.VFSFileProvider.java

/**
 * @param file//from w w w  .  jav  a2  s  .  c o  m
 * @param toPath
 * @param overwrite
 * @return
 * @throws FileException
 */
@Override
public VFSFile copy(VFSFile file, String toPath, boolean overwrite) throws FileException {
    try {
        FileObject fileObject = KettleVFS.getFileObject(file.getPath(), new Variables(),
                VFSHelper.getOpts(file.getPath(), file.getConnection()));
        FileObject copyObject = KettleVFS.getFileObject(toPath, new Variables(),
                VFSHelper.getOpts(file.getPath(), file.getConnection()));
        copyObject.copyFrom(fileObject, Selectors.SELECT_SELF);
        if (file instanceof VFSDirectory) {
            return VFSDirectory.create(copyObject.getParent().getPublicURIString(), fileObject,
                    file.getConnection());
        } else {
            return VFSFile.create(copyObject.getParent().getPublicURIString(), fileObject,
                    file.getConnection());
        }
    } catch (KettleFileException | FileSystemException e) {
        throw new FileException();
    }
}