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.openremote.beehive.listener.ApplicationListener.java

private SVNUrl checkRepoExists(String svnDir, File svnRepo, SVNUrl svnUrl, File workCopyDir) {
    try {//from ww  w  .j  a  v  a2s . c  om
        svnUrl = new SVNUrl(svnDir);
        svnClient.getInfo(svnUrl);
    } catch (MalformedURLException e) {
        logger.error("Create SVNUrl from " + svnDir + " failed!");
    } catch (NullPointerException e) {
        logger.error("Create svn client from " + svnUrl + " failed!");
    } catch (SVNClientException e) {
        try {
            if (svnRepo.exists()) {
                logger.info("Clean svn repository directory " + svnRepo.getPath() + " ......");
                FileUtils.cleanDirectory(svnRepo);
                logger.info("Clean svn repository directory " + svnRepo.getPath() + " success");
            } else {
                svnRepo.mkdirs();
            }
            svnClient.createRepository(svnRepo, ISVNClientAdapter.REPOSITORY_BDB);
            logger.info("Create svn repository " + svnRepo.getPath() + " success.");
            svnClient.mkdir(svnUrl, true, "create /trunk");
            logger.info("Make svn directory " + svnDir + " success!");
            if (workCopyDir.exists()) {
                logger.info("Clean workCopy " + workCopyDir.getPath() + " ......");
                FileUtils.cleanDirectory(workCopyDir);
                logger.info("Clean workCopy " + workCopyDir.getPath() + " success.");
            } else {
                workCopyDir.mkdirs();
                logger.info("Create workCopy directory " + workCopyDir.getPath() + " success.");
            }
            logger.info("Checkout " + svnUrl + " to " + workCopyDir + " ......");
            svnClient.checkout(svnUrl, workCopyDir, SVNRevision.HEAD, true);
            logger.info("Checkout " + svnUrl + " to " + workCopyDir + " success.");
        } catch (SVNClientException e1) {
            logger.error("Unable to create local repository '" + svnDir
                    + "', please install svn server to sync with LIRC.");
            return null;
        } catch (IOException e2) {
            logger.error("Can't clean dir " + svnRepo + " or " + workCopyDir);
        }
    }
    return svnUrl;
}

From source file:org.openremote.beehive.listener.ApplicationListener.java

private void checkWorkCopyExists(SVNUrl svnUrl, File workCopyDir) {
    try {//from   w  ww .j  a  v  a2 s .co m
        svnClient.getInfo(workCopyDir);
    } catch (NullPointerException e) {
        logger.error("Create svn client from " + svnUrl + " failed!");
    } catch (SVNClientException e) {
        try {
            if (workCopyDir.exists()) {
                logger.info("Clean workCopy " + workCopyDir.getPath() + " ......");
                FileUtils.cleanDirectory(workCopyDir);
                logger.info("Clean workCopy " + workCopyDir.getPath() + " success.");
            } else {
                workCopyDir.mkdirs();
                logger.info("Create workCopy directory " + workCopyDir.getPath() + " success.");
            }
            logger.info("Checkout " + svnUrl + " to " + workCopyDir + " ......");
            svnClient.checkout(svnUrl, workCopyDir, SVNRevision.HEAD, true);
            logger.info("Checkout " + svnUrl + " to " + workCopyDir + " success.");
        } catch (SVNClientException e1) {
            logger.error("Can't checkout " + svnUrl + " to " + workCopyDir);
        } catch (IOException e1) {
            logger.error("Can't clean dir " + workCopyDir);
        }
    }
}

From source file:org.opentestsystem.authoring.testspecbank.service.impl.FileManagerServiceImpl.java

@Override
public File initializeCleanDirectory(final String directoryName) {
    final File downloadDir = new File(tempFileDirectory + directoryName);
    downloadDir.mkdir();/*from w  ww  .  j  a  v a2  s.  c  o  m*/

    try {
        FileUtils.cleanDirectory(downloadDir);
    } catch (final IOException e) {
        LOGGER.error("unable to initialize local directory", e);
        throw new LocalizedException("localFile.directory.init",
                new String[] { tempFileDirectory + directoryName });
    }
    return downloadDir;
}

From source file:org.owasp.benchmark.score.BenchmarkScore.java

