Example usage for org.apache.commons.vfs2 FileUtil copyContent

List of usage examples for org.apache.commons.vfs2 FileUtil copyContent

Introduction

In this page you can find the example usage for org.apache.commons.vfs2 FileUtil copyContent.

Prototype

public static void copyContent(final FileObject srcFile, final FileObject destFile) throws IOException 

Source Link

Document

Copies the content from a source file to a destination file.

Usage

From source file:de.innovationgate.wgpublisher.design.fs.FileSystemDesignProvider.java

public static boolean upgradeOverlay(FileSystemDesignProvider originalDesignProvider, PluginID baseId,
        OverlayStatus status, FileObject targetFolder, String targetEncoding, Logger log,
        DesignFileValidator validator) throws Exception {

    if (!status.isUpdatedBaseDesign() && !status.isNewOverlay()) {
        throw new WGDesignSyncException(
                "Used base plugin is no higher version than overlay compliance version. Cannot perform upgrade");
    }/* ww w.  j  a  v  a  2 s .c  o m*/

    if (status.isNewOverlay()) {
        log.info("Initializing empty overlay");
    } else {
        log.info("Upgrading overlay from base design version " + status.getCompliantBaseVersion() + " to "
                + status.getCurrentBaseVersion());
    }

    // Creating new folders (Done separately because there may be empty folders in the overlay which would not be created via resource changes)
    for (String folder : status.getNewFolders()) {
        FileObject targetFile = targetFolder.resolveFile(folder);
        if (!targetFile.exists()) {
            log.info("Adding new overlay folder "
                    + targetFolder.getName().getRelativeName(targetFile.getName()));
            targetFile.createFolder();
        }
    }

    // Perform resource changes
    boolean conflictFileCreated = false;
    for (ChangedDocument resource : status.getChangedDocuments().values()) {
        if (performChange(resource, originalDesignProvider, status, targetEncoding, targetFolder, log,
                validator)) {
            conflictFileCreated = true;
        }
    }

    // Overwrite plugin version
    status.getOverlayData().setBasepluginVersion(baseId.getVersion().toString());

    // Write new overlay data file
    FileObject targetFCFolder = targetFolder.resolveFile(DesignDirectory.FOLDERNAME_FILES);
    FileObject systemFC = targetFCFolder.resolveFile("system");
    FileObject overlayDataFile = systemFC.resolveFile(OverlayDesignProvider.OVERLAY_DATA_FILE);
    OutputStream out = new BufferedOutputStream(overlayDataFile.getContent().getOutputStream(false));
    status.getOverlayData().write(out);
    out.flush();
    out.close();

    // Eventually update base-csconfig.xml
    FileObject baseCsConfigFile = originalDesignProvider.getFilesFolder().resolveFile("system/csconfig.xml");
    if (baseCsConfigFile.exists()) {
        String sourceHash = MD5HashingInputStream.getStreamHash(baseCsConfigFile.getContent().getInputStream());
        String targetHash = "";
        FileObject baseCsConfigFileOnOverlay = systemFC.resolveFile("base-csconfig.xml");
        if (baseCsConfigFileOnOverlay.exists()) {
            targetHash = MD5HashingInputStream
                    .getStreamHash(baseCsConfigFileOnOverlay.getContent().getInputStream());
        }
        if (!sourceHash.equals(targetHash)) {
            baseCsConfigFileOnOverlay.delete();
            FileUtil.copyContent(baseCsConfigFile, baseCsConfigFileOnOverlay);
        }
    }

    // Eventually update the dependency to the base plugin on csconfig.xml's plugin config
    FileObject overlayCsConfigFile = systemFC.resolveFile("csconfig.xml");
    if (overlayCsConfigFile.exists()) {
        CSConfig overlayCsConfig = CSConfig.load(overlayCsConfigFile);
        if (overlayCsConfig.getPluginConfig() != null) {
            boolean dependencyUpdated = false;
            for (PluginID id : overlayCsConfig.getPluginConfig().getDependencies()) {
                if (id.getUniqueName().equals(baseId.getUniqueName())
                        && !id.getVersion().equals(baseId.getVersion())) {
                    Version dependencyVersion = new Version(baseId.getVersion().getMajorVersion(),
                            baseId.getVersion().getMinorVersion(), baseId.getVersion().getMaintenanceVersion(),
                            baseId.getVersion().getPatchVersion(), 0);
                    id.setVersion(dependencyVersion);
                    dependencyUpdated = true;
                }
            }

            if (dependencyUpdated) {
                log.info("Updating dependency to base plugin in overlay plugin to new version "
                        + baseId.getVersion());
                overlayCsConfig.write(overlayCsConfigFile);
            }
        }
    }

    // Read/Write design configuration model to ensure correct storage versions of csconfig.xml (#00003634)
    FileObject designDefinitionFile = DesignDirectory.getDesignDefinitionFile(targetFolder);
    WGADesignConfigurationModel model = new WGADesignConfigurationModel(
            new File(designDefinitionFile.getName().getPath()));
    model.saveChanges();

    // Clear the overlay status
    status.overlayWasUpgraded();

    return conflictFileCreated;

}

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

