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

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

Introduction

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

Prototype

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

Source Link

Document

Moves a directory.

Usage

From source file:com.alibaba.jstorm.daemon.nimbus.ServiceHandler.java

@Override
public void updateTopology(String name, String uploadedLocation, String updateConf)
        throws NotAliveException, InvalidTopologyException, TException {
    try {//w  ww  .  jav a2 s  . c  o  m
        checkTopologyActive(data, name, true);

        String topologyId = null;
        StormClusterState stormClusterState = data.getStormClusterState();
        topologyId = Cluster.get_topology_id(stormClusterState, name);
        if (topologyId == null) {
            throw new NotAliveException(name);
        }
        if (uploadedLocation != null) {
            String stormroot = StormConfig.masterStormdistRoot(conf, topologyId);

            int lastIndexOf = uploadedLocation.lastIndexOf("/");
            // /local-dir/nimbus/inbox/xxxx/
            String tmpDir = uploadedLocation.substring(0, lastIndexOf);

            // /local-dir/nimbus/inbox/xxxx/stormjar.jar
            String stormJarPath = StormConfig.stormjar_path(tmpDir);

            File file = new File(uploadedLocation);
            if (file.exists()) {
                file.renameTo(new File(stormJarPath));
            } else {
                throw new FileNotFoundException("Source \'" + uploadedLocation + "\' does not exist");
            }
            // move fileDir to /local-dir/nimbus/topologyid/
            File srcDir = new File(tmpDir);
            File destDir = new File(stormroot);
            try {
                FileUtils.moveDirectory(srcDir, destDir);
            } catch (FileExistsException e) {
                FileUtils.copyDirectory(srcDir, destDir);
                FileUtils.deleteQuietly(srcDir);
            }
            // Update downloadCode timeStamp
            StormConfig.write_nimbus_topology_timestamp(data.getConf(), topologyId, System.currentTimeMillis());
            LOG.info("update jar of " + name + " successfully");
        }

        Map topoConf = StormConfig.read_nimbus_topology_conf(data.getConf(), topologyId);
        Map<Object, Object> config = (Map<Object, Object>) JStormUtils.from_json(updateConf);
        topoConf.putAll(config);
        StormConfig.write_nimbus_topology_conf(data.getConf(), topologyId, topoConf);

        LOG.info("update topology " + name + " successfully");
        NimbusUtils.transitionName(data, name, true, StatusType.update_topology, config);

    } catch (NotAliveException e) {
        String errMsg = "Error, no this topology " + name;
        LOG.error(errMsg, e);
        throw new NotAliveException(errMsg);
    } catch (Exception e) {
        String errMsg = "Failed to update topology " + name;
        LOG.error(errMsg, e);
        throw new TException(errMsg);
    }

}

From source file:org.ala.util.RebuildFromFS.java

/**
 * /*ww w.jav a2s . co m*/
 * @param directoryRoot
 * @param newDirectoryRoot
 * @throws Exception
 */
private void rebuildFS(String directoryRoot, String newDirectoryRoot) throws Exception {

    int fileIndex = 1;
    File oldDirectory = new File(directoryRoot);

    //this gives the directory per infosource
    File[] dirs = oldDirectory.listFiles((FileFilter) DirectoryFileFilter.DIRECTORY);

    //iterate through each infosource directory
    for (File infosourceDir : dirs) {

        System.out.println("Reading directory: " + infosourceDir.getAbsolutePath());

        String infosource = infosourceDir.getName();

        File[] subDirectories = infosourceDir.listFiles((FileFilter) DirectoryFileFilter.DIRECTORY);

        for (File subDirectory : subDirectories) {

            File[] directories = subDirectory.listFiles((FileFilter) DirectoryFileFilter.DIRECTORY);

            String subDirectoryPath = Integer.toString(fileIndex / 10000);

            //move each directory
            FileUtils.forceMkdir(
                    new File(directoryRoot + File.separator + infosource + File.separator + subDirectoryPath));

            for (File directory : directories) {

                FileUtils.moveDirectory(directory, new File(newDirectoryRoot + File.separator + infosource
                        + File.separator + subDirectoryPath + File.separator + fileIndex));
                fileIndex++;
            }
        }
    }

    //remove the temporary dir
    FileUtils.forceDelete(new File(directoryRoot));
    FileUtils.moveDirectory(new File(newDirectoryRoot), new File(directoryRoot));
}

From source file:org.apache.archiva.webdav.ArchivaDavResource.java

