Example usage for org.apache.commons.io FileUtils copyDirectory

List of usage examples for org.apache.commons.io FileUtils copyDirectory

Introduction

In this page you can find the example usage for org.apache.commons.io FileUtils copyDirectory.

Prototype

public static void copyDirectory(File srcDir, File destDir) throws IOException 

Source Link

Document

Copies a whole directory to a new location preserving the file dates.

Usage

From source file:com.taobao.android.builder.tasks.tpatch.TPatchDiffApkBuildTask.java

@TaskAction
public void doApkBuild() throws Exception {

    //TODO ?2zip/*from  w  w  w  .  j  a v  a2  s.  c o m*/
    apkFile = getApkFile();
    diffAPkFile = getDiffAPkFile();

    File tmpWorkDir = new File(diffAPkFile.getParentFile(), "tmp-apk");
    if (tmpWorkDir.exists()) {
        FileUtils.deleteDirectory(tmpWorkDir);
    }
    if (!tmpWorkDir.exists()) {
        tmpWorkDir.mkdirs();
    }

    Map zipEntityMap = new HashMap();
    ZipUtils.unzip(apkFile, tmpWorkDir.getAbsolutePath(), "UTF-8", zipEntityMap, true);

    FileUtils.deleteDirectory(new File(tmpWorkDir, "assets"));
    FileUtils.deleteDirectory(new File(tmpWorkDir, "res"));
    FileUtils.forceDelete(new File(tmpWorkDir, "resources.arsc"));
    FileUtils.forceDelete(new File(tmpWorkDir, "AndroidManifest.xml"));

    File resdir = new File(diffAPkFile.getParentFile(), "tmp-diffResAp");
    resdir.mkdirs();
    ZipUtils.unzip(getResourceFile(), resdir.getAbsolutePath(), "UTF-8", new HashMap<String, ZipEntry>(), true);

    FileUtils.copyDirectory(resdir, tmpWorkDir);
    ZipUtils.rezip(diffAPkFile, tmpWorkDir, zipEntityMap);

    FileUtils.deleteDirectory(tmpWorkDir);
    FileUtils.deleteDirectory(resdir);

}

From source file:com.mindquarry.desktop.workspace.conflict.DeleteWithModificationConflict.java

