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.artifactory.webapp.wicket.application.ArtifactoryApplication.java

/**
 * Delete the upload folder (in case we were not shut down cleanly)
 *//*from ww  w  . j  a v a 2s.  c  o m*/
private void deleteUploadsFolder() {
    ArtifactoryHome artifactoryHome = getArtifactoryContext().getArtifactoryHome();
    File tmpUploadsDir = artifactoryHome.getTempUploadDir();
    if (tmpUploadsDir.exists()) {
        try {
            FileUtils.cleanDirectory(tmpUploadsDir);
        } catch (IOException ignore) {
            log.warn("Failed to delete the upload directory.");
        }
    }
}

From source file:org.astrojournal.configuration.ajconfiguration.AJConfigurationUtils.java

/**
 * Delete the previous output folder content if this is present.
 * //from  ww  w  . ja v  a2s . c o m
 * @param config
 *            The configuration.
 * @throws IOException
 *             if the folder could not be cleaned.
 */
@Override
public void cleanFolder(Configuration config) throws IOException {
    File filesLocation = new File(config.getProperty(AJPropertyConstants.FILES_LOCATION.getKey()));
    if (!(filesLocation.exists() && filesLocation.canWrite())) {
        throw new FileNotFoundException();
    }
    try {
        FileUtils.cleanDirectory(new File(filesLocation.getAbsolutePath() + File.separator
                + config.getProperty(AJPropertyConstants.LATEX_REPORTS_FOLDER_BY_DATE.getKey())));
        FileUtils.cleanDirectory(new File(filesLocation.getAbsolutePath() + File.separator
                + config.getProperty(AJPropertyConstants.LATEX_REPORTS_FOLDER_BY_TARGET.getKey())));
        FileUtils.cleanDirectory(new File(filesLocation.getAbsolutePath() + File.separator
                + config.getProperty(AJPropertyConstants.LATEX_REPORTS_FOLDER_BY_CONSTELLATION.getKey())));
        FileUtils.cleanDirectory(new File(filesLocation.getAbsolutePath() + File.separator
                + config.getProperty(AJPropertyConstants.TXT_REPORTS_FOLDER_BY_DATE.getKey())));
    } catch (IOException e) {
        throw e;
    }
}

From source file:org.bonitasoft.platform.setup.PlatformSetup.java

public void pull(Path configurationFolder, Path licensesFolder) throws PlatformException {
    try {/*from  w ww. j a v a2  s.c  o  m*/
        recreateDirectory(configurationFolder);
        if (Files.isDirectory(licensesFolder)) {
            FileUtils.cleanDirectory(licensesFolder.toFile());
        }
        List<File> licenses = new ArrayList<>();
        List<File> files = configurationService.writeAllConfigurationToFolder(configurationFolder.toFile(),
                licensesFolder.toFile());
        LOGGER.info("Retrieved following files in " + configurationFolder);
        for (File file : files) {
            if (file.toPath().getParent().equals(licensesFolder)) {
                licenses.add(file);
            } else {
                LOGGER.info(configurationFolder.relativize(file.toPath()).toString());
            }
        }
        if (!licenses.isEmpty()) {
            LOGGER.info("Retrieved following licenses in " + licensesFolder);
            for (File license : licenses) {
                LOGGER.info(licensesFolder.relativize(license.toPath()).toString());
            }
        }
    } catch (IOException e) {
        throw new PlatformException(e);
    }
}

From source file:org.clickframes.mavenplugin.ClickframesGenPlugin.java

