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

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

Introduction

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

Prototype

public static void cleanDirectory(File directory) throws IOException 

Source Link

Document

Cleans a directory without deleting it.

Usage

From source file:org.jasig.ssp.util.importer.job.BatchPartialUploadTest.java

private void deleteDirectory(String directoryPath) throws IOException {
    File directory = new File(directoryPath);
    if (directory.exists()) {
        FileUtils.cleanDirectory(directory);
        FileUtils.deleteDirectory(directory);
    }/*w  w w .  ja v  a 2 s .c  om*/
}

From source file:org.jasig.ssp.util.importer.job.tasklet.BatchFinalizer.java

private void cleanDirectoryQuietly(File directory) {
    if (directory.exists()) {
        try {/*from  www .j  a  v  a2 s  . co m*/
            logger.info("Emptying directory [{}]", directory);
            FileUtils.cleanDirectory(directory);
        } catch (Exception e) {
            logger.error("Failed to empty directory [{}]", directory, e);
        }
    } else {
        logger.info("Attempting to empty directory [{}], directory does not exist.", directory);
    }
}

From source file:org.jasig.ssp.util.importer.job.tasklet.BatchInitializer.java

private void cleanDirectoryQuietly(File directory) {
    try {//from ww  w  .  j a  v a 2 s. c  o m
        logger.info("Emptying directory [{}]", directory);
        FileUtils.cleanDirectory(directory);
    } catch (Exception e) {
        logger.error("Failed to empty directory [{}]", directory, e);
    }
}

From source file:org.jboss.as.test.manualmode.deployment.DeploymentScannerRedeploymentTestCase.java

@After
public void after() throws IOException {
    FileUtils.cleanDirectory(deployDir);
}

From source file:org.jdesktop.wonderland.modules.service.ModuleManagerUtils.java

/**
 * Creates a directory if it does not exist. If it does exist, then remove
 * any exist directory contents. Returns true upon success, false upon
 * failure./*from   ww w.ja  v  a 2  s .  c o  m*/
 * 
 * @param root The directory to create
 */
public static boolean makeCleanDirectory(File root) {
    Logger logger = ModuleManager.getLogger();
    if (root.exists() == true) {
        /* Log an info message, and try to clean the existing directory */
        try {
            FileUtils.cleanDirectory(root);
            return true;
        } catch (java.io.IOException excp) {
            /* If we cannot delete the existing directory, this is fatal */
            logger.warning("[MODULES] MAKE CLEAN Failed " + excp.toString());
            return false;
        }
    }

    /* Now go ahead and recreate the directory */
    try {
        root.mkdir();
    } catch (java.lang.SecurityException excp) {
        logger.warning("[MODULES] MAKE CLEAN Failed " + excp.toString());
        return false;
    }
    return true;
}

From source file:org.jenkinsci.plugins.os_ci.model.Product.java