public void afterUpdate() throws ClientException, IOException {
    switch (action) {
    case UNKNOWN:
        // client did not set a conflict resolution
        log.error("DeleteWithModificationConflict with no action set: " + status.getPath());
        break;//from www.j  a  v a 2s.  c o  m

    case DELETE:
        log.info("now deleting again " + status.getPath());

        // Delete file or directory -- works in all cases:
        // 1. Local container delete with remote updates:
        //    Update operation makes sure that the remote updates are
        //    adopted locally, re-creating the affected files if necessary.
        //    So they need to be deleted again. Commit deletes remote
        //    directory.
        //
        // 2. Remote container delete with local updates:
        //    Update operation deletes everything in the remotely deleted
        //    directory apart from files affected by local changes, which
        //    are left unversioned and need to be deleted locally.
        //
        // 3. Remotely modified file deleted locally:
        //    Update operation makes sure that the remote update is adopted
        //    locally, re-creating the affected file if necessary. Hence
        //    need to delete the local file again.
        //
        // 4. Locally modified file deleted remotely:
        //    Update operation leaves the affected file as unversioned which
        //    is therefore deleted.
        File file = new File(status.getPath());
        FileUtils.forceDelete(file);

        break;

    case ONLYKEEPMODIFIED:
        log.info("keeping added/modified from remote: " + status.getPath());

        if (localDelete) {
            // revert deletion status for local deletions
            client.revert(status.getPath(), true);
        } else {
            // only re-add files/directories that were added/modified
            client.add(status.getPath(), false);
            if (otherMods != null) {
                for (Status s : otherMods) {
                    client.add(s.getPath(), false);
                }
            }
        }

        break;

    case REVERTDELETE:
        if (localDelete == false) {
            log.info("reverting remote delete: " + status.getPath());
            // Revert remote deletes in three steps:
            // 1. Restore last revision before deletion (incl. history)
            // 2. Redo changes by replacing with local files
            // 3. Re-add locally added files

            // 1. Restore last revision before deletion (incl. history)
            File targetFile = new File(status.getPath());
            String parent = targetFile.getParent();
            Number restoreRev = null;
            String delFile = null;

            // Get all log messages since last update
            LogMessage[] logMessages = client.logMessages(parent, Revision.BASE, Revision.HEAD, false, true);

            // need to translate svn URLs from ChangePath to wc paths, so we
            // have to find out about the working copy root to see what the
            // URL prefix of the checkout is
            File wcDir = new File(status.getPath());
            if (tempCopy.isFile()) {
                wcDir = wcDir.getParentFile();
            }
            File wcRoot = SVNAdminDirectoryLocator.findWCRoot(wcDir);
            Info info = client.info(wcRoot.getPath());

            // eg. http://svn.server.com/team1/trunk/my%20path
            String wcRootURL = info.getUrl();
            // eg. http://svn.server.com/team1
            String repoRootURL = info.getRepository();
            // eg. /trunk/my%20path
            String checkoutPrefixURL = wcRootURL.substring(repoRootURL.length());
            // eg. /trunk/my path
            String checkoutPrefix = SVNEncodingUtil.uriDecode(checkoutPrefixURL);

            // eg. /home/peter/checkout/team1
            String wcRootPath = wcRoot.getPath();
            // eg. /home/peter/checkout/team1/dir/file.txt
            String currentPath = status.getPath();
            // eg. /dir/file.txt (the one to look for in the ChangePaths below)
            String relativePath = currentPath.substring(wcRootPath.length());

            // Look for revision in which the file/dir was (last) deleted
            for (LogMessage logMessage : logMessages) {
                for (ChangePath changePath : logMessage.getChangedPaths()) {

                    // eg. /trunk/my path/dir/file.txt
                    String cp = changePath.getPath();
                    // eg. /dir/file.txt
                    String relativeChangePath = cp.substring(checkoutPrefix.length());

                    if (relativePath.equals(relativeChangePath) && changePath.getAction() == 'D') {
                        // want to restore last revision before deletion
                        restoreRev = new Number(logMessage.getRevision().getNumber() - 1);
                        delFile = cp;
                        log.debug("found revision of deletion: '" + changePath.getPath()
                                + "' was deleted in revision " + logMessage.getRevision().toString());
                    }
                }
            }

            // Restore deleted version with version history
            if (restoreRev != null) {
                log.debug("copy " + repoRootURL + delFile + " to " + status.getPath() + ", restoreRev "
                        + restoreRev);

                client.copy(repoRootURL + delFile, status.getPath(), null, restoreRev);
            } else {
                log.error("Failed to restore deleted version of " + status.getPath());
            }

            // 2. Redo changes by replacing with local files (move B => A)
            File destination = new File(status.getPath());
            if (tempCopy.isFile()) {
                log.debug("copy file from " + tempCopy + " to " + destination);
                FileUtils.copyFile(tempCopy, destination);
                tempCopy.delete();
            } else {
                log.debug("copy dir from " + tempCopy + " to " + destination);
                FileUtils.copyDirectory(tempCopy, destination);
                FileUtils.deleteDirectory(tempCopy);
            }

            // 3. Re-add locally added files
            // Cannot just add directories recursively since the copy
            // operation above automatically adds them and adding them twice
            // results in an error. So just add files that were added
            // locally.
            if (otherMods != null) {
                for (Status s : otherMods) {
                    if (s.getTextStatus() == StatusKind.added) {
                        log.debug("re-adding " + s.getPath());
                        client.add(s.getPath(), false);
                    }
                }
            }
        }

        break;
    }
}

From source file:com.collective.celos.CelosClientServerTest.java

@Test
public void testGetWorkflowStatusTransitionToSuccessFailure() throws Exception {

    File src = new File(Thread.currentThread().getContextClassLoader()
            .getResource("com/collective/celos/client/wf-list").toURI());
    FileUtils.copyDirectory(src, workflowsDir);

    celosClient.iterateScheduler();// ww  w  .j  a  v a2  s  .c  o m
    celosClient.iterateScheduler();
    celosClient.iterateScheduler();

    List<SlotState> slotStates = celosClient
            .getWorkflowStatus(new WorkflowID("workflow-Itrntinliztin")).getSlotStates();
    Assert.assertEquals(slotStates.size(), SLOTS_IN_CELOS_SERVER_SLIDING_WINDOW);

    SlotState slotStateFst = slotStates.get(slotStates.size() - 1);
    Assert.assertEquals(slotStateFst.getStatus(), SlotState.Status.FAILURE);
    Assert.assertNotNull(slotStateFst.getExternalID());
    Assert.assertEquals(slotStateFst.getRetryCount(), 0);
}