@SuppressWarnings("unchecked")
// @Override/*from  ww w .  j ava  2 s  .  c  o m*/
public void processProject(Techspec techspec, Appspec appspec) throws IOException, MojoExecutionException {
    List<String> classpathEntries = getMavenRuntimeClasspathEntries();
    List<String> autoscanTemplatesFromClasspath = RuntimeManifestGenerator
            .getAutoscanTemplatesFromClasspath(classpathEntries);

    File originalOutputDirectory = techspec.getOutputDirectory();
    File incomingDirectory = new File(originalOutputDirectory,
            "target" + File.separator + "clickframes-incoming");
    File modifiedDirectory = new File(originalOutputDirectory,
            "target" + File.separator + "clickframes-modified");

    try {
        if (modifiedDirectory.exists()) {
            FileUtils.deleteDirectory(modifiedDirectory);
        }
        // run the techspec in a temp directory
        if (incomingDirectory.exists()) {
            FileUtils.cleanDirectory(incomingDirectory);
        }
        techspec.setOutputDirectory(incomingDirectory);

        TechspecRunner.run(techspec, appspec, autoscanTemplatesFromClasspath);

        // update manifest from directory, using basepath
        TechspecManifest techspecManifest;

        File techspecManifestFile = new File(getClickframesDirectory(), "techspec-manifest.xml");

        if (!techspecManifestFile.exists()) {
            techspecManifest = TechspecManifest.create();
        } else {
            try {
                techspecManifest = TechspecManifest
                        .readTechspecManifest(new FileInputStream(techspecManifestFile));
            } catch (JAXBException e) {
                throw new MojoExecutionException("Invalid manifest file", e);
            }
        }

        int addedCount = 0;
        int modifications = 0;
        for (File newFile : (Collection<File>) FileUtils.listFiles(techspec.getOutputDirectory(),
                FileFilterUtils.trueFileFilter(), FileFilterUtils.trueFileFilter())) {
            addedCount += techspecManifest.addOrUpdateEntry(techspec.getOutputDirectory(), newFile) ? 1 : 0;

            // copy newFile from tmpdir to originalOutputDir, preserving the
            // relative path - if original source is not modified

            File dest = ClickframeUtils.getDestinationFile(techspec.getOutputDirectory(), newFile,
                    originalOutputDirectory);

            // if dest is modified, we want to keep a list of original
            // version of modified files handy
            if (dest.exists() && VelocityCodeGenerator.isModified(dest)) {
                File modifiedDest = ClickframeUtils.getDestinationFile(techspec.getOutputDirectory(), newFile,
                        modifiedDirectory);
                FileUtils.copyFile(newFile, modifiedDest);
            }

            boolean moved = VelocityCodeGenerator.moveIfContentNotModified(newFile, dest);

            if (!moved && VelocityCodeGenerator.isSameEmbeddedChecksum(newFile, dest)) {
                // source template is not modified, but destination may have
                // been
                // customized
                newFile.delete();
                modifications += 1;
            }

            // remove empty directories - as we go along
            File parent = newFile.getParentFile();

            while (parent.list().length == 0
                    && parent.getCanonicalPath() != techspec.getOutputDirectory().getCanonicalPath()) {
                parent.delete();
                parent = parent.getParentFile();
            }
        }

        if (modifications > 0) {
            getLog().info(modifications + " incoming changes blocked by local modifications, see "
                    + incomingDirectory.getCanonicalPath());
        }

        // save techspec manifest
        try {
            techspecManifestFile.getParentFile().mkdirs();
            FileUtils.writeStringToFile(techspecManifestFile, techspecManifest.toXml());
            // getLog().info(addedCount +
            // " entries added to manifest, wrote " +
            // techspecManifestFile.getCanonicalPath());
        } catch (JAXBException e) {
            throw new MojoExecutionException("Error saving manifest", e);
        }
    } catch (IOException e) {
        throw new RuntimeException("Could not clean the tmp directory:" + incomingDirectory.getAbsolutePath());
    } finally {
        techspec.setOutputDirectory(originalOutputDirectory);
    }
}

From source file:org.clickframes.mavenplugin.TechspecRunnerPlugin.java

