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

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

Introduction

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

Prototype

public static void moveDirectoryToDirectory(File src, File destDir, boolean createDestDir) throws IOException 

Source Link

Document

Moves a directory to another directory.

Usage

From source file:de.uzk.hki.da.cb.UnpackNoBagitAction.java

private void moveSipDir() throws IOException {

    if (!wa.dataPath().toFile().mkdirs()) {
        throw new RuntimeException("couldn't create directory: " + wa.dataPath().toFile());
    }//  www.  jav  a  2  s .com

    File[] files = wa.sipFile().listFiles();
    if (files.length == 1) {
        File[] folderFiles = files[0].listFiles();
        for (File f : folderFiles) {
            if (f.isFile()) {
                try {
                    FileUtils.moveFileToDirectory(f, wa.dataPath().toFile(), false);
                } catch (IOException e) {
                    throw new RuntimeException("couldn't move file " + f.getAbsolutePath() + " to folder "
                            + wa.dataPath().toFile(), e);
                }
            }
            if (f.isDirectory()) {
                try {
                    FileUtils.moveDirectoryToDirectory(f, wa.dataPath().toFile(), false);
                } catch (IOException e) {
                    throw new RuntimeException("couldn't move folder " + f.getAbsolutePath() + " to folder "
                            + wa.dataPath().toFile(), e);
                }
            }
        }

        try {
            FolderUtils.deleteDirectorySafe(files[0]);
        } catch (IOException e) {
            throw new RuntimeException("couldn't delete folder " + files[0].getAbsolutePath());
        }
    }

}

From source file:edu.kit.dama.staging.services.processor.impl.IngestToDownloadProcessor.java

@Override
public void performPostTransferProcessing(TransferTaskContainer pContainer) throws StagingProcessorException {
    LOGGER.debug("Performing IngestToDownloadProcessor");
    IngestInformation ingest = (IngestInformation) pContainer.getTransferInformation();

    LOGGER.debug(" - Creating download entry");
    IAuthorizationContext ctx = new AuthorizationContext(new UserId(ingest.getOwnerId()),
            new GroupId(ingest.getGroupId()), Role.MEMBER);
    TransferClientProperties props = new TransferClientProperties();
    props.setStagingAccessPointId(accessPoint.getConfiguration().getUniqueIdentifier());
    DownloadInformation download;/*from   w w w .ja va2s. c om*/
    try {
        download = DownloadInformationServiceLocal.getSingleton()
                .scheduleDownload(new DigitalObjectId(ingest.getDigitalObjectId()), props, ctx);
        LOGGER.debug(" - Download entry created. Setting status to DOWNLOAD_STATUS.PREPARING.");
        DownloadInformationServiceLocal.getSingleton().updateStatus(download.getId(),
                DOWNLOAD_STATUS.PREPARING.getId(), null, ctx);
        LOGGER.debug(" - Status successfully set. Starting moving data.");
    } catch (TransferPreparationException ex) {
        throw new StagingProcessorException(
                "Failed to create download for ingest with object id " + ingest.getDigitalObjectId(), ex);
    }

    LOGGER.debug(" - Obtaining data folder URL of ingest.");
    URL data = ingest.getDataFolderUrl();

    LOGGER.debug(" - Ingest data folder URL is: {}", data);

    AbstractStagingAccessPoint ingestAP = StagingConfigurationManager.getSingleton()
            .getAccessPointById(ingest.getAccessPointId());
    File baseFile = ingestAP.getLocalPathForUrl(data, ctx);
    LOGGER.debug(" - Ingest data path is: {}", baseFile);

    LOGGER.debug(" - Obtaining data folder URL of download.");
    File stagingPath = accessPoint.getLocalPathForUrl(download.getDataFolderUrl(), ctx);
    LOGGER.debug(" - Download data folder URL is: {}", stagingPath);

    try {
        LOGGER.debug("Moving {} to {}", baseFile, stagingPath);
        for (File f : baseFile.listFiles()) {
            LOGGER.debug(" - Moving file {}", f);
            if (f.isFile()) {
                FileUtils.moveFileToDirectory(f, stagingPath, false);
            } else if (f.isDirectory()) {
                FileUtils.moveDirectoryToDirectory(f, stagingPath, false);
            }
        }
        LOGGER.debug("All files successfully moved.");
    } catch (IOException ex) {
        throw new StagingProcessorException("Failed to move " + baseFile + " to " + stagingPath, ex);
    }

    if (doChgrp) {
        LOGGER.debug("GroupChange flag ist TRUE, changing ownership of data folder at {} to group {}",
                stagingPath, ingest.getGroupId());
        if (edu.kit.dama.util.SystemUtils.chgrpFolder(stagingPath, ingest.getGroupId())) {
            LOGGER.debug("Group ownership successfully changed.");
        } else {
            throw new StagingProcessorException("Failed to change group ownership for data folder "
                    + stagingPath + " to groupId {} " + ingest.getGroupId());
        }
    }

    LOGGER.debug("Successfully moved data to download path. Setting download to be ready.");
    DownloadInformationServiceLocal.getSingleton().updateStatus(download.getId(),
            DOWNLOAD_STATUS.DOWNLOAD_READY.getId(), null, ctx);
}

