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:org.protocoderrunner.apprunner.api.PFileIO.java

@ProtoMethod(description = "Move a directory to another directory", example = "")
@ProtoMethodParam(params = { "name", "destination" })
public void moveDirToDir(String name, String to) {
    File fromDir = new File(AppRunnerSettings.get().project.getStoragePath() + File.separator + name);
    File dir = new File(AppRunnerSettings.get().project.getStoragePath() + File.separator + to);

    dir.mkdirs();//from  ww w.  j a v a 2s .c  om
    try {
        FileUtils.moveDirectoryToDirectory(fromDir, dir, false);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:org.rhq.plugins.cassandra.util.TakeSnapshotOperation.java

public OperationResult invoke() {
    OperationResult result = new OperationResult();
    String snapshotName = parameters.getSimpleValue("snapshotName", "" + System.currentTimeMillis()).trim();
    if (snapshotName.isEmpty()) {
        result.setErrorMessage("Snapshot Name parameter cannot be an empty string");
        return result;
    }/*from   www.j  av  a 2 s . c o  m*/
    String retentionStrategy = parameters.getSimpleValue("retentionStrategy", R_STRATEGY_KEEP_ALL);
    Integer count = parameters.getSimple("count").getIntegerValue();
    String deletionStrategy = parameters.getSimpleValue("deletionStrategy", D_STRATEGY_DEL);
    String location = parameters.getSimpleValue("location");

    // validate parameters
    if (R_STRATEGY_KEEP_LASTN.equals(retentionStrategy) || R_STRATEGY_DEL_OLDERN.equals(retentionStrategy)) {
        if (count == null) {
            result.setErrorMessage("Invalid input parameters. Selected Retention Strategy [" + retentionStrategy
                    + "] but 'count' parameter was null");
            return result;
        }
    }
    if (D_STRATEGY_MOVE.equals(deletionStrategy)) {
        if (location == null) {
            result.setErrorMessage("Invalid input parameters. Selected Deletion Strategy [" + deletionStrategy
                    + "] but 'location' parameter was null");
            return result;
        }
        File locationDir = new File(location);
        if (!locationDir.exists()) {
            try {
                if (!locationDir.mkdirs()) {
                    result.setErrorMessage("Location [" + locationDir.getAbsolutePath()
                            + "] did not exist and failed to be created");
                    return result;
                }
            } catch (Exception e) {
                result.setErrorMessage("Location [" + locationDir.getAbsolutePath()
                        + "] did not exist and failed to be created - " + e.getMessage());
                return result;
            }
        }
        if (!locationDir.isDirectory()) {
            result.setErrorMessage("Location [" + locationDir.getAbsolutePath() + "] must be directory");
            return result;
        }
        if (!locationDir.canWrite()) {
            result.setErrorMessage("Location [" + locationDir.getAbsolutePath() + "] must be writable");
        }
    }

    String[] keyspaces = service.getKeyspaces().toArray(new String[] {});
    log.info("Taking snapshot of keyspaces " + Arrays.toString(keyspaces));
    long startTime = System.currentTimeMillis();
    service.takeSnapshot(keyspaces, snapshotName);
    log.info("Snapshot taken in " + (System.currentTimeMillis() - startTime) + "ms");

    if (R_STRATEGY_KEEP_ALL.equals(retentionStrategy)) { // do nothing
        return result;
    }

    List<String> columnFamilyDirs = service.getColumnFamilyDirs();

    // obtain list of snapshot dirs to be moved or deleted
    List<String[]> eligibleSnapshots = findEligibleSnapshots(service.getKeySpaceDataFileLocations(),
            columnFamilyDirs, retentionStrategy, count);

    if (eligibleSnapshots.isEmpty()) {
        return result;
    }
    if (D_STRATEGY_DEL.equals(deletionStrategy)) {
        log.info("Strategy [" + deletionStrategy + "] is set, deleting " + eligibleSnapshots.size()
                + " snapshots");
        for (String[] snapPath : eligibleSnapshots) {
            File snapDir = new File(snapPath[0], snapPath[1]);
            log.info("Deleting " + snapDir);
            if (!FileUtils.deleteQuietly(snapDir)) {
                log.warn("Failed to delete " + snapDir.getAbsolutePath());
            }
        }
    }
    if (D_STRATEGY_MOVE.equals(deletionStrategy)) {
        log.info("Strategy [" + deletionStrategy + "] is set, moving " + eligibleSnapshots.size()
                + " snapshots");
        for (String[] snapPath : eligibleSnapshots) {
            File snapDir = new File(snapPath[0], snapPath[1]);
            File snapTargetDir = new File(location, snapPath[1]);
            log.info("Moving  " + snapDir + " to " + snapTargetDir);
            try {
                FileUtils.moveDirectoryToDirectory(snapDir, snapTargetDir.getParentFile(), true);
            } catch (IOException e) {
                log.warn("Failed to move directory : " + e.getMessage());
            }
        }
    }
    return result;
}

From source file:org.syncany.tests.integration.scenarios.framework.MoveFolderToOtherFolder.java

@Override
public void execute() throws Exception {
    final File fromFolder = pickFolder(1212);
    final File toFolder = pickFileOrFolder(72178, new FileFilter() {
        @Override/*w  ww .  j  av  a2 s . c  om*/
        public boolean accept(File file) {
            return file.isDirectory() && !FileUtil.isSymlink(file)
                    && !file.getAbsolutePath().startsWith(fromFolder.getAbsolutePath());
        }
    });

    log(this, fromFolder + " -> " + toFolder);
    FileUtils.moveDirectoryToDirectory(fromFolder, toFolder, false);
}

From source file:org.wso2.carbon.appfactory.utilities.project.ProjectUtils.java

/**
 * Move deploy artifact to a new path// w  w w  .j  a  va2  s  . c om
 *
 * @param deployAtrifact
 * @param parentFile
 * @param appId id of the application
 * @throws AppFactoryException
 */
private static void moveDepolyArtifact(File deployAtrifact, File parentFile, String appId)
        throws AppFactoryException {
    try {
        String deployArtifactPath = parentFile.getAbsolutePath() + File.separator + appId
                + AppFactoryConstants.AF_ARCHETYPE_INITIAL_ARTIFACT_LOCATION;
        File deployArtifactFile = new File(deployArtifactPath);
        if (deployArtifactFile.exists()) {
            FileUtils.forceDelete(deployArtifactFile);
        }
        FileUtils.moveDirectoryToDirectory(deployAtrifact, parentFile, false);
    } catch (IOException e) {
        String msg = "Error while moving deploy artifact from " + deployAtrifact.getAbsolutePath() + " to "
                + parentFile.getAbsolutePath();
        log.error(msg, e);
        throw new AppFactoryException(msg, e);
    }
}

From source file:org.wso2.developerstudio.msf4j.artifact.util.MSF4JDependencyResolverJob.java

private IWorkspaceRoot resourceAlteration() throws IOException, CoreException, JavaModelException {
    // Renaming generated folder structure to match with WSO2
    // conventional directory structure
    IWorkspaceRoot workspace = ResourcesPlugin.getWorkspace().getRoot();
    IProject project = workspace.getProject(msf4jArtifactModel.getProjectName());
    msf4jArtifactModel.setProject(project);
    IFolder resourceFolder = ProjectUtils.getWorkspaceFolder(msf4jArtifactModel.getProject(), SRC_DIRECTORY,
            MAIN_DIRECTORY);/*ww w.  j  av a 2s .  c  o m*/
    File resourcePhysicalFolder = resourceFolder.getRawLocation().makeAbsolute().toFile();
    File newResourcePhysicalFolder = new File(
            resourcePhysicalFolder.getParent() + File.separator + RESOURCES_DIRECTORY);
    resourcePhysicalFolder.renameTo(newResourcePhysicalFolder);

    IFolder sourceFolder = ProjectUtils.getWorkspaceFolder(msf4jArtifactModel.getProject(), SRC_DIRECTORY,
            GEN_DIRECTORY);
    File sourcePhysicalFolder = sourceFolder.getRawLocation().makeAbsolute().toFile();
    File newSourcePhysicalFolder = new File(sourcePhysicalFolder.getParent() + File.separator + MAIN_DIRECTORY);
    sourcePhysicalFolder.renameTo(newSourcePhysicalFolder);

    // Moving src/resources to src/main
    resourceFolder = ProjectUtils.getWorkspaceFolder(msf4jArtifactModel.getProject(), SRC_DIRECTORY,
            RESOURCES_DIRECTORY);
    resourcePhysicalFolder = resourceFolder.getRawLocation().makeAbsolute().toFile();
    sourceFolder = ProjectUtils.getWorkspaceFolder(msf4jArtifactModel.getProject(), SRC_DIRECTORY,
            MAIN_DIRECTORY);
    sourcePhysicalFolder = sourceFolder.getRawLocation().makeAbsolute().toFile();
    FileUtils.moveDirectoryToDirectory(resourcePhysicalFolder, sourcePhysicalFolder, true);

    // Adding Java support to the source folder src/main/java
    // delete the project target folder
    IFolder targetFolder = ProjectUtils.getWorkspaceFolder(msf4jArtifactModel.getProject(),
            MSF4JArtifactConstants.TRGET_DIRECTORY);
    targetFolder.delete(true, new NullProgressMonitor());
    IFolder mainFolder = ProjectUtils.getWorkspaceFolder(msf4jArtifactModel.getProject(), SRC_DIRECTORY,
            MAIN_DIRECTORY, JAVA_DIRECTORY);
    JavaUtils.addJavaSupportAndSourceFolder(msf4jArtifactModel.getProject(), mainFolder);

    // removing the webapps folder generated by the tool
    IFolder webAppFolder = ProjectUtils.getWorkspaceFolder(msf4jArtifactModel.getProject(), SRC_DIRECTORY,
            MAIN_DIRECTORY, RESOURCES_DIRECTORY, WEBAPP_DIRECTORY);
    File webAppPhysicalFolder = webAppFolder.getRawLocation().makeAbsolute().toFile();
    if (webAppPhysicalFolder.exists()) {
        FileUtils.forceDelete(webAppPhysicalFolder);
    }

    // removing unnecessary classes generated by the tool
    IProject newMSF4JProject = workspace.getProject(msf4jArtifactModel.getProject().getName());
    String[] filesToBeDeleted = { NOT_FOUND_EXCEPTION_JAVA, API_ORIGIN_FILTER_JAVA, API_RESPONSE_MESSAGE_JAVA,
            API_EXCEPTION_JAVA };

    for (String fileToBeDeleted : filesToBeDeleted) {
        IResource originFilterFile = newMSF4JProject
                .getFile(SRC_DIRECTORY + File.separator + MAIN_DIRECTORY + File.separator + JAVA_DIRECTORY
                        + File.separator + msf4jArtifactModel.getPackageName().replace(".", File.separator)
                        + File.separator + API + File.separator + fileToBeDeleted);
        File fileToDelete = originFilterFile.getRawLocation().makeAbsolute().toFile();
        if (fileToDelete.exists()) {
            FileUtils.forceDelete(fileToDelete);
        }
    }
    ProjectUtils.addNatureToProject(project, false, MAVEN2_PROJECT_NATURE);
    ProjectUtils.addNatureToProject(project, false, MSF4J_PROJECT_NATURE);
    project.refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor());
    return workspace;
}

From source file:platform.tooling.support.Runner.java

private Result installRemoteTool(Result result) {
    // download/*w ww.jav  a2  s . c  om*/
    var version = request.getVersion();
    var toolArchive = tool.computeArchive(version);
    var toolUri = tool.computeUri(version);
    var toolArchivePath = toolPath.resolve(toolArchive);
    if (Files.notExists(toolArchivePath)) {
        var timeout = (int) TimeUnit.MILLISECONDS.convert(9, TimeUnit.SECONDS);
        try {
            FileUtils.copyURLToFile(toolUri.toURL(), toolArchivePath.toFile(), timeout, timeout);
        } catch (IOException e) {
            throw new UncheckedIOException("Loading tool failed: " + toolUri, e);
        }
    }

    // extract
    var jarTool = ToolProvider.findFirst("jar").orElseThrow();
    var stringWriter = new StringWriter();
    var printWriter = new PrintWriter(stringWriter);
    jarTool.run(printWriter, printWriter, "--list", "--file", toolArchivePath.toString());
    var toolFolderName = stringWriter.toString().split("\\R")[0];
    var toolFolderPath = toolPath.resolve(toolFolderName);
    if (Files.notExists(toolFolderPath)) {
        try {
            jarTool.run(System.out, System.err, "--extract", "--file", toolArchivePath.toString());
            FileUtils.moveDirectoryToDirectory(Paths.get(toolFolderName).toFile(), toolPath.toFile(), true);
        } catch (IOException e) {
            throw new UncheckedIOException("Extracting tool failed: " + toolUri, e);
        }
    }
    result.toolHome = toolFolderPath.normalize().toAbsolutePath();

    // compute program entry point
    var executable = toolFolderPath.resolve(tool.computeExecutablePath());
    if (FileSystems.getDefault().supportedFileAttributeViews().contains("posix")) {
        executable.toFile().setExecutable(true);
    }
    result.toolExecutable = executable;
    return result;
}

From source file:pm.filemanager.operations.FileOperations.java

public static void cutPasteFile(String sourceName, String destName) throws IOException {

    File sourceFile = new File(sourceName);
    File destFile = new File(destName);
    // TO-DO .exists() check needs to be added here
    if (sourceFile.isFile() && destFile.isDirectory()) {
        FileUtils.moveFileToDirectory(sourceFile, destFile, false);
    } else if (sourceFile.isFile()) {
        FileUtils.moveFile(sourceFile, destFile);
    } else {/*from  www . j  a  va  2s . c om*/
        FileUtils.moveDirectoryToDirectory(sourceFile, destFile, false);
    }
    //FileUtils.deleteQuietly(sourceFile); // ZOMG it deletes EVERYTHING!!!
    //        File checkFileExistance = new File(destName + name);
    //        resultPaste = checkFileExistance.exists();
    //        if(checkFileExistance.exists()) {
    //            resultPaste = true;
    //            sourceFile.delete();
    //        }
    //        else {
    //            resultPaste = false;
    //            // TO-DO logger, exception handling
    //        }
}

From source file:scanct.ScanCT.java

public void clasificar() {
    //creamos la ruta en la cual se van a almacenar los documentos
    String ruta = conf.carpetaRemota + "aceptados\\";
    File f = new File(ruta);

    FileUtils Files = new FileUtils();
    FileUtils Files2 = new FileUtils();
    String ct = "";
    System.out.println(f.list());
    ArrayList<String> names = new ArrayList<String>(Arrays.asList(f.list()));
    if (!names.isEmpty()) {
        for (int i = 0; i < names.size(); i++) {
            //____________Elifor ()

            System.out.println(names.get(i));
            ct = obtenerCT(names.get(i));
            //ct = obtenerCT(names2.get())
            if (ct.equals("")) {
                System.out.println("Se acab");

            }/*ww  w.  j a v  a 2s .  c o m*/

            else {
                String prueba = (String) (names.get(i).toString());
                String rutadestino = conf.carpetaCT + "\\" + names.get(i) + "\\";
                System.out.println("CT:" + ct);
                System.out.println("Carpeta destino: " + rutadestino);
                File destino = new File(conf.carpetaCT + ct + "\\");
                File destino2 = new File(conf.carpetaCT + ct + "\\" + names.get(i) + "\\");
                //String rutadest = conf.carpetaCT+"\\"+ct+"\\";
                File origen = new File(ruta + names.get(i) + "\\");
                File f3;

                File f2 = new File(origen + "\\");

                if (destino2.exists()) {

                    ArrayList<String> names2 = new ArrayList<String>(Arrays.asList(f2.list()));

                    for (int j = 0; j < names2.size(); j++) {

                        f3 = new File(f2.toString() + "\\" + names2.get(j));
                        System.out.println("El fichero que estoy intentando tomar: " + f3.toString());
                        System.out.println("Destino es: " + destino2);
                        try {

                            Files2.moveFileToDirectory(f3, destino2, true);

                            f2.delete();

                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        // f3 = new File(f2+"\\"+names2.get(i)+"\\");
                    }
                    // Files.moveFile(origen, destino);
                    //try{
                    //   Files.moveDirectoryToDirectory(origen, destino, true);
                    // }
                    //catch(IOException e){}
                } else {
                    try {
                        Files.moveDirectoryToDirectory(origen, destino, true);
                    } catch (IOException e) {
                    }
                }

                System.out.println("Se imprime el origen: " + origen);
                System.out.println("Se imprime el destino: " + destino);

            }

        }
        JOptionPane.showMessageDialog(null, "Se han movido exitosamente los elementos de directorio");
    }

    else {
        JOptionPane.showMessageDialog(null, "No hay mas archivos que mover");
    }

}