@SuppressWarnings("unchecked")
// @Override//from  www  .  j a va2s .  c  om
public void processProject2(Techspec techspec, Appspec appspec) throws IOException, MojoExecutionException {
    List<String> classpathEntries = getMavenRuntimeClasspathEntries();
    List<String> autoscanTemplatesFromClasspath = RuntimeManifestGenerator
            .getAutoscanTemplatesFromClasspath(classpathEntries);

    File originalOutputDirectory = techspec.getOutputDirectory();
    File incomingDirectory = new File(originalOutputDirectory,
            "target" + File.separator + "clickframes-incoming");
    File modifiedDirectory = new File(originalOutputDirectory,
            "target" + File.separator + "clickframes-modified");

    try {
        if (modifiedDirectory.exists()) {
            FileUtils.deleteDirectory(modifiedDirectory);
        }
        // run the techspec in a temp directory
        if (incomingDirectory.exists()) {
            FileUtils.cleanDirectory(incomingDirectory);
        }
        techspec.setOutputDirectory(incomingDirectory);

        TechspecRunner.run(techspec, appspec, autoscanTemplatesFromClasspath);

        // update manifest from directory, using basepath
        TechspecManifest techspecManifest;

        File techspecManifestFile = new File(clickframesDirectory, "techspec-manifest.xml");

        if (!techspecManifestFile.exists()) {
            techspecManifest = TechspecManifest.create();
        } else {
            try {
                techspecManifest = TechspecManifest
                        .readTechspecManifest(new FileInputStream(techspecManifestFile));
            } catch (JAXBException e) {
                throw new MojoExecutionException("Invalid manifest file", e);
            }
        }

        int addedCount = 0;
        int modifications = 0;
        for (File newFile : (Collection<File>) FileUtils.listFiles(techspec.getOutputDirectory(),
                FileFilterUtils.trueFileFilter(), FileFilterUtils.trueFileFilter())) {
            addedCount += techspecManifest.addOrUpdateEntry(techspec.getOutputDirectory(), newFile) ? 1 : 0;

            // copy newFile from tmpdir to originalOutputDir, preserving the
            // relative path - if original source is not modified

            File dest = ClickframeUtils.getDestinationFile(techspec.getOutputDirectory(), newFile,
                    originalOutputDirectory);

            // if dest is modified, we want to keep a list of original
            // version of modified files handy
            if (dest.exists() && VelocityCodeGenerator.isModified(dest)) {
                File modifiedDest = ClickframeUtils.getDestinationFile(techspec.getOutputDirectory(), newFile,
                        modifiedDirectory);
                FileUtils.copyFile(newFile, modifiedDest);
            }

            boolean moved = VelocityCodeGenerator.moveIfContentNotModified(newFile, dest);

            if (!moved && VelocityCodeGenerator.isSameEmbeddedChecksum(newFile, dest)) {
                // source template is not modified, but destination may have
                // been
                // customized
                newFile.delete();
                modifications += 1;
            }

            // remove empty directories - as we go along
            File parent = newFile.getParentFile();

            while (parent.list().length == 0
                    && parent.getCanonicalPath() != techspec.getOutputDirectory().getCanonicalPath()) {
                parent.delete();
                parent = parent.getParentFile();
            }
        }

        if (modifications > 0) {
            getLog().info(modifications + " incoming changes blocked by local modifications, see "
                    + incomingDirectory.getCanonicalPath());
        }

        // save techspec manifest
        try {
            techspecManifestFile.getParentFile().mkdirs();
            FileUtils.writeStringToFile(techspecManifestFile, techspecManifest.toXml());
            // getLog().info(addedCount +
            // " entries added to manifest, wrote " +
            // techspecManifestFile.getCanonicalPath());
        } catch (JAXBException e) {
            throw new MojoExecutionException("Error saving manifest", e);
        }
    } catch (IOException e) {
        throw new RuntimeException("Could not clean the tmp directory:" + incomingDirectory.getAbsolutePath());
    } finally {
        techspec.setOutputDirectory(originalOutputDirectory);
    }
}

From source file:org.cloudifysource.dsl.download.ResourceDownloaderTest.java

private void cleanDownloadFolder() throws IOException {
    FileUtils.cleanDirectory(new File(DESTINATION_FOLDER));
}

From source file:org.dataconservancy.dcs.index.rebuild.DcsHome.java