public static void main(String[] args) {
    if (args == null || args.length < 2) {
        System.out.println(usageNotice);
        System.exit(-1);/*from www  .  j a  va 2  s . c o m*/
    }

    if (args.length > 2) {
        focus = args[2].replace(' ', '_');
    }

    if (args.length > 3) {
        if ("anonymous".equalsIgnoreCase(args[3])) {
            anonymousMode = true;
        } else if ("show_ave_only".equalsIgnoreCase(args[3])) {
            showAveOnlyMode = true;
        } else {
            System.out.println(usageNotice);
            System.exit(-1);
        }
    }

    // Prepare the scorecard results directory for the newly generated scorecards
    // Step 1: Create the dir if it doesn't exist, or delete everything in it if it does
    File scoreCardDir = new File(scoreCardDirName);
    try {
        if (!scoreCardDir.exists()) {
            Files.createDirectories(Paths.get(scoreCardDirName));
        } else {
            System.out.println(
                    "Deleting previously generated scorecard files in: " + scoreCardDir.getAbsolutePath());
            FileUtils.cleanDirectory(scoreCardDir);
        }

        // Step 2: Now copy the entire /content directory, that either didn't exist, or was just deleted with everything else
        File dest1 = new File(scoreCardDirName + File.separator + "content");
        FileUtils.copyDirectory(new File(pathToScorecardResources + "content"), dest1);

    } catch (IOException e) {
        System.out.println("Error dealing with scorecard directory: '" + scoreCardDir.getAbsolutePath()
                + "' for some reason!");
        e.printStackTrace();
    }

    // Step 3: Copy over the Homepage and Guide templates
    try {
        Files.copy(Paths.get(pathToScorecardResources + HOMEFILENAME),
                Paths.get(scoreCardDirName + "/" + HOMEFILENAME), StandardCopyOption.REPLACE_EXISTING);

        Files.copy(Paths.get(pathToScorecardResources + GUIDEFILENAME),
                Paths.get(scoreCardDirName + "/" + GUIDEFILENAME), StandardCopyOption.REPLACE_EXISTING);
    } catch (IOException e) {
        System.out.println("Problem copying home and guide files");
        e.printStackTrace();
    }

    // Step 4: Read the expected results so we know what each tool 'should do'
    try {

        if ("mixed".equalsIgnoreCase(args[0])) {

            mixedMode = true; // Tells anyone that cares that we aren't processing a single version of Benchmark results

            File f = new File(args[1]);
            if (!f.exists()) {
                System.out.println("Error! - results directory: '" + f.getAbsolutePath() + "' doesn't exist.");
                System.exit(-1);
            }
            if (!f.isDirectory()) {
                System.out.println("Error! - results parameter is a file: '" + f.getAbsolutePath()
                        + "' but must be a directory when processing results in 'mixed' mode.");
                System.exit(-1);
            }

            // Go through each file in the root directory.
            // -- 1st find each directory. And then within each of those directories:
            //    -- 1st find the expected results file in that directory
            //    -- and then each of the actual results files in that directory
            for (File rootDirFile : f.listFiles()) {

                if (rootDirFile.isDirectory()) {

                    // Process this directory
                    TestResults expectedResults = null;
                    String expectedResultsFilename = null;
                    // Step 4a: Find and process the expected results file so we know what each tool in this directory 'should do'
                    for (File resultsDirFile : rootDirFile.listFiles()) {

                        if (resultsDirFile.getName().startsWith("expectedresults-")) {
                            if (expectedResults != null) {
                                System.out.println("Found 2nd expected results file "
                                        + resultsDirFile.getAbsolutePath()
                                        + " in same directory. Can only have 1 in each results directory");
                                System.exit(-1);
                            }

                            // read in the expected results for this directory of results
                            expectedResults = readExpectedResults(resultsDirFile);
                            if (expectedResults == null) {
                                System.out.println("Couldn't read expected results file: "
                                        + resultsDirFile.getAbsolutePath());
                                System.exit(-1);
                            } // end if

                            expectedResultsFilename = resultsDirFile.getName();
                            if (benchmarkVersion == null) {
                                benchmarkVersion = expectedResults.getBenchmarkVersion();
                            } else
                                benchmarkVersion += "," + expectedResults.getBenchmarkVersion();
                            System.out.println(
                                    "\nFound expected results file: " + resultsDirFile.getAbsolutePath());
                        } // end if
                    } // end for loop going through each file looking for expected results file

                    // Make sure we found an expected results file, before processing the results
                    if (expectedResults == null) {
                        System.out.println("Couldn't find expected results file in results directory: "
                                + rootDirFile.getAbsolutePath());
                        System.out.println(
                                "Expected results file has to be a .csv file that starts with: 'expectedresults-'");
                        System.exit(-1);
                    }

                    // Step 5a: Go through each result file and generate a scorecard for that tool.
                    if (!anonymousMode) {
                        for (File actual : rootDirFile.listFiles()) {
                            // Don't confuse the expected results file as an actual results file if its in the same directory
                            if (!actual.isDirectory() && !expectedResultsFilename.equals(actual.getName()))
                                process(actual, expectedResults, toolResults);
                        }
                    } else {
                        // To handle anonymous mode, we are going to randomly grab files out of this directory
                        // and process them. By doing it this way, multiple runs should randomly order the commercial
                        // tools each time.
                        List<File> files = new ArrayList();
                        for (File file : rootDirFile.listFiles()) {
                            files.add(file);
                        }

                        SecureRandom generator = SecureRandom.getInstance("SHA1PRNG");
                        while (files.size() > 0) {
                            // Get a random, positive integer
                            int fileToGet = Math.abs(generator.nextInt(files.size()));
                            File actual = files.remove(fileToGet);
                            // Don't confuse the expected results file as an actual results file if its in the same directory
                            if (!actual.isDirectory() && !expectedResultsFilename.equals(actual.getName()))
                                process(actual, expectedResults, toolResults);
                        }
                    }
                } // end if a directory
            } // end for loop through all files in the directory

            // process the results the normal way with a single results directory
        } else {

            // Step 4b: Read the expected results so we know what each tool 'should do'
            File expected = new File(args[0]);
            TestResults expectedResults = readExpectedResults(expected);
            if (expectedResults == null) {
                System.out.println("Couldn't read expected results file: " + expected);
                System.exit(-1);
            } else {
                System.out.println("Read expected results from file: " + expected.getAbsolutePath());
                int totalResults = expectedResults.totalResults();
                if (totalResults != 0) {
                    System.out.println(totalResults + " results found.");
                    benchmarkVersion = expectedResults.getBenchmarkVersion();
                } else {
                    System.out.println("Error! - zero expected results found in results file.");
                    System.exit(-1);
                }
            }

            // Step 5b: Go through each result file and generate a scorecard for that tool.
            File f = new File(args[1]);
            if (!f.exists()) {
                System.out.println("Error! - results file: '" + f.getAbsolutePath() + "' doesn't exist.");
                System.exit(-1);
            }
            if (f.isDirectory()) {
                if (!anonymousMode) {
                    for (File actual : f.listFiles()) {
                        // Don't confuse the expected results file as an actual results file if its in the same directory
                        if (!actual.isDirectory() && !expected.getName().equals(actual.getName()))
                            process(actual, expectedResults, toolResults);
                    }
                } else {
                    // To handle anonymous mode, we are going to randomly grab files out of this directory
                    // and process them. By doing it this way, multiple runs should randomly order the commercial
                    // tools each time.
                    List<File> files = new ArrayList();
                    for (File file : f.listFiles()) {
                        files.add(file);
                    }

                    SecureRandom generator = SecureRandom.getInstance("SHA1PRNG");
                    while (files.size() > 0) {
                        int randomNum = generator.nextInt();
                        // FIXME: Get Absolute Value better
                        if (randomNum < 0)
                            randomNum *= -1;
                        int fileToGet = randomNum % files.size();
                        File actual = files.remove(fileToGet);
                        // Don't confuse the expected results file as an actual results file if its in the same directory
                        if (!actual.isDirectory() && !expected.getName().equals(actual.getName()))
                            process(actual, expectedResults, toolResults);
                    }
                }

            } else {
                // This will process a single results file, if that is what the 2nd parameter points to.
                // This has never been used.
                process(f, expectedResults, toolResults);
            }
        } // end else

        System.out.println("Tool scorecards computed.");
    } catch (Exception e) {
        System.out.println("Error during processing: " + e.getMessage());
        e.printStackTrace();
    }

    // Step 6: Now generate scorecards for each type of vulnerability across all the tools

    // First, we have to figure out the list of vulnerabilities
    // A set is used here to eliminate duplicate categories across all the results
    Set<String> catSet = new TreeSet<String>();
    for (Report toolReport : toolResults) {
        catSet.addAll(toolReport.getOverallResults().getCategories());
    }

    // Then we generate each vulnerability scorecard
    BenchmarkScore.generateVulnerabilityScorecards(toolResults, catSet);
    System.out.println("Vulnerability scorecards computed.");

    // Step 7: Update all the menus for all the generated pages to reflect the tools and vulnerability categories
    updateMenus(toolResults, catSet);

    // Step 8: Generate the overall comparison chart for all the tools in this test
    ScatterHome.generateComparisonChart(toolResults, focus);

    // Step 9: Generate the results table across all the tools in this test
    String table = generateOverallStatsTable(toolResults);

    File f = Paths.get(scoreCardDirName + "/" + HOMEFILENAME).toFile();
    try {
        String html = new String(Files.readAllBytes(f.toPath()));
        html = html.replace("${table}", table);
        Files.write(f.toPath(), html.getBytes());
    } catch (IOException e) {
        System.out.println("Error updating results table in: " + f.getName());
        e.printStackTrace();
    }

    System.out.println("Benchmark scorecards complete.");

    System.exit(0);
}