public static boolean copyContents(String fromLocation, String toLocation)
        throws FileNotFoundException, VFSException {

    FileObject fromFile = null;//w ww  .  j  a va 2s.c  om
    FileObject toFile = null;
    boolean retVal = false;

    try {
        URL fromLocationURL = new URL(fromLocation);

        // log.debug("fromLocationURL: " + fromLocationURL.toString());

        if (exists(fromLocationURL)) {
            // log.debug(fromLocationURL + " Exists");

            fromFile = resolveFile(fromLocationURL);
            toFile = resolveFile(new URL("file:///" + toLocation));

            // now copy the contents to the destination

            try {
                log.info("Downloading " + fromFile);

                FileUtil.copyContent(fromFile, toFile);

                retVal = true;
            } catch (IOException e) {
                e.printStackTrace();
            }

        } else {
            log.debug("From Location " + fromLocation + " does not exist. Please check if it is a valid path");
        }

    } catch (MalformedURLException e) {
        e.printStackTrace();
    }

    return retVal;
}

From source file:org.kalypso.commons.io.VFSUtilities.java

/**
 * This function copies a source file to a given destination. If no filename is given in the destination file handle,
 * the filename of the source is used.<br>
 * <br>//from  w w w.j av  a 2  s .  c o  m
 * It is tried to copy the file three times. If all three tries has failed, only then an IOException is thrown. <br>
 * All other exceptions are thrown normally.
 *
 * @param source
 *          The source file.
 * @param destination
 *          The destination file or path.
 * @param overwrite
 *          If set, always overwrite existing and newer files
 */
public static void copyFileTo(final FileObject source, final FileObject destination, final boolean overwrite)
        throws IOException {
    if (source.equals(destination)) {
        KalypsoCommonsDebug.DEBUG.printf(Messages.getString("org.kalypso.commons.io.VFSUtilities.1"), //$NON-NLS-1$
                source.getName(), destination.getName());
        return;
    }

    /* Some variables for handling the errors. */
    boolean success = false;
    int cnt = 0;

    while (success == false) {
        try {
            if (FileType.FOLDER.equals(source.getType()))
                throw new IllegalArgumentException(Messages.getString("org.kalypso.commons.io.VFSUtilities.2")); //$NON-NLS-1$

            /* If the destination is only a directory, use the sources filename for the destination file. */
            FileObject destinationFile = destination;
            if (FileType.FOLDER.equals(destination.getType()))
                destinationFile = destination.resolveFile(source.getName().getBaseName());

            if (overwrite || !destinationFile.exists()
                    || destinationFile.getContent().getSize() != source.getContent().getSize()) {
                /* Copy file. */
                KalypsoCommonsDebug.DEBUG.printf("Copy file '%s' to '%s'...%n", source.getName(), //$NON-NLS-1$
                        destinationFile.getName());
                FileUtil.copyContent(source, destinationFile);
                source.close();
            }

            /* End copying of this file, because it was a success. */
            success = true;
        } catch (final IOException e) {
            /* An error has occurred while copying the file. */
            KalypsoCommonsDebug.DEBUG.printf("An error has occured with the message: %s%n", //$NON-NLS-1$
                    e.getLocalizedMessage());

            /* If a certain amount (here 2) of retries was reached before, re-throw the error. */
            if (cnt >= 2) {
                KalypsoCommonsDebug.DEBUG.printf("The second retry has failed, rethrowing the error...%n"); //$NON-NLS-1$
                throw e;
            }

            /* Retry the copying of the file. */
            cnt++;
            KalypsoCommonsDebug.DEBUG.printf("Retry: %s%n", String.valueOf(cnt)); //$NON-NLS-1$
            success = false;

            /* Wait for some milliseconds. */
            try {
                Thread.sleep(1000);
            } catch (final InterruptedException e1) {
                /*
                 * Runs in the next loop then and if no error occurs then, it is ok. If an error occurs again, it is an
                 * exception thrown on the last failed retry or it is slept again.
                 */
            }
        }
    }
}

From source file:org.kalypso.service.unittests.WebDavWrite.java

/**
 * This function tries to copy a file to a webdav.
 *//* w w w  .  ja  v a  2s  . c  om*/
@Test
public void testWebDavWrite() throws IOException {
    final DefaultFileSystemManager manager = new DefaultFileSystemManager();
    manager.addProvider("webdav", new WebdavFileProvider());
    manager.addProvider("file", new DefaultLocalFileProvider());
    manager.addProvider("tmp", new TemporaryFileProvider());

    manager.setDefaultProvider(new UrlFileProvider());
    manager.setFilesCache(new DefaultFilesCache());
    manager.setTemporaryFileStore(new DefaultFileReplicator());
    manager.init();

    final File file = new File(FileUtilities.TMP_DIR, "davWrite.txt");
    final FileObject testFile = manager.toFileObject(file);

    final FileObject davFile = manager
            .resolveFile("webdav://albert:gnimfe@ibpm.bjoernsen.de/dav/pub/Test/test.txt");
    Assert.assertNotNull(davFile);

    FileUtil.copyContent(testFile, davFile);

    Assert.assertTrue(davFile.exists());
}