From 187c56de86769dd51b9116dbc1032c074f278d15 Mon Sep 17 00:00:00 2001 From: Jim Sellers Date: Mon, 8 Jan 2024 22:19:27 -0500 Subject: [PATCH] for #6374 to delete non-empty directories --- .../owasp/dependencycheck/utils/FileUtils.java | 13 ++++++++----- .../dependencycheck/utils/FileUtilsTest.java | 17 +++++++++++++++++ 2 files changed, 25 insertions(+), 5 deletions(-) diff --git a/utils/src/main/java/org/owasp/dependencycheck/utils/FileUtils.java b/utils/src/main/java/org/owasp/dependencycheck/utils/FileUtils.java index 27a7e435e87..b5ace3b050a 100644 --- a/utils/src/main/java/org/owasp/dependencycheck/utils/FileUtils.java +++ b/utils/src/main/java/org/owasp/dependencycheck/utils/FileUtils.java @@ -25,15 +25,15 @@ import java.io.InputStream; import java.net.URL; import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Comparator; import java.util.UUID; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - import org.apache.commons.io.FilenameUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.SystemUtils; - +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -91,7 +91,10 @@ public static boolean delete(@Nullable File file) { } try { - Files.delete(file.toPath()); + Files.walk(file.toPath()) + .sorted(Comparator.reverseOrder()) + .map(Path::toFile) + .forEach(File::delete); } catch (IOException ex) { LOGGER.trace(ex.getMessage(), ex); LOGGER.debug("Failed to delete file: {} (error message: {}); attempting to delete on exit.", file.getPath(), ex.getMessage()); diff --git a/utils/src/test/java/org/owasp/dependencycheck/utils/FileUtilsTest.java b/utils/src/test/java/org/owasp/dependencycheck/utils/FileUtilsTest.java index f075573b073..fec966af8a2 100644 --- a/utils/src/test/java/org/owasp/dependencycheck/utils/FileUtilsTest.java +++ b/utils/src/test/java/org/owasp/dependencycheck/utils/FileUtilsTest.java @@ -58,4 +58,21 @@ public void testDelete() throws Exception { assertTrue("delete returned a failed status", status); assertFalse("Temporary file exists after attempting deletion", file.exists()); } + + /** + * Test of delete method with a non-empty directory, of class FileUtils. + */ + @Test + public void testDeleteWithSubDirectories() throws Exception { + + File dir = new File(getSettings().getTempDirectory(), "delete-me"); + dir.mkdirs(); + File file = File.createTempFile("tmp", "deleteme", dir); + assertTrue("Unable to create a temporary file " + file.getAbsolutePath(), file.exists()); + + // delete the file + boolean status = FileUtils.delete(dir); + assertTrue("delete returned a failed status", status); + assertFalse("Temporary file exists after attempting deletion", file.exists()); + } }