From source file:com.fanniemae.ezpie.actions.Directory.java

protected String moveDirectory() throws IOException {
    if (StringUtilities.isNullOrEmpty(_destinationPath)) {
        throw new PieException(String.format("%s is missing a value for DestinationPath.", _actionName));
    }// w  w  w. ja v  a2 s .co  m
    if (FileUtilities.isValidDirectory(_destinationPath)) {
        throw new PieException(String.format("Destination directory (%s) already exists.", _destinationPath));
    }
    _session.addLogMessage("", "Destination Path", _destinationPath);
    _session.addLogMessage("", "Process", "Moving directory");
    FileUtils.moveDirectoryToDirectory(new File(_path), new File(_destinationPath), true);
    return "";
}

From source file:me.ryanhamshire.griefprevention.FlatFileDataStore.java

@Override
public void loadWorldData(World world) {
    WorldProperties worldProperties = world.getProperties();
    DimensionType dimType = worldProperties.getDimensionType();
    Path dimPath = rootConfigPath.resolve(((IMixinDimensionType) dimType).getModId())
            .resolve(((IMixinDimensionType) dimType).getEnumName());
    if (!Files.exists(dimPath.resolve(worldProperties.getWorldName()))) {
        try {/*from  w  w  w . ja v a2  s .c om*/
            Files.createDirectories(dimPath.resolve(worldProperties.getWorldName()));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    // create/load configs
    // create dimension config
    DataStore.dimensionConfigMap.put(worldProperties.getUniqueId(),
            new GriefPreventionConfig<DimensionConfig>(Type.DIMENSION, dimPath.resolve("dimension.conf")));
    // create world config
    DataStore.worldConfigMap.put(worldProperties.getUniqueId(), new GriefPreventionConfig<>(Type.WORLD,
            dimPath.resolve(worldProperties.getWorldName()).resolve("world.conf")));

    GPClaimManager claimWorldManager = new GPClaimManager(worldProperties);
    this.claimWorldManagers.put(worldProperties.getUniqueId(), claimWorldManager);

    // check if world has existing data
    Path oldWorldDataPath = rootWorldSavePath.resolve(worldProperties.getWorldName()).resolve(claimDataPath);
    Path oldPlayerDataPath = rootWorldSavePath.resolve(worldProperties.getWorldName()).resolve(playerDataPath);
    if (worldProperties.getUniqueId() == Sponge.getGame().getServer().getDefaultWorld().get().getUniqueId()) {
        oldWorldDataPath = rootWorldSavePath.resolve(claimDataPath);
        oldPlayerDataPath = rootWorldSavePath.resolve(playerDataPath);
    }

    if (DataStore.USE_GLOBAL_PLAYER_STORAGE) {
        // use global player data
        oldPlayerDataPath = rootWorldSavePath.resolve(playerDataPath);
    }

    Path newWorldDataPath = dimPath.resolve(worldProperties.getWorldName());

    try {
        // Check for old data location
        if (Files.exists(oldWorldDataPath)) {
            GriefPreventionPlugin.instance.getLogger().info("Detected GP claim data in old location.");
            GriefPreventionPlugin.instance.getLogger().info("Migrating GP claim data from "
                    + oldWorldDataPath.toAbsolutePath() + " to " + newWorldDataPath.toAbsolutePath() + "...");
            FileUtils.moveDirectoryToDirectory(oldWorldDataPath.toFile(), newWorldDataPath.toFile(), true);
            GriefPreventionPlugin.instance.getLogger().info("Done.");
        }
        if (Files.exists(oldPlayerDataPath)) {
            GriefPreventionPlugin.instance.getLogger().info("Detected GP player data in old location.");
            GriefPreventionPlugin.instance.getLogger().info("Migrating GP player data from "
                    + oldPlayerDataPath.toAbsolutePath() + " to " + newWorldDataPath.toAbsolutePath() + "...");
            FileUtils.moveDirectoryToDirectory(oldPlayerDataPath.toFile(), newWorldDataPath.toFile(), true);
            GriefPreventionPlugin.instance.getLogger().info("Done.");
        }

        // Create data folders if they do not exist
        if (!Files.exists(newWorldDataPath.resolve("ClaimData"))) {
            Files.createDirectories(newWorldDataPath.resolve("ClaimData"));
        }
        if (DataStore.USE_GLOBAL_PLAYER_STORAGE) {
            if (!globalPlayerDataPath.toFile().exists()) {
                Files.createDirectories(globalPlayerDataPath);
            }
        } else if (!Files.exists(newWorldDataPath.resolve("PlayerData"))) {
            Files.createDirectories(newWorldDataPath.resolve("PlayerData"));
        }

        // Migrate RedProtectData if enabled
        if (GriefPreventionPlugin.getGlobalConfig().getConfig().migrator.redProtectMigrator) {
            Path redProtectFilePath = redProtectDataPath
                    .resolve("data_" + worldProperties.getWorldName() + ".conf");
            Path gpMigratedPath = redProtectDataPath.resolve("gp_migrated_" + worldProperties.getWorldName());
            if (Files.exists(redProtectFilePath) && !Files.exists(gpMigratedPath)) {
                RedProtectMigrator.migrate(world, redProtectFilePath, newWorldDataPath.resolve("ClaimData"));
                Files.createFile(gpMigratedPath);
            }
        }
        // Migrate Polis data if enabled
        if (GriefPreventionPlugin.getGlobalConfig().getConfig().migrator.polisMigrator) {
            Path claimsFilePath = polisDataPath.resolve("claims.conf");
            Path teamsFilePath = polisDataPath.resolve("teams.conf");
            Path gpMigratedPath = polisDataPath.resolve("gp_migrated_" + worldProperties.getWorldName());
            if (Files.exists(claimsFilePath) && Files.exists(teamsFilePath) && !Files.exists(gpMigratedPath)) {
                PolisMigrator.migrate(world, claimsFilePath, teamsFilePath,
                        newWorldDataPath.resolve("ClaimData"));
                Files.createFile(gpMigratedPath);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    // Load Claim Data
    try {
        File[] files = newWorldDataPath.resolve("ClaimData").toFile().listFiles();
        if (files != null && files.length > 0) {
            this.loadClaimData(files, worldProperties);
            GriefPreventionPlugin.instance.getLogger()
                    .info("[" + worldProperties.getWorldName() + "] " + files.length + " total claims loaded.");
        }

        if (GriefPreventionPlugin.getGlobalConfig().getConfig().playerdata.useGlobalPlayerDataStorage) {
            files = globalPlayerDataPath.toFile().listFiles();
        } else {
            files = newWorldDataPath.resolve("PlayerData").toFile().listFiles();
        }
        if (files != null && files.length > 0) {
            this.loadPlayerData(worldProperties, files);
        }

        // If a wilderness claim was not loaded, create a new one
        if (claimWorldManager.getWildernessClaim() == null) {
            claimWorldManager.createWildernessClaim(worldProperties);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    // handle default flag permissions
    this.setupDefaultPermissions(world);
}

From source file:de.uzk.hki.da.cb.RetrievePackagesHelper.java

/**
 * Unpacks one archive container and moves its content to targetPath.
 * When unpacked, all files below [containerFirstLevelEntry]/data/ are content in this sense.
 * <pre>Example:/*from w w  w  .j  av  a 2s  .  com*/
 * a/data/rep/abc.tif (from a.tar) -\> [targetPath]/rep/abc.tif</pre>
 *  
 * @param container
 * @param targetPath
 * @throws IOException
 */
private List<DAFile> unpackArchiveAndMoveContents(File container, String targetPath) throws IOException {

    List<DAFile> results = new ArrayList<DAFile>();

    File tempFolder = new File(targetPath + "Temp");
    tempFolder.mkdir();

    try {
        ArchiveBuilder builder = ArchiveBuilderFactory.getArchiveBuilderForFile(container);
        builder.unarchiveFolder(container, tempFolder);
    } catch (Exception e) {
        throw new IOException("Existing AIP \"" + container + "\" couldn't be unpacked to folder " + tempFolder,
                e);
    }

    String containerFirstLevelEntry[] = (tempFolder).list();
    File tempDataFolder = new File(tempFolder.getPath() + "/" + containerFirstLevelEntry[0] + "/data");
    if (!tempDataFolder.exists())
        throw new RuntimeException("unpacked package in Temp doesn't contain a data folder!");

    logger.debug("Listing representations inside temporary folder: ");
    File[] repFolders = tempDataFolder.listFiles();
    for (File rep : repFolders) {

        String repPartialPath = (rep.getPath()).replace(tempDataFolder.getPath() + "/", "");
        if (!rep.isDirectory())
            continue;

        for (File f : FileUtils.listFiles(rep, TrueFileFilter.INSTANCE, TrueFileFilter.INSTANCE)) {
            results.add(new DAFile(repPartialPath,
                    f.getPath().replace((tempDataFolder.getPath() + "/" + repPartialPath + "/"), "")));
        }

        FileUtils.moveDirectoryToDirectory(rep, new File(targetPath), true);
    }

    FolderUtils.deleteDirectorySafe(tempFolder);

    return results;
}

From source file:de.jwi.jfm.Folder.java

private String copyOrMove(boolean move, String[] selectedIDs, String target)
        throws IOException, OutOfSyncException {
    if ((selectedIDs == null) || (selectedIDs.length == 0)) {
        return "No file selected";
    }/*ww  w . j a v  a  2s .  co  m*/

    File f1 = getTargetFile(target);

    if ((null == f1) || (myFile.getCanonicalFile().equals(f1.getCanonicalFile()))) {
        return "illegal target file";
    }

    if ((!f1.isDirectory()) && (selectedIDs.length > 1)) {
        return "target is not a directory";
    }

    StringBuffer sb = new StringBuffer();

    File fx = null;

    for (int i = 0; i < selectedIDs.length; i++) {
        File f = checkAndGet(selectedIDs[i]);

        if (null == f) {
            throw new OutOfSyncException();
        }

        if (!f1.isDirectory()) {
            fx = f1;
        } else {
            fx = new File(f1, f.getName());
        }

        if (move) {
            if (f.isDirectory()) {
                FileUtils.moveDirectoryToDirectory(f, fx, true);
            } else {
                if (!f.renameTo(fx)) {
                    sb.append(f.getName()).append(" ");
                }
            }
        } else {
            try {
                if (f.isDirectory()) {
                    FileUtils.copyDirectoryToDirectory(f, fx);
                } else {
                    FileUtils.copyFile(f, fx, true);
                }
            } catch (IOException e) {
                sb.append(f.getName()).append(" ");
            }
        }
    }

    String s = sb.toString();

    if (!"".equals(s)) {
        String op = move ? "move" : "copy";
        return "failed to " + op + " " + s + " to " + f1.toString();
    }

    return "";
}

From source file:io.yields.plugins.kpi.KPIReportPublisher.java

@Override
public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener)
        throws InterruptedException, IOException {

    PrintStream logger = listener.getLogger();

    if (Result.SUCCESS == build.getResult()) {

        FilePath workspace = getWorkspace(build);

        // copy results from yields folder to build folder
        FilePath buildFolder = workspace.child(format("builds/%d/yields", build.getNumber()));
        buildFolder.mkdirs();//from w  w w.  j  a  v a 2s.  c o  m

        logger.printf("[YIELDS] Scanning for KPI Scores in path %s (trendSize = %d, detailSize = %d)\n",
                config.getPath().getAbsolutePath(), config.getTrendSize(), config.getDetailSize());

        // copy the latest folder to the build folder
        File[] folders = config.getPath().listFiles();
        if (folders != null) {
            List<File> buildFolders = Arrays.asList(folders);
            Collections.sort(buildFolders, new Comparator<File>() {
                @Override
                public int compare(File file, File other) {
                    return valueOf(other.lastModified()).compareTo(valueOf(file.lastModified()));
                }
            });

            new FilePath(buildFolders.get(0)).copyRecursiveTo(buildFolder);

            logger.printf("[YIELDS] Copied KPI Scores from %s into %s\n", buildFolders.get(0), buildFolder);

        } else {
            logger.printf("[YIELDS] No KPI Scores found in %s, nothing will be copied\n", config.getPath());
        }

    } else {
        logger.printf("[YIELDS] No KPI Scores to copy, build has result %s\n", build.getResult());
    }

    if (Result.SUCCESS == build.getResult()) {

        if (dataSetExportConfig != null) {

            // copy the latest folder to the configured export filter
            File sourceFolder = new File(FileUtils.getTempDirectory(), FOLDER_NAME_DATA_SET);

            // move exported data sets from yields_data folder to configured export filter
            logger.printf("[YIELDS_DATA] Scanning for KPI Data Sets in path %s\n",
                    sourceFolder.getAbsolutePath());

            File[] folders = sourceFolder.listFiles();
            if (folders != null) {
                List<File> exportFolders = Arrays.asList(folders);
                Collections.sort(exportFolders, new Comparator<File>() {
                    @Override
                    public int compare(File file, File other) {
                        return valueOf(other.lastModified()).compareTo(valueOf(file.lastModified()));
                    }
                });

                FileUtils.moveDirectoryToDirectory(exportFolders.get(0), dataSetExportConfig.getPath(), true);

                logger.printf("[YIELDS_DATA] Moved KPI Data Sets from %s into %s\n",
                        exportFolders.get(0).getAbsolutePath(),
                        dataSetExportConfig.getPath().getAbsolutePath());

            } else {
                logger.printf("[YIELDS_DATA] No KPI Data Sets found in %s, nothing will be moved\n",
                        sourceFolder.getAbsolutePath());
            }

        } else {
            logger.printf("[YIELDS_DATA] No KPI export path configured\n");
        }

    } else {
        logger.printf("[YIELDS_DATA] No KPI Data Sets to move, build has result %s\n", build.getResult());
    }

    KPIReport report = new KPIReportService().getReport(build, config.getTrendSize(), listener.getLogger());
    listener.getLogger().printf("[YIELDS] Retrieved KPI Report with %d previous KPI report(s)\n",
            config.getTrendSize() - 1);

    KPIReportBuildAction buildAction = new KPIReportBuildAction(build, report, config.getTrendSize());
    build.addAction(buildAction);

    // TODO fail build if configured to fail and 1 or more scores went down compared to previous build (build.setResult)

    return true;
}

From source file:com.diffplug.gradle.FileMisc.java

/**
 * Flattens a single directory (moves its children to be its peers, then deletes the given directory.
 * /* w w w  .  j  a  v  a  2  s.  c  om*/
 * ```
 * before:
 *     root/
 *        toFlatten/
 *           child1
 *           child2
 * 
 * flatten("root/toFlatten")
 * 
 * after:
 *     root/
 *        child1
 *        child2
 * ```
 */
public static void flatten(File dirToRemove) throws IOException {
    final File parent = dirToRemove.getParentFile();
    // move each child directory to the parent
    for (File child : FileMisc.list(dirToRemove)) {
        boolean createDestDir = false;
        if (child.isFile()) {
            FileUtils.moveFileToDirectory(child, parent, createDestDir);
        } else if (child.isDirectory()) {
            FileUtils.moveDirectoryToDirectory(child, parent, createDestDir);
        } else {
            throw new IllegalArgumentException("Unknown filetype: " + child);
        }
    }
    // remove the directory which we're flattening away
    FileMisc.forceDelete(dirToRemove);
}

From source file:de.uzk.hki.da.cb.RetrievePackagesHelper.java

/**
 * At the beginning the objects data are located under:
 * <pre>[workAreaRootPath]/[csn]/object-id/loadedAIPs/data</pre>
 * After they should be at/*from w w  w. j  a v a 2  s. com*/
 * <pre>[workAreaRootPath]/[csn]/[id]/data</pre>
 * @param object
 * @throws IOException
 */
private void normalizeObject(Object object) throws IOException {

    String dataPath = wa.objectPath() + "/loadedAIPs/data/";
    String dataPathContents[] = new File(dataPath).list();

    if (dataPathContents == null)
        throw new RuntimeException("Listing files in " + dataPath + " failed!");
    for (int i = 0; i < dataPathContents.length; i++) {
        logger.debug("adding " + dataPathContents[i] + " to target location");
        if (new File(dataPath + dataPathContents[i]).isDirectory())
            FileUtils.moveDirectoryToDirectory(new File(dataPath + dataPathContents[i]), wa.dataPath().toFile(),
                    false);
        else
            FileUtils.moveFileToDirectory(new File(dataPath + dataPathContents[i]), wa.dataPath().toFile(),
                    false);
    }
}

From source file:de.uzk.hki.da.cb.UnpackAction.java

private void expandDirInto() {

    File[] files = wa.objectPath().toFile().listFiles();
    if (files.length == 1) {
        File[] folderFiles = files[0].listFiles();

        for (File f : folderFiles) {
            if (f.isFile()) {
                try {
                    FileUtils.moveFileToDirectory(f, wa.objectPath().toFile(), false);
                } catch (IOException e) {
                    throw new RuntimeException("couldn't move file " + f.getAbsolutePath() + " to folder "
                            + wa.objectPath().toFile(), e);
                }/*from   w  ww.j  a v  a 2  s.co  m*/
            }
            if (f.isDirectory()) {
                try {
                    FileUtils.moveDirectoryToDirectory(f, wa.objectPath().toFile(), false);
                } catch (IOException e) {
                    throw new RuntimeException("couldn't move folder " + f.getAbsolutePath() + " to folder "
                            + wa.objectPath().toFile(), e);
                }
            }
        }

        try {
            FolderUtils.deleteDirectorySafe(files[0]);
        } catch (IOException e) {
            throw new RuntimeException("couldn't delete folder " + files[0].getAbsolutePath());
        }
    }

}