@Override
public void move(DavResource destination) throws DavException {
    if (!exists()) {
        throw new DavException(HttpServletResponse.SC_NOT_FOUND, "Resource to copy does not exist.");
    }/*from www .  ja v a 2 s  .  co m*/

    try {
        ArchivaDavResource resource = checkDavResourceIsArchivaDavResource(destination);
        if (isCollection()) {
            FileUtils.moveDirectory(getLocalResource(), resource.getLocalResource());

            triggerAuditEvent(remoteAddr, locator.getRepositoryId(), logicalResource,
                    AuditEvent.MOVE_DIRECTORY);
        } else {
            FileUtils.moveFile(getLocalResource(), resource.getLocalResource());

            triggerAuditEvent(remoteAddr, locator.getRepositoryId(), logicalResource, AuditEvent.MOVE_FILE);
        }

        log.debug("{}{}' moved to '{}' (current user '{}')", (isCollection() ? "Directory '" : "File '"),
                getLocalResource().getName(), destination, this.principal);

    } catch (IOException e) {
        throw new DavException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e);
    }
}

From source file:org.apache.bookkeeper.bookie.FileSystemUpgrade.java

public static void upgrade(ServerConfiguration conf)
        throws BookieException.UpgradeException, InterruptedException {
    LOG.info("Upgrading...");

    ZooKeeper zk = newZookeeper(conf);//from ww w. j a v a 2s . c  o  m
    try {
        Map<File, File> deferredMoves = new HashMap<File, File>();
        Cookie.Builder cookieBuilder = Cookie.generateCookie(conf);
        Cookie c = cookieBuilder.build();
        for (File d : getAllDirectories(conf)) {
            LOG.info("Upgrading {}", d);
            int version = detectPreviousVersion(d);
            if (version == Cookie.CURRENT_COOKIE_LAYOUT_VERSION) {
                LOG.info("Directory is current, no need to upgrade");
                continue;
            }
            try {
                File curDir = new File(d, BookKeeperConstants.CURRENT_DIR);
                File tmpDir = new File(d, "upgradeTmp." + System.nanoTime());
                deferredMoves.put(curDir, tmpDir);
                if (!tmpDir.mkdirs()) {
                    throw new BookieException.UpgradeException(
                            "Could not create temporary directory " + tmpDir);
                }
                c.writeToDirectory(tmpDir);

                String[] files = d.list(new FilenameFilter() {
                    public boolean accept(File dir, String name) {
                        return BOOKIE_FILES_FILTER.accept(dir, name) && !(new File(dir, name).isDirectory());
                    }
                });
                HardLink.createHardLinkMult(d, files, tmpDir);

                linkIndexDirectories(d, tmpDir);
            } catch (IOException ioe) {
                LOG.error("Error upgrading {}", d);
                throw new BookieException.UpgradeException(ioe);
            }
        }

        for (Map.Entry<File, File> e : deferredMoves.entrySet()) {
            try {
                FileUtils.moveDirectory(e.getValue(), e.getKey());
            } catch (IOException ioe) {
                String err = String.format("Error moving upgraded directories into place %s -> %s ",
                        e.getValue(), e.getKey());
                LOG.error(err, ioe);
                throw new BookieException.UpgradeException(ioe);
            }
        }

        if (deferredMoves.isEmpty()) {
            return;
        }

        try {
            c.writeToZooKeeper(zk, conf, Version.NEW);
        } catch (KeeperException ke) {
            LOG.error("Error writing cookie to zookeeper");
            throw new BookieException.UpgradeException(ke);
        }
    } catch (IOException ioe) {
        throw new BookieException.UpgradeException(ioe);
    } finally {
        zk.close();
    }
    LOG.info("Done");
}

From source file:org.apache.geode.distributed.internal.ClusterConfigurationService.java

public void renameExistingSharedConfigDirectory() {
    File configDirFile = new File(configDirPath);
    if (configDirFile.exists()) {
        String configDirFileName2 = CLUSTER_CONFIG_ARTIFACTS_DIR_NAME
                + new SimpleDateFormat("yyyyMMddhhmm").format(new Date()) + "." + System.nanoTime();
        File configDirFile2 = new File(configDirFile.getParent(), configDirFileName2);
        try {/*  w w w  .jav a2s .  c  o m*/
            FileUtils.moveDirectory(configDirFile, configDirFile2);
        } catch (IOException e) {
            logger.info(e);
        }
    }
}