From source file:org.patterson.WebsiteGenerator.java

/**
 * @throws IOException//from w  w w.j  av a2 s  .c o m
 */
private void cleanTargetDir() throws IOException {
    File tempDest = new File(settings.getTargetDir());
    logger.info("Cleaning target dir: " + tempDest.getAbsolutePath());
    if (tempDest.exists()) {
        FileUtils.cleanDirectory(tempDest);
    }
}

From source file:org.pentaho.platform.plugin.services.importer.SolutionImportHandlerNamingIT.java

@Before
public void init() throws IOException, PlatformInitializationException, PlatformImportException,
        DomainIdNullException, DomainAlreadyExistsException, DomainStorageException {
    // repository
    File repoDir = new File(tempDir.getAbsolutePath() + REPO_PATH);
    FileUtils.forceMkdir(repoDir);//w  w w  . ja  va  2 s.  c o  m
    FileUtils.cleanDirectory(repoDir);
    repoRoot = repoDir;
    repo = new FileSystemBackedUnifiedRepository();
    repo = Mockito.spy(repo);
    repo.setRootDir(repoRoot);

    // mimeResolver
    final Converter defaultConverter = new StreamConverter();

    final List<IMimeType> solutionMimeList = java.util.Collections.singletonList(MIME_SOLUTION);
    final List<IMimeType> contentMimeList = java.util.Arrays.asList(new IMimeType[] { MIME_PRPT, MIME_XML });
    final List<IMimeType> allMimeTypes = new ArrayList<IMimeType>(
            solutionMimeList.size() + contentMimeList.size());
    {
        allMimeTypes.addAll(solutionMimeList);
        allMimeTypes.addAll(contentMimeList);
        for (IMimeType mimeType : allMimeTypes) {
            mimeType.setConverter(defaultConverter);
        }
    }

    final IPlatformMimeResolver mimeResolver = new NameBaseMimeResolver();
    for (IMimeType mimeType : allMimeTypes) {
        mimeResolver.addMimeType(mimeType);
    }

    // platform, import handlers
    PentahoSystem.clearObjectFactory();
    microPlatform = new MicroPlatform(getSolutionPath());
    microPlatform.defineInstance(IUnifiedRepository.class, repo);
    microPlatform.defineInstance(IPlatformMimeResolver.class, mimeResolver);
    microPlatform.defineInstance(ISolutionEngine.class, Mockito.mock(SolutionEngine.class));
    microPlatform.defineInstance(IDatasourceMgmtService.class, Mockito.mock(IDatasourceMgmtService.class));

    IRepositoryContentConverterHandler converterHandler = new DefaultRepositoryContentConverterHandler(
            new HashMap<String, Converter>());

    RepositoryFileImportFileHandler contentImportFileHandler = new RepositoryFileImportFileHandler(
            contentMimeList);
    contentImportFileHandler.setRepository(repo);
    solutionImportHandler = new SolutionImportHandler(solutionMimeList);

    List<IPlatformImportHandler> handlers = new ArrayList<IPlatformImportHandler>();
    handlers.add(contentImportFileHandler);
    handlers.add(solutionImportHandler);

    PentahoPlatformImporter importer = new PentahoPlatformImporter(handlers, converterHandler);
    importer.setDefaultHandler(contentImportFileHandler);
    importer.setRepositoryImportLogger(new Log4JRepositoryImportLogger());

    microPlatform.defineInstance(IPlatformImporter.class, importer);

    microPlatform.start();
}