public static void prepareHome(Class<?> testClass) {
    try {/*from   www .  j  av  a2  s . c  o m*/

        Properties defaultProps = new Properties();
        defaultProps.load(DcsHome.class.getResourceAsStream("/default.properties"));

        MDC.put("testClass", testClass.getName());

        System.out.println(">>> DCS HOME " + defaultProps.getProperty("dcs.home"));

        File dcsHome = new File(defaultProps.getProperty("dcs.home"), testClass.getName());

        System.out.println(">>> DCS HOME " + dcsHome);

        System.setProperty("dcs.home", dcsHome.getAbsolutePath());

        if (dcsHome.exists()) {
            FileUtils.cleanDirectory(dcsHome);
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.dataconservancy.packaging.tool.impl.generator.BagItPackageAssembler.java

/**
 * Initializes the Assembler. Operations include:
 * <ul>/*www  .j a  va  2s  .  co m*/
 *     <li>Checking for required parameters</li>
 *     <li>Creating a base directory for the bag</li>
 *     <li>Creating a payload directory</li>
 * </ul>
 *
 * Required parameters for this kind of Assembler include:
 * <ul>
 *     <li>package-name</li>
 *     <li>Bag-It-Profile-Identifier</li>
 *     <li>Contact-Name</li>
 *     <li>Contact-Phone</li>
 *     <li>Contact-Email</li>
 * </ul>
 *
 * Optional with defaults parameters:
 * <ul>
 *     <li> archiving-format: when not set, is defaulted to ".tar" </li>
 *     <li> compression-format: when not set, no compression will be performed on the serialized content. </li>
 *     <li> checksum-algs: when not set, is defaulted to "md5" </li>
 * </ul>
 *
 * NOTE: If this is called a second time, the first initialization will still take effect unless parameters are
 * specifically overridden in the second call.  It's probably not a good idea to call this more than once in most
 * cases; if you just need to add parameters after initialization, use the
 * {@link #addParameter(String, String) addParameter} method.
 * @param params The parameters object containing whatever is needed for the assembler.
 */
@Override
public void init(PackageGenerationParameters params) {
    //Checking for required parameters
    this.params = params;

    //validate parameters
    validateParams();

    //retrieve list of checksum algorithms to be performed
    checksumAlgs = params.getParam(BagItParameterNames.CHECKSUM_ALGORITHMS);

    if (checksumAlgs == null) {
        checksumAlgs = new ArrayList<>();
    }
    if (checksumAlgs.isEmpty()) {
        //Indicates the default checksum algorithm that would be used if none is provided.
        String defaultChecksumAlg = "md5";
        checksumAlgs.add(defaultChecksumAlg);
    }

    //retrieve archiving format, if it is set in the input parameters
    if (params.getParam(BagItParameterNames.ARCHIVING_FORMAT) != null
            && !params.getParam(BagItParameterNames.ARCHIVING_FORMAT).isEmpty()) {
        archivingFormat = params.getParam(BagItParameterNames.ARCHIVING_FORMAT, 0);
        validateArchivingFormat();
    }

    if (archivingFormat.equals("exploded")) {
        isExploded = true;
    }

    //retrieve compression format, if it is set in the input parameters
    if (params.getParam(BagItParameterNames.COMPRESSION_FORMAT) != null
            && !params.getParam(BagItParameterNames.COMPRESSION_FORMAT).isEmpty()) {
        compressionFormat = params.getParam(BagItParameterNames.COMPRESSION_FORMAT, 0);
        validateCompressionFormat();
    }

    //Create a parent dir, must be in a user-controlled location. default will be set here as the users homeDir/packageStaging.
    //This can be overridden in the defaultGenerationParams file
    //This will help prevent deleting data if a user tries to create a package in place.
    String packageStagingLocationName = System.getProperty("user.home") + File.separator
            + "DCS-PackageToolStaging";
    String packageStagingLocationParameterValue = params
            .getParam(GeneralParameterNames.PACKAGE_STAGING_LOCATION, 0);
    String packageLocationParameterValue = params.getParam(GeneralParameterNames.PACKAGE_LOCATION, 0);

    if (isExploded) {
        if (packageLocationParameterValue != null && !packageLocationParameterValue.isEmpty()) {
            packageStagingLocationName = packageLocationParameterValue;
        }
    } else {
        if (packageStagingLocationParameterValue != null && !packageStagingLocationParameterValue.isEmpty()) {
            packageStagingLocationName = packageStagingLocationParameterValue;
        }
    }
    packageLocationDir = new File(packageStagingLocationName);

    //Creating base directory for the bag based on specified package name
    if (!packageLocationDir.exists()) {
        log.info("Creating bag base dir: " + packageLocationDir.getPath());
        boolean isDirCreated = packageLocationDir.mkdirs();
        if (!isDirCreated) {
            throw new PackageToolException(PackagingToolReturnInfo.PKG_ASSEMBLER_DIR_CREATION_EXP,
                    "\nAttempt to create staging directory for the package at \"" + packageLocationDir.getPath()
                            + "\" failed. Possible reasons include: \n"
                            + "- Permission restriction in creating the specified directory \n" + "- \""
                            + packageLocationDir.getPath()
                            + "\" is not a valid path. For more information about "
                            + "where this value can be set and what it is used for, see release documentation on "
                            + "Package Generation Parameters, Package-Staging-Location parameter in particular.");
        }
    }

    //retrieve package name from params
    //Name of the packageName as specified in the input parameters.
    String packageName = params.getParam(BagItParameterNames.PACKAGE_NAME, 0);

    //Creating base directory
    bagBaseDir = new File(packageLocationDir, packageName);
    //Creating base directory for the bag based on specified package name
    if (!bagBaseDir.exists()) {
        log.info("Creating bag base dir: " + bagBaseDir.getPath());
        boolean isDirCreated = bagBaseDir.mkdirs();
        if (!isDirCreated) {
            throw new PackageToolException(PackagingToolReturnInfo.PKG_ASSEMBLER_DIR_CREATION_EXP,
                    "Attempt to create a base directory for bag at " + bagBaseDir.getPath() + " failed.");
        }
    } else {
        //If it exists remove everything in it and start fresh
        try {
            FileUtils.cleanDirectory(bagBaseDir);
        } catch (IOException e) {
            log.warn("Exception thrown when cleaning existing directory: " + e.getMessage());
        }
    }

    //Creating payload directory
    payloadDir = new File(bagBaseDir, "data");
    //Creating payloadDir
    if (!payloadDir.exists()) {
        log.info("Creating payload dir: " + payloadDir.getPath());
        boolean isDirCreated = payloadDir.mkdirs();
        if (!isDirCreated) {
            throw new PackageToolException(PackagingToolReturnInfo.PKG_ASSEMBLER_DIR_CREATION_EXP,
                    "Attempt to create a payload directory for bag at " + payloadDir.getPath() + " failed.");
        }
    }

}

From source file:org.dataconservancy.packaging.tool.model.impl.PackageStateBuilderImpl.java

/**
 * This implementation of the {@link org.dataconservancy.packaging.tool.model.PackageStateBuilder} produce the
 * serialization of the {@link org.dataconservancy.packaging.tool.model.PackageState} object in a
 * {@link java.util.zip.ZipOutputStream} which contains multiple {@link java.util.zip.ZipEntry} of its content.
 * These are the {@link java.util.zip.ZipEntry} that can be expected to be in the {@link java.util.zip.ZipOutputStream}
 * produced by this method: Name:Value file of Package and Tool Metadata, Serialized {@code DomainObjectStore},
 * Serialized package tree {@code Node}, Serialized list of {@code DomainProfile}s relevant to the package.
 * @param state//w  w  w .j  a  v a  2  s  .co  m
 *        {@link org.dataconservancy.packaging.tool.model.PackageState} to serialize.
 * @param stream
 *        The {@link java.io.OutputStream} to serialize to.
 * @throws PackageToolException
 */
@Override
public void serialize(PackageState state, OutputStream stream) throws PackageToolException {
    //Create a staging directory for this package:
    File packageStageDir = new File(this.stagingDirectory, state.getPackageName());

    //Creating a staging directory for the package state file
    if (!packageStageDir.exists()) {
        log.info("Creating bag base dir: " + packageStageDir.getPath());
        boolean isDirCreated = packageStageDir.mkdirs();
        if (!isDirCreated) {
            throw new PackageToolException(PackagingToolReturnInfo.PKG_DIR_CREATION_EXP,
                    "Attempt to create a base directory for bag at " + packageStageDir.getPath() + " failed.");
        }
    } else {
        //If it exists remove everything in it and start fresh
        try {
            FileUtils.cleanDirectory(packageStageDir);
        } catch (IOException e) {
            log.warn("Exception thrown when cleaning existing directory: " + e.getMessage());
        }
    }
    //create zip outputstream
    ZipOutputStream zipOStream = new ZipOutputStream(stream);

    try {
        /****************************************************
         * Write Package and tool metadata to file
         ****************************************************/
        //Create file to write package and tool metadata into
        File packageToolMetadataFile = new File(packageStageDir, PACKAGE_TOOL_METADATA_FILE);
        //write package and tool metadata from state object to package-tool-metadata file
        writePackageMetadata(state, packageToolMetadataFile);
        //create package-tool-metadata file to the zip outputstream
        writeToZipOutputStream(zipOStream, packageToolMetadataFile);
        /****************************************************
         * TODO: Write DomainObjectStore to file
         ****************************************************/
        /****************************************************
        * TODO: Write DomainProfileList to file
        ****************************************************/
        /****************************************************
        * TODO: Write Package tree to file
        ****************************************************/
    } catch (IOException e) {
        throw new PackageToolException(PackagingToolReturnInfo.PKG_IO_EXCEPTION, e);
    } finally {
        try {
            zipOStream.close();
        } catch (IOException e) {
            log.error("Unable to close zip output stream for the serialized package state file.", e);
            throw new PackageToolException(PackagingToolReturnInfo.PKG_IO_EXCEPTION, e);
        }
    }

    try {
        FileUtils.deleteDirectory(packageStageDir);
    } catch (IOException e) {
        log.warn("Could not clean up staging directory created during the serialization of package state ."
                + e.getMessage());

    }
}

From source file:org.dbmaintain.integrationtest.DbMaintainIntegrationTest.java

private void clearScriptsDirectory() {
    try {//from   w w  w  .j  av a  2s  .com
        FileUtils.cleanDirectory(scriptsLocation);
    } catch (IOException e) {
        throw new DbMaintainException(e);
    } catch (IllegalArgumentException e) {
        // Ignored
    }
}