public boolean deploy(NexusClient nexusClient, OpenStackClient openStackClient,
        YumRepoParameters yumRepoParameters, DeployParmeters deployParmeters) throws Exception {
    final String targetFolder = Joiner.on(File.separator).join(build.getWorkspace().getRemote(), "archive");

    LogUtils.logSection(listener, "Deploy Product " + artifact.getArtifactId());

    List<String> fileTypes = new ArrayList<String>();
    fileTypes.add("pom");
    fileTypes.add("tar.gz");
    fileTypes.add("rpm");
    fileTypes.add("rh6");
    nexusClient.downloadProductArtifacts(getArtifact(),
            Joiner.on(File.separator).join(targetFolder, artifact.getArtifactId()), fileTypes);
    //****************** get pom file dependencies ******************
    MavenPom mavenPom = new MavenPom(
            new File(Joiner.on(File.separator).join(targetFolder, artifact.getArtifactId(), "pom.xml")));
    List<ArtifactParameters> subProducts = mavenPom.getPomProductDependencies();

    for (ArtifactParameters m : subProducts) {
        Product p = new Product(m, build, listener);
        boolean return_ = p.deploy(nexusClient, openStackClient, yumRepoParameters, deployParmeters);
        if (!return_)
            throw new ProductDeployPluginException(
                    "Deploy dependent product " + m.getArtifactId() + " failed.");
    }//from www .jav a  2  s  .  c  o  m

    String buildId = Joiner.on("-").join(new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss-SS").format(build.getTime()),
            deployParmeters.getDeployCounter());

    if (!new File(Joiner.on(File.separator).join(targetFolder, artifact.getArtifactId(),
            "external_dependencies.tar.gz")).exists()) {
        // if there isn't an external_dependencies.tar.gz file
        // only a pom file => we're deploying a profile
        LogUtils.log(listener, "Finish Deploy: " + artifact.getArtifactId());
        return true;
    }

    CompressUtils.untarFile(new File(Joiner.on(File.separator).join(targetFolder, artifact.getArtifactId(),
            "external_dependencies.tar.gz")));
    LogUtils.log(listener, "Untar File: " + Joiner.on(File.separator).join(targetFolder,
            artifact.getArtifactId(), "external_dependencies.tar.gz"));

    //****************** move deployment-scripts ******************
    // Push scripts to YUM repo machine
    copyFolderToRepoMachine(build, listener, yumRepoParameters,
            Joiner.on(File.separator).join(targetFolder, artifact.getArtifactId(), "archive", "deploy-scripts"),
            Joiner.on("/").join("/var", "www", "html", "build", buildId));
    LogUtils.log(listener, "Copy deployment-scripts folder to Yum Repo machine.");

    // move external rpms from archive/product/archive/rpms  to /archive/repo folder

    if (new File(Joiner.on(File.separator).join(targetFolder, artifact.getArtifactId(), "archive", "repo"))
            .exists()) {
        moveExternalRpmsToRepoDirectory(
                Joiner.on(File.separator).join(targetFolder, artifact.getArtifactId(), "archive", "repo"),
                Joiner.on(File.separator).join(targetFolder, "repo"));
        LogUtils.log(listener, "Copied external RPMS to repo directory.");
    }

    File deploymentScriptsRPM = new File(Joiner.on(File.separator).join(targetFolder, artifact.getArtifactId(),
            artifact.getArtifactId() + "-" + artifact.getVersion() + ".rpm"));
    if (deploymentScriptsRPM.exists()) {
        //            Rename RPM file according to rpm metadata
        if (!System.getProperty("os.name").toLowerCase().startsWith("windows")) {
            ExecUtils.executeLocalCommand(
                    "/usr/local/bin/download_rpm.sh " + deploymentScriptsRPM.getPath().replaceAll(" ", "\\ "),
                    deploymentScriptsRPM.getParentFile().getPath().replaceAll(" ", "\\ "));
            deploymentScriptsRPM.delete();
            deploymentScriptsRPM = new File(Joiner.on(File.separator).join(targetFolder,
                    artifact.getArtifactId(), "nds_" + artifact.getArtifactId() + "_deployment-scripts" + "-"
                            + artifact.getVersion() + "_1.noarch.rpm"));
        }

        LogUtils.log(listener, deploymentScriptsRPM.getParentFile().list().toString());
        FileUtils.moveFileToDirectory(deploymentScriptsRPM,
                new File(Joiner.on(File.separator).join(targetFolder, "repo")), true);
        LogUtils.log(listener, "Copied deployment-scripts to repo directory");
    }
    MavenPom mp = new MavenPom(
            new File(Joiner.on(File.separator).join(targetFolder, artifact.getArtifactId(), "pom.xml")));
    List<ArtifactParameters> rpms = mp.getPomModuleDependencies();

    // download rpms to archive/repo
    LogUtils.logSection(listener, "Download dependent RPMS.");
    for (ArtifactParameters m : rpms) {
        new NexusClient(m, build, listener).downloadRPM(Joiner.on(File.separator).join(targetFolder, "repo"));
    }

    // create yum repo
    createAndMoveYumRepo(build, listener, yumRepoParameters,
            Joiner.on(File.separator).join(targetFolder, "repo"),
            String.valueOf(deployParmeters.getDeployCounter()));
    LogUtils.log(listener, "YUM repository have been created.");

    // deploy stack
    String stackName = artifact.getArtifactId().toLowerCase().replace("-product", "");

    openStackClient.createStack(stackName, deployParmeters.getOverridingParameters(),
            deployParmeters.getGlobalOutputs(), Joiner.on(File.separator).join(targetFolder,
                    artifact.getArtifactId(), "archive", "heat", stackName));

    long startTime = System.currentTimeMillis();
    boolean createComplete = false;

    while (!createComplete && System.currentTimeMillis() - startTime < CREATE_TIMEOUT) {
        StackStatus stackStatus = openStackClient.getStackStatus(stackName);
        LogUtils.log(listener, "Waiting for stack creation for " + stackName + ". Status is: " + stackStatus);
        if (stackStatus == StackStatus.CREATE_COMPLETE) {
            createComplete = true;
            // update outputs map
            Map<String, String> stackOutputs = openStackClient.getStackOutputs(stackName);
            deployParmeters.setGlobalOutputsWithNewOutputs(stackOutputs);
        } else if (stackStatus == StackStatus.FAILED || stackStatus == StackStatus.CREATE_FAILED
                || stackStatus == StackStatus.UNDEFINED)
            throw new ProductDeployPluginException("Failed to Launch Stack " + stackName);
        else
            Thread.sleep(SLEEP_TIME);

    }
    // if stack is not complete after 40 minutes -  throw a timeout exception
    if (!createComplete)
        throw new TimeoutException("Create Stack- timeout exception");

    // clean files
    try {
        FileUtils.cleanDirectory(new File(Joiner.on(File.separator).join(targetFolder, "repo")));
    } catch (IOException e) {
        /*Swallow*/ }

    deployParmeters.increaseDeployCounter();
    LogUtils.log(listener, "Increased deployment counter.");

    return true;

}