From source file:org.pentaho.platform.plugin.services.importer.SolutionImportHandlerNamingIT.java

@After
public void cleanup() throws PluginBeanException, PlatformInitializationException, IOException {
    microPlatform.stop();
    FileUtils.cleanDirectory(repoRoot);
}

From source file:org.polymap.rhei.batik.app.SvgImageRegistryHelper.java

public SvgImageRegistryHelper(AbstractUIPlugin plugin) {
    super(plugin);
    ConfigurationFactory.inject(this);

    // temp folder
    try {//w  w  w .  j a  va 2 s  .  c  o  m
        tempFolder = new File(plugin.getStateLocation().toFile(), "svg-icons");
        tempFolder.mkdirs();
        FileUtils.cleanDirectory(tempFolder);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    // default configs
    putConfig(NORMAL12, new ReplaceBlackSvgConfiguration(COLOR_NORMAL, 16));
    putConfig(NORMAL24, new ReplaceBlackSvgConfiguration(COLOR_NORMAL, 24));
    putConfig(NORMAL48, new ReplaceBlackSvgConfiguration(COLOR_NORMAL, 48));
    putConfig(ACTION48, new ReplaceBlackSvgConfiguration(COLOR_ACTION, 48));
    putConfig(ACTION24, new ReplaceBlackSvgConfiguration(COLOR_ACTION, 24));
    putConfig(ACTION12, new ReplaceBlackSvgConfiguration(COLOR_ACTION, 16));
    putConfig(OK24, new ReplaceBlackSvgConfiguration(COLOR_OK, 24));
    putConfig(ALERT24, new ReplaceBlackSvgConfiguration(new RGB(0xFF, 0xD2, 0x2C), 24));
    putConfig(ERROR24, new ReplaceBlackSvgConfiguration(COLOR_DANGER, 24));
    putConfig(WHITE24, new ReplaceBlackSvgConfiguration(COLOR_WHITE, 24));
    putConfig(OVR12_ACTION, new ReplaceBlackSvgConfiguration(new RGB(140, 240, 100), 16));
    putConfig(DISABLED24, new ReplaceBlackSvgConfiguration(COLOR_DISABLED, 24));
    putConfig(DISABLED12, new ReplaceBlackSvgConfiguration(COLOR_DISABLED, 16));
}

From source file:org.polymap.rhei.batik.engine.svg.Svg2PngTest.java

@Test
public void testScaleSVG() throws Exception {
    ImageConfiguration imageConfig = new ImageConfiguration();
    imageConfig.setName("default");
    imageConfig.setDepth(ColorDepth.B4);
    imageConfig.setAdjHue(0.3f);/* w  w  w . j  av  a  2 s  .co  m*/
    imageConfig.setAdjSaturation(0.8f);
    imageConfig.setAdjBrightness(0f);
    imageConfig.setColorType(COLOR_TYPE.RGB);

    File pngPath = new File("build/Svg2PngTest");
    pngPath.mkdirs();
    FileUtils.cleanDirectory(pngPath);

    File svgFile = new File(pngPath, EXAMPLE_SVG2);
    FileUtils.copyURLToFile(getClass().getResource(EXAMPLE_SVG2), svgFile);

    svg2Png.transcode(pngPath.getAbsolutePath(), Collections.singletonList(svgFile),
            Collections.singletonList(Scale.P16), Collections.singletonList(imageConfig));

    BufferedImage image = ImageIO
            .read(new File(pngPath + "/default/16/" + EXAMPLE_SVG2.replace(".svg", ".png")));
    Assert.assertNotNull(image);
    Assert.assertEquals(16f, image.getHeight(), 0.5f);
    Assert.assertEquals(16f, image.getWidth(), 0.5f);
    Assert.assertEquals(1, image.getColorModel().getPixelSize());
}