From source file:com.taobao.android.builder.tools.cache.SimpleLocalCache.java

@Override
public boolean fetchFile(String type, String key, File localFile, boolean folder) throws FileCacheException {

    if (StringUtils.isEmpty(key)) {
        throw new FileCacheException("cache key is empty ");
    }// ww  w .  j  a va2  s . c  o  m

    File cacheFile = getLocalCacheFile(type, key);

    try {
        if (cacheFile.exists() && cacheFile.length() > 0) {
            if (cacheFile.isDirectory()) {
                FileUtils.copyDirectory(cacheFile, localFile);
            } else {
                FileUtils.copyFile(cacheFile, localFile);
            }
        }
    } catch (IOException e) {
        throw new FileCacheException(e.getMessage(), e);
    }

    return true;
}

From source file:ee.ria.xroad.asyncdb.AsyncDBIntegrationTest.java

private static void setUpCorruptDb() throws Exception {
    File corruptDbDir = new File(CORRUPT_DB_DIR);
    corruptDbDir.mkdir();//from  w  ww .  ja v a 2 s .  com

    FileUtils.copyDirectory(new File("src/test/resources/db_corrupt"), corruptDbDir);

    System.setProperty(SystemProperties.ASYNC_DB_PATH, CORRUPT_DB_DIR);

    ClientId provider = ClientId.create("EE", "GOV", "XTS4CLIENT");
    queue = AsyncDB.getMessageQueue(provider);
}

From source file:eu.asterics.ape.packaging.Packager.java

/**
 * Copyies the given srcURI to the given targetDir directory. 
 * @param srcURI//from ww  w.  j  a v a2s.co m
 * @param targetDir
 * @param resolveTargetSubDirs: true: Resolves subdirs of bin/ARE to appropriate subdirs in a target directory.
 * @throws URISyntaxException
 * @throws IOException
 */
public void copyURI(URI srcURI, File targetDir, boolean resolveAREBaseURISubDirs)
        throws URISyntaxException, IOException {
    try {
        File targetSubDir = targetDir;
        File src = ResourceRegistry.toFile(srcURI);

        //If we should resolve against ARE subfolders
        if (resolveAREBaseURISubDirs) {
            //Only works if the URI contains the currently active ARE.baseURI.
            //Determine relative src dir which will then be resolved against the base target dir.
            File relativeSrc = ResourceRegistry.toFile(ResourceRegistry.getInstance().toRelative(srcURI));

            //Determine parent folder of relativeSrc File
            targetSubDir = src.isDirectory() ? relativeSrc : relativeSrc.getParentFile();

            if (targetSubDir != null) {
                //Resolve targetSubDir against targetDir
                targetSubDir = ResourceRegistry.resolveRelativeFilePath(targetDir, targetSubDir.getPath());
            } else {
                targetSubDir = targetDir;
            }
        }
        //Actually copy file
        Notifier.debug("Copying " + src + " -> " + targetSubDir, null);
        if (src.isDirectory()) {
            FileUtils.copyDirectory(src, targetSubDir);
        } else {
            FileUtils.copyFileToDirectory(src, targetSubDir);
        }
    } catch (MalformedURLException e) {
        //else try if it is a URL that can be fetched from anywhere else.
        Notifier.warning("URL resources not supported so far", e);
    }
}

From source file:com.taobao.android.builder.tools.cache.FileCacheCenter.java

public static void fetchFile(String type, String key, boolean folder, boolean remote, File dest)
        throws FileCacheException {

    if (!BUILD_CACHE_ENABLED) {
        return;//from   ww w . j a v  a  2s. c  o  m
    }

    File cacheFile = queryFile(type, key, folder, remote);

    if (null != cacheFile && cacheFile.exists()) {

        try {
            if (cacheFile.isFile()) {
                FileUtils.copyFile(cacheFile, dest);
            } else {
                FileUtils.copyDirectory(cacheFile, dest);
            }
            logger.log(type + "." + key + " fech  file success  " + dest.getAbsolutePath());
        } catch (Throwable e) {
            throw new FileCacheException(e.getMessage(), e);
        }

    }

}

From source file:com.aliyun.odps.graph.local.LocalGraphJobRunner.java

private void moveOutputs() throws IOException {
    for (TableInfo table : LocalGraphRunUtils.getOutputTables(conf)) {
        String label = table.getLabel();

        String projName = table.getProjectName();
        if (projName == null) {
            projName = SessionState.get().getOdps().getDefaultProject();
        }/*from   w w  w  . ja v  a  2 s  .c  o m*/
        String tblName = table.getTableName();
        Map<String, String> partSpec = table.getPartSpec();

        File tempTblDir = jobDirecotry.getOutputDir(table.getLabel());
        File whOutputDir = wareHouse.createPartitionDir(projName, tblName, PartitionUtils.convert(partSpec));
        if (wareHouse.existsTable(projName, tblName)) {
            LOG.info("Reload warehouse table:" + tblName);
            if (!wareHouse.isRetainTempData()) {
                LocalRunUtils.removeDataFiles(whOutputDir);
            }
            wareHouse.copyDataFiles(tempTblDir, null, whOutputDir, wareHouse.getInputColumnSeperator());
        } else {
            LOG.info("Copy output to warehouse: label=" + label + " -> " + whOutputDir.getAbsolutePath());
            FileUtils.copyDirectory(tempTblDir, whOutputDir);
        }
    }
}

From source file:net.doubledoordev.cmd.CurseModpackDownloader.java

private void unpackOrMoveJson() throws ZipException, IOException {
    String inputExtension = FilenameUtils.getExtension(input.getName());
    switch (inputExtension.toLowerCase()) {
    case "zip":
        ZipFile zipFile = new ZipFile(input);
        FileHeader manifestHeader = zipFile.getFileHeader("manifest.json");
        if (manifestHeader == null)
            throw new IOException("There is no manifest in the zip. Corrupt zip?");
        zipFile.extractFile(manifestHeader, output.getPath());
        manifest = GSON.fromJson(FileUtils.readFileToString(manifestFile), Manifest.class);
        zipFile.setRunInThread(true);/*from www. j  a  va2 s.c  o m*/
        ProgressMonitor pm = zipFile.getProgressMonitor();
        zipFile.extractAll(output.getPath());
        long lastUpdate = 0L;
        while (pm.getState() == ProgressMonitor.STATE_BUSY) {
            if (System.currentTimeMillis() - lastUpdate > 5000) {
                if (!quiet)
                    logger.println("Unzipping... " + pm.getPercentDone() + "%");
                lastUpdate = System.currentTimeMillis();
            }
            smallDelay();
        }
        File overrides = new File(output, manifest.overrides);
        FileUtils.copyDirectory(overrides, output);
        FileUtils.deleteDirectory(overrides);
        break;
    case "json":
        if (!inputEqualsOutput)
            FileUtils.copyFile(input, manifestFile);
        manifest = GSON.fromJson(FileUtils.readFileToString(manifestFile), Manifest.class);
        break;
    default:
        throw new IOException("Input file needs to be a .json or .zip. " + input.toString() + " is neither.");
    }
}

From source file:com.collective.celos.CelosClientServerTest.java

@Test
public void testGetWorkflowStatusInPast() throws Exception {

    ScheduledTime timeInPast = new ScheduledTime("2000-12-01T00:00Z");
    File src = new File(Thread.currentThread().getContextClassLoader()
            .getResource("com/collective/celos/client/wf-list").toURI());
    FileUtils.copyDirectory(src, workflowsDir);

    List<SlotState> slotStates = celosClient.getWorkflowStatus(new WorkflowID("workflow-4")).getSlotStates();
    Assert.assertEquals(slotStates.size(), SLOTS_IN_CELOS_SERVER_SLIDING_WINDOW);
    Assert.assertTrue(slotStates.get(slotStates.size() - 1).getScheduledTime().getDateTime()
            .isAfter(timeInPast.getDateTime().plusYears(1)));

    slotStates = celosClient.getWorkflowStatus(new WorkflowID("workflow-4"), timeInPast).getSlotStates();
    Assert.assertEquals(slotStates.get(slotStates.size() - 1).getScheduledTime(),
            timeInPast.minusDays(SchedulerConfiguration.SLIDING_WINDOW_DAYS));
    Assert.assertEquals(slotStates.get(0).getScheduledTime(), timeInPast.minusHours(1));

    slotStates = celosClient.getWorkflowStatus(new WorkflowID("workflow-4"), timeInPast.plusSeconds(1))
            .getSlotStates();/*w w w . j  a  v a  2 s .  c  om*/
    Assert.assertEquals(slotStates.get(0).getScheduledTime(), timeInPast);
}