From source file:org.jenkinsci.plugins.os_ci.ProductBuilder.java

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

    FileUtils.cleanDirectory(new File(build.getRootBuild().getModuleRoot().getRemote()));
    LogUtils.log(listener, "Cleaned directory: " + build.getRootBuild().getModuleRoot().getRemote());
    final String tempTargetFolder = Joiner.on(File.separator).join(build.getWorkspace().getRemote(),
            "temp_archive");
    final String targetFolder = Joiner.on(File.separator).join(build.getWorkspace().getRemote(), "archive");
    final String scriptsFolder = Joiner.on(File.separator).join(build.getWorkspace().getRemote(),
            "deployment-scripts");

    // Get product version from Nexus and increase minor version
    ArtifactParameters artifact = null;// w  w w.j  a  v  a 2 s  . c o m
    if (VersionUtils.checkVersionParameterExists(build)) {
        artifact = new ArtifactParameters(groupId, artifactId, VersionUtils.getVersionParameterValue(build),
                "pom");
    } else {
        artifact = new ArtifactParameters(groupId, artifactId, "LATEST", "pom");
    }
    Product product = new Product(artifact, build, listener);
    artifact.setVersion(new NexusClient(artifact, build, listener).increaseVersion(increaseVersionOption));
    artifact.setOsVersion("pom");
    // Resolve version information on all Products
    LogUtils.logSection(listener, "Getting Nexus dependentProducts versions");
    ArrayList<ArtifactParameters> productDependencies = VersionUtils
            .resolveVersionInformation(dependentProducts, build, listener);

    // Resolve version information on all Modules
    LogUtils.logSection(listener, "Getting Nexus component versions");
    ArrayList<ArtifactParameters> artifactDependencies = VersionUtils.resolveVersionInformation(artifacts,
            build, listener);

    // download GIT repos
    if (!product.downloadGitRepos(tempTargetFolder, targetFolder, scriptsFolder, scriptsGitUrl, heatGitUrl,
            puppetBaseGitUrl))
        return false;

    // download all non-Nexus artifacts
    LogUtils.logSection(listener, "Downloading URLs");
    if (externalDependencies != null) {
        for (UrlParameters externalDependency : externalDependencies) {
            UrlClient uc = new UrlClient(externalDependency, build, listener);
            uc.downloadRPM();
            LogUtils.log(listener, "Downloaded url " + externalDependency.getUrl());
        }
    }

    // Download Puppet scripts
    if (artifactDependencies != null) {
        List<String> fileTypes = new ArrayList<String>();
        fileTypes.add("puppet.tar.gz");
        for (ArtifactParameters ap : artifactDependencies) {
            FileUtils.forceMkdir(new File(Joiner.on(File.separator).join(scriptsFolder, "puppets", "modules")));
            NexusClient nc = new NexusClient(ap, build, listener);
            List<String> names = nc.downloadProductArtifacts(ap,
                    Joiner.on(File.separator).join(scriptsFolder, "puppets", "modules"), fileTypes);

            if (names.size() > 0) {
                File puppetTarFile = new File(Joiner.on(File.separator).join(scriptsFolder, "puppets",
                        "modules", "external_dependencies.tar.gz"));
                if (puppetTarFile.exists()) {
                    CompressUtils.untarFile(puppetTarFile);
                    FileUtils.deleteQuietly(puppetTarFile);
                }
            }
        }
    }

    // Build external_dependencies.tar.gz from artifacts and scripts
    String tarPath = product.createExternalDependenciesTar(targetFolder);
    if (tarPath == null) {
        return false;
    }

    // Create pom.xml
    String pomPath = product.createPom(targetFolder, productDependencies, artifactDependencies);
    String rpmPomPath = product.createRPMPom(scriptsFolder);

    // upload pom, rpm and tar to Nexus
    NexusClient nexusClient = new NexusClient(artifact, build, listener);

    if (!System.getProperty("os.name").toLowerCase().startsWith("windows")) {
        try {
            FileUtils.deleteDirectory(new File(Joiner.on(File.separator).join(scriptsFolder, "target")));
        } finally {
            LogUtils.logSection(listener, "Puppet scrips RPM creation");
            MavenInvoker.createRPM(rpmPomPath, build, listener);
            LogUtils.log(listener, "Created rpm from pom:" + rpmPomPath);
        }
        nexusClient.uploadPomWithExternalDependencies("versionDesc", pomPath, "pom.xml", tarPath,
                "external_dependencies.tar.gz",
                Joiner.on(File.separator).join(scriptsFolder, "target", "rpm",
                        "nds_" + artifact.getArtifactId() + "_deployment-scripts", "RPMS", "noarch",
                        "nds_" + artifact.getArtifactId() + "_deployment-scripts-" + artifact.getVersion()
                                + "_1.noarch.rpm"));

    } else {
        nexusClient.uploadPomWithExternalDependencies("versionDesc", pomPath, "pom.xml", tarPath,
                "external_dependencies.tar.gz", null);
    }
    build.setDescription(artifact.getVersion());
    return true;
}

