@Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { if (!dir.equals(path)) { deleteDirectory(dir.toFile()); } return CONTINUE; } }
void checkWritableDir(String tempPath) { try { File tempFile = File.createTempFile("check", "tmp", new File(tempPath)); deleteQuietly(tempFile); } catch (IOException e) { throw new IllegalStateException(format("Temp directory is not writable: %s", tempPath), e); } }
/** * Cleans a directory recursively. * * @param directory directory to delete * @throws IOException in case deletion is unsuccessful */ public static void cleanDirectory(File directory) throws IOException { requireNonNull(directory, DIRECTORY_CAN_NOT_BE_NULL); if (!directory.exists()) { return; } cleanDirectoryImpl(directory.toPath()); }
@Test public void sizeOf_is_zero_on_empty_files() throws IOException { File file = temporaryFolder.newFile(); assertThat(FileUtils2.sizeOf(file.toPath())).isEqualTo(0); }
@Test public void cleanDirectory_does_nothing_if_argument_does_not_exist() throws IOException { FileUtils2.cleanDirectory(new File("/a/b/ToDoSSS")); }
/** * Deletes a directory recursively. Does not support symbolic link to directories. * * @param directory directory to delete * @throws IOException in case deletion is unsuccessful */ public static void deleteDirectory(File directory) throws IOException { requireNonNull(directory, DIRECTORY_CAN_NOT_BE_NULL); if (!directory.exists()) { return; } Path path = directory.toPath(); if (Files.isSymbolicLink(path)) { throw new IOException(format("Directory '%s' is a symbolic link", directory)); } if (directory.isFile()) { throw new IOException(format("Directory '%s' is a file", directory)); } deleteDirectoryImpl(path); if (directory.exists()) { throw new IOException(format("Unable to delete directory '%s'", directory)); } }
@Test public void sizeOf_sums_sizes_of_all_files_in_directory() throws IOException { File dir = temporaryFolder.newFolder(); File child = new File(dir, "child.txt"); File grandChild1 = new File(dir, "grand/child1.txt"); File grandChild2 = new File(dir, "grand/child2.txt"); FileUtils.write(child, "foo", UTF_8); FileUtils.write(grandChild1, "bar", UTF_8); FileUtils.write(grandChild2, "baz", UTF_8); long childSize = FileUtils2.sizeOf(child.toPath()); assertThat(childSize).isPositive(); long grandChild1Size = FileUtils2.sizeOf(grandChild1.toPath()); assertThat(grandChild1Size).isPositive(); long grandChild2Size = FileUtils2.sizeOf(grandChild2.toPath()); assertThat(grandChild2Size).isPositive(); assertThat(FileUtils2.sizeOf(dir.toPath())) .isEqualTo(childSize + grandChild1Size + grandChild2Size); // sanity check by comparing commons-io assertThat(FileUtils2.sizeOf(dir.toPath())) .isEqualTo(FileUtils.sizeOfDirectory(dir)); }
@Test public void cleanDirectory_throws_NPE_if_file_is_null() throws IOException { expectDirectoryCanNotBeNullNPE(); FileUtils2.cleanDirectory(null); }
@Override public FileVisitResult visitFile(Path filePath, BasicFileAttributes attrs) throws IOException { File file = filePath.toFile(); if (file.isDirectory()) { deleteDirectory(file); } else if (filePath.getFileName().equals(SHAREDMEMORY_FILE)) { return CONTINUE; } else if (!symLink || !filePath.equals(path)) { Files.delete(filePath); } return CONTINUE; }
static Props loadPropsFromCommandLineArgs(String[] args) { if (args.length != 1) { throw new IllegalArgumentException("Only a single command-line argument is accepted " + "(absolute path to configuration file)"); } File propertyFile = new File(args[0]); Properties properties = new Properties(); Reader reader = null; try { reader = new InputStreamReader(new FileInputStream(propertyFile), StandardCharsets.UTF_8); properties.load(reader); } catch (Exception e) { throw new IllegalStateException("Could not read properties from file: " + args[0], e); } finally { IOUtils.closeQuietly(reader); deleteQuietly(propertyFile); } return new Props(properties); } }
@Test public void sizeOf_ignores_size_of_non_regular_files() throws IOException { assumeTrue(SystemUtils.IS_OS_UNIX); File outside = temporaryFolder.newFile(); FileUtils.write(outside, "outside!!!", UTF_8); File dir = temporaryFolder.newFolder(); File child = new File(dir, "child1.txt"); FileUtils.write(child, "inside!!!", UTF_8); File symlink = new File(dir, "child2.txt"); Files.createSymbolicLink(symlink.toPath(), outside.toPath()); assertThat(FileUtils2.sizeOf(dir.toPath())) .isPositive() .isEqualTo(FileUtils2.sizeOf(child.toPath())); }
@Test public void cleanDirectory_removes_directories_and_files_in_target_directory_but_not_target_directory() throws IOException { Path target = temporaryFolder.newFolder().toPath(); Path childFile1 = Files.createFile(target.resolve("file1.txt")); Path childDir1 = Files.createDirectory(target.resolve("subDir1")); Path childFile2 = Files.createFile(childDir1.resolve("file2.txt")); Path childDir2 = Files.createDirectory(childDir1.resolve("subDir2")); assertThat(target).isDirectory(); assertThat(childFile1).isRegularFile(); assertThat(childDir1).isDirectory(); assertThat(childFile2).isRegularFile(); assertThat(childDir2).isDirectory(); // on supporting FileSystem, target will change if directory is recreated Object targetKey = getFileKey(target); FileUtils2.cleanDirectory(target.toFile()); assertThat(target).isDirectory(); assertThat(childFile1).doesNotExist(); assertThat(childDir1).doesNotExist(); assertThat(childFile2).doesNotExist(); assertThat(childDir2).doesNotExist(); assertThat(getFileKey(target)).isEqualTo(targetKey); }
/** * Deletes a file, never throwing an exception. If file is a directory, delete it and all sub-directories. * <p> * The difference between File.delete() and this method are: * <ul> * <li>A directory to be deleted does not have to be empty.</li> * <li>No exceptions are thrown when a file or directory cannot be deleted.</li> * </ul> * * @param file file or directory to delete, can be {@code null} * @return {@code true} if the file or directory was deleted, otherwise {@code false} */ public static boolean deleteQuietly(@Nullable File file) { if (file == null) { return false; } try { if (file.isDirectory()) { deleteDirectory(file); } else { Files.delete(file.toPath()); } return true; } catch (IOException | SecurityException ignored) { return false; } }
@Test public void deleteQuietly_does_not_fail_if_argument_is_null() { FileUtils2.deleteQuietly(null); }
@Test public void sizeOf_throws_IOE_if_path_does_not_exist() throws IOException { Path path = temporaryFolder.newFile().toPath(); Files.delete(path); expectedException.expect(IOException.class); FileUtils2.sizeOf(path); }
@Test public void cleanDirectory_throws_IAE_if_argument_is_a_file() throws IOException { File file = temporaryFolder.newFile(); expectedException.expect(IllegalArgumentException.class); expectedException.expectMessage("'" + file.getAbsolutePath() + "' is not a directory"); FileUtils2.cleanDirectory(file); }
@Test public void deleteDirectory_does_not_fail_if_file_does_not_exist() throws IOException { File file = new File(temporaryFolder.newFolder(), "foo.d"); FileUtils2.deleteDirectory(file); }
@Test public void deleteQuietly_does_not_fail_if_file_does_not_exist() throws IOException { File file = new File(temporaryFolder.newFolder(), "blablabl"); assertThat(file).doesNotExist(); FileUtils2.deleteQuietly(file); }
@Override public void execute(ComputationStep.Context context) { try (DbSession dbSession = dbClient.openSession(false)) { Optional<CeTaskInputDao.DataStream> opt = dbClient.ceTaskInputDao().selectData(dbSession, task.getUuid()); if (opt.isPresent()) { File unzippedDir = tempFolder.newDir(); try (CeTaskInputDao.DataStream reportStream = opt.get(); InputStream zipStream = new BufferedInputStream(reportStream.getInputStream())) { ZipUtils.unzip(zipStream, unzippedDir); } catch (IOException e) { throw new IllegalStateException("Fail to extract report " + task.getUuid() + " from database", e); } reportDirectoryHolder.setDirectory(unzippedDir); if (LOGGER.isDebugEnabled()) { // size is not added to context statistics because computation // can take time. It's enabled only if log level is DEBUG. try { String dirSize = FileUtils.byteCountToDisplaySize(FileUtils2.sizeOf(unzippedDir.toPath())); LOGGER.debug("Analysis report is {} uncompressed", dirSize); } catch (IOException e) { LOGGER.warn("Fail to compute size of directory " + unzippedDir, e); } } } else { throw MessageException.of("Analysis report " + task.getUuid() + " is missing in database"); } } }
@Test public void cleanDirectory_follows_symlink_to_target_directory() throws IOException { assumeTrue(SystemUtils.IS_OS_UNIX); Path target = temporaryFolder.newFolder().toPath(); Path symToDir = Files.createSymbolicLink(temporaryFolder.newFolder().toPath().resolve("sym_to_dir"), target); Path childFile1 = Files.createFile(target.resolve("file1.txt")); Path childDir1 = Files.createDirectory(target.resolve("subDir1")); Path childFile2 = Files.createFile(childDir1.resolve("file2.txt")); Path childDir2 = Files.createDirectory(childDir1.resolve("subDir2")); assertThat(target).isDirectory(); assertThat(symToDir).isSymbolicLink(); assertThat(childFile1).isRegularFile(); assertThat(childDir1).isDirectory(); assertThat(childFile2).isRegularFile(); assertThat(childDir2).isDirectory(); // on supporting FileSystem, target will change if directory is recreated Object targetKey = getFileKey(target); Object symLinkKey = getFileKey(symToDir); FileUtils2.cleanDirectory(symToDir.toFile()); assertThat(target).isDirectory(); assertThat(symToDir).isSymbolicLink(); assertThat(childFile1).doesNotExist(); assertThat(childDir1).doesNotExist(); assertThat(childFile2).doesNotExist(); assertThat(childDir2).doesNotExist(); assertThat(getFileKey(target)).isEqualTo(targetKey); assertThat(getFileKey(symToDir)).isEqualTo(symLinkKey); }