From source file:org.apache.storm.daemon.supervisor.SyncSupervisorEvent.java

private void downloadLocalStormCode(Map conf, String stormId, String masterCodeDir, Localizer localizer)
        throws Exception {

    String tmproot = ConfigUtils.supervisorTmpDir(conf) + Utils.FILE_PATH_SEPARATOR + Utils.uuid();
    String stormroot = ConfigUtils.supervisorStormDistRoot(conf, stormId);
    BlobStore blobStore = Utils.getNimbusBlobStore(conf, masterCodeDir, null);
    FileOutputStream codeOutStream = null;
    FileOutputStream confOutStream = null;
    try {//from w ww  .j av a 2  s.  c o  m
        FileUtils.forceMkdir(new File(tmproot));
        String stormCodeKey = ConfigUtils.masterStormCodeKey(stormId);
        String stormConfKey = ConfigUtils.masterStormConfKey(stormId);
        String codePath = ConfigUtils.supervisorStormCodePath(tmproot);
        String confPath = ConfigUtils.supervisorStormConfPath(tmproot);
        codeOutStream = new FileOutputStream(codePath);
        blobStore.readBlobTo(stormCodeKey, codeOutStream, null);
        confOutStream = new FileOutputStream(confPath);
        blobStore.readBlobTo(stormConfKey, confOutStream, null);
    } finally {
        if (codeOutStream != null)
            codeOutStream.close();
        if (confOutStream != null)
            codeOutStream.close();
        blobStore.shutdown();
    }
    FileUtils.moveDirectory(new File(tmproot), new File(stormroot));
    SupervisorUtils.setupStormCodeDir(conf, ConfigUtils.readSupervisorStormConf(conf, stormId), stormroot);
    ClassLoader classloader = Thread.currentThread().getContextClassLoader();

    String resourcesJar = resourcesJar();

    URL url = classloader.getResource(ConfigUtils.RESOURCES_SUBDIR);

    String targetDir = stormroot + Utils.FILE_PATH_SEPARATOR + ConfigUtils.RESOURCES_SUBDIR;

    if (resourcesJar != null) {
        LOG.info("Extracting resources from jar at {} to {}", resourcesJar, targetDir);
        Utils.extractDirFromJar(resourcesJar, ConfigUtils.RESOURCES_SUBDIR, stormroot);
    } else if (url != null) {

        LOG.info("Copying resources at {} to {} ", url.toString(), targetDir);
        if (url.getProtocol() == "jar") {
            JarURLConnection urlConnection = (JarURLConnection) url.openConnection();
            Utils.extractDirFromJar(urlConnection.getJarFileURL().getFile(), ConfigUtils.RESOURCES_SUBDIR,
                    stormroot);
        } else {
            FileUtils.copyDirectory(new File(url.getFile()), (new File(targetDir)));
        }
    }
}

From source file:org.apache.storm.daemon.supervisor.SyncSupervisorEvent.java

/**
 * Downloading to permanent location is atomic
 * //from w  ww  .j  a va  2 s  .  c  o  m
 * @param conf
 * @param stormId
 * @param masterCodeDir
 * @param localizer
 * @throws Exception
 */
private void downloadDistributeStormCode(Map conf, String stormId, String masterCodeDir, Localizer localizer)
        throws Exception {

    String tmproot = ConfigUtils.supervisorTmpDir(conf) + Utils.FILE_PATH_SEPARATOR + Utils.uuid();
    String stormroot = ConfigUtils.supervisorStormDistRoot(conf, stormId);
    ClientBlobStore blobStore = Utils.getClientBlobStoreForSupervisor(conf);
    FileUtils.forceMkdir(new File(tmproot));
    if (Utils.isOnWindows()) {
        if (Utils.getBoolean(conf.get(Config.SUPERVISOR_RUN_WORKER_AS_USER), false)) {
            throw new RuntimeException("ERROR: Windows doesn't implement setting the correct permissions");
        }
    } else {
        Utils.restrictPermissions(tmproot);
    }
    String stormJarKey = ConfigUtils.masterStormJarKey(stormId);
    String stormCodeKey = ConfigUtils.masterStormCodeKey(stormId);
    String stormConfKey = ConfigUtils.masterStormConfKey(stormId);
    String jarPath = ConfigUtils.supervisorStormJarPath(tmproot);
    String codePath = ConfigUtils.supervisorStormCodePath(tmproot);
    String confPath = ConfigUtils.supervisorStormConfPath(tmproot);
    Utils.downloadResourcesAsSupervisor(stormJarKey, jarPath, blobStore);
    Utils.downloadResourcesAsSupervisor(stormCodeKey, codePath, blobStore);
    Utils.downloadResourcesAsSupervisor(stormConfKey, confPath, blobStore);
    blobStore.shutdown();
    Utils.extractDirFromJar(jarPath, ConfigUtils.RESOURCES_SUBDIR, tmproot);
    downloadBlobsForTopology(conf, confPath, localizer, tmproot);
    if (didDownloadBlobsForTopologySucceed(confPath, tmproot)) {
        LOG.info("Successfully downloaded blob resources for storm-id {}", stormId);
        if (Utils.isOnWindows()) {
            // Files/move with non-empty directory doesn't work well on Windows
            FileUtils.moveDirectory(new File(tmproot), new File(stormroot));
        } else {
            FileUtils.forceMkdir(new File(stormroot));
            Files.move(new File(tmproot).toPath(), new File(stormroot).toPath(),
                    StandardCopyOption.ATOMIC_MOVE);
        }
    } else {
        LOG.info("Failed to download blob resources for storm-id ", stormId);
        Utils.forceDelete(tmproot);
    }
}