From source file:org.jenkinsci.plugins.vssj.VssExe.java

/**
 * Clean a project directory./* ww w  .jav a2  s.c  o  m*/
 * @param project SourceSafe project
 * @throws IOException if clean failed
 */
public void clean(String project) throws IOException {
    File dir = new File(getVssProjectDirectory(project));
    if (dir.exists()) {
        listener.getLogger().println("Clean Directory: " + dir.getAbsolutePath());
        FileUtils.cleanDirectory(dir);
    }
    dir.mkdirs();
}

From source file:org.jsweet.input.typescriptdef.TypescriptDef2Java.java

public static void printAst(File outputDir, Context context) {
    outputDir.mkdirs();//from   ww  w .j a  va  2s  .c  o  m
    try {
        FileUtils.cleanDirectory(outputDir);
    } catch (IOException e) {
        logger.error("did not clean output directory: " + outputDir, e);
    }
    scan((cu, scanner) -> {
        logger.info("translated " + cu);
    }, context.compilationUnits, new JavaDefModelPrinter(context, outputDir));
}

From source file:org.kaaproject.kaa.examples.robotrun.visualization.emulator.EmulatorProcess.java

public EmulatorProcess(Integer id, File labyrinthFile, Cell startCell, Direction startDirection,
        Properties robotProperties, int debugPort, EmulatorCallback callback) {

    this.id = id;
    this.callback = callback;

    String workingDir = System.getProperty("user.dir");

    File emulatorWorkingDir = new File(new File(workingDir), EMULATOR_ID_PREFIX + id);
    if (!emulatorWorkingDir.exists()) {
        emulatorWorkingDir.mkdirs();//w w  w.  j  a v  a2  s  .co m
    } else {
        try {
            FileUtils.cleanDirectory(emulatorWorkingDir);
        } catch (IOException e) {
            LOG.error("Unable to clean emulator directory {}", emulatorWorkingDir);
            throw new RuntimeException("Unable to clean emulator directory!");
        }
    }

    outFile = new File(emulatorWorkingDir, OUT_FILE);
    try {
        emulatorStdout = new PrintWriter(outFile);
    } catch (IOException e) {
        LOG.error("Unable to create emulator stdout {}", outFile);
        throw new RuntimeException("Unable to create emulator stdout!");
    }

    String separator = System.getProperty("path.separator");
    String classPath = System.getProperty("java.class.path");
    String[] classPathUnits = classPath.split(separator);
    StringBuilder normalizedClassPath = new StringBuilder();
    for (int i = 0; i < classPathUnits.length; i++) {
        File classPathUnitFile = new File(classPathUnits[i]);
        if (classPathUnitFile.exists()) {
            if (i > 0) {
                normalizedClassPath.append(separator);
            }
            normalizedClassPath.append(classPathUnitFile.getAbsolutePath());
        }
    }

    List<String> command = new ArrayList<>();
    command.add("java");
    command.add("-cp");
    command.add(normalizedClassPath.toString());
    if (debugPort > -1) {
        command.add("-Xdebug");
        command.add("-Xrunjdwp:server=y,transport=dt_socket,address=" + debugPort + ",suspend=n");
    }
    command.add(EmulatorMain.class.getName());
    command.add(labyrinthFile.getAbsolutePath());
    command.add("" + startCell.getX());
    command.add("" + startCell.getY());
    command.add(startDirection.name());
    command.add("" + id);

    if (robotProperties != null) {
        for (Object key : robotProperties.keySet()) {
            String val = robotProperties.getProperty("" + key);
            command.add(key + "=" + val);
        }
    }

    StringBuilder emulatorStartCommand = new StringBuilder();
    for (String arg : command) {
        emulatorStartCommand.append(arg + " ");
    }

    emulatorStdout.println("Starting emulator using the following command:");
    emulatorStdout.println(emulatorStartCommand.toString());

    processBuilder = new ProcessBuilder(command);
    processBuilder.directory(emulatorWorkingDir);
    processBuilder.redirectErrorStream(true);
}