From source file:org.artifactory.build.BuildServiceImpl.java

/**
 * Makes sure that all the correct build/backup dirs are prepared for backup
 *
 * @param settings          Export settings
 * @param multiStatusHolder Process status holder
 * @param buildsFolder      Builds folder within the backup
 *//*from w  ww.  j  av a 2s  .  co m*/
private void prepareBuildsFolder(ExportSettings settings, MutableStatusHolder multiStatusHolder,
        File buildsFolder) {
    if (buildsFolder.exists()) {
        // Backup previous builds folder if incremental
        if (settings.isIncremental()) {
            File tempBuildBackupDir = new File(settings.getBaseDir(),
                    BACKUP_BUILDS_FOLDER + "." + System.currentTimeMillis());
            try {
                FileUtils.moveDirectory(buildsFolder, tempBuildBackupDir);
                FileUtils.forceMkdir(buildsFolder);
            } catch (IOException e) {
                multiStatusHolder.error(
                        "Failed to create incremental builds temp backup dir: " + tempBuildBackupDir, e, log);
            }
        }
    } else {
        try {
            FileUtils.forceMkdir(buildsFolder);
        } catch (IOException e) {
            multiStatusHolder.error("Failed to create builds backup dir: " + buildsFolder, e, log);
        }
    }
}

From source file:org.artifactory.spring.ArtifactoryApplicationContext.java

private void moveTmpToBackupDir(ExportSettings settings, MutableStatusHolder status, String timestamp,
        File workingExportDir) {/*from w  ww.j ava2s  . com*/
    //Delete any exiting final export dir
    File exportDir = new File(settings.getBaseDir(), timestamp);
    try {
        FileUtils.deleteDirectory(exportDir);
    } catch (IOException e) {
        log.warn("Failed to delete existing final export directory.", e);
    }
    //Switch the directories
    try {
        FileUtils.moveDirectory(workingExportDir, exportDir);
    } catch (IOException e) {
        log.error("Failed to move '{}' to '{}': {}", workingExportDir, exportDir, e.getMessage());
    } finally {
        settings.setOutputFile(exportDir);
    }
}

From source file:org.ballerinalang.stdlib.internal.file.MoveTo.java

@Override
public void execute(Context context) {
    BMap<String, BValue> sourcePathStruct = (BMap<String, BValue>) context.getRefArgument(0);
    Path sourcePath = (Path) sourcePathStruct.getNativeData(Constants.PATH_DEFINITION_NAME);

    BMap<String, BValue> targetPathStruct = (BMap<String, BValue>) context.getRefArgument(1);
    Path targetPath = (Path) targetPathStruct.getNativeData(Constants.PATH_DEFINITION_NAME);

    File source = new File(sourcePath.toString());
    File target = new File(targetPath.toString());
    try {/*  w  w w  . j  a va 2  s.  co  m*/
        if (source.isDirectory()) {
            FileUtils.moveDirectory(source, target);
        } else {
            FileUtils.moveFile(source, target);
        }
    } catch (IOException ex) {
        String msg = "IO error occurred while moving file/directory from: \'" + sourcePath + "\' to: \'"
                + targetPath + "\'. " + ex.getMessage();
        log.error(msg, ex);
        context.setReturnValues(BLangVMErrors.createError(context, msg));
    }
}