From 7263b1167264b959c09253a5229a1cef36be6176 Mon Sep 17 00:00:00 2001 From: jeb228 Date: Thu, 5 Aug 2010 15:35:50 +0000 Subject: [PATCH] NIHVIVO-813 the file storage system will delete any parent directories that become empty as a result of deleting a file. --- .../filestorage/backend/FileStorageImpl.java | 50 +++++++++++++++++++ 1 file changed, 50 insertions(+) diff --git a/webapp/src/edu/cornell/mannlib/vitro/webapp/filestorage/backend/FileStorageImpl.java b/webapp/src/edu/cornell/mannlib/vitro/webapp/filestorage/backend/FileStorageImpl.java index 02e389428..b1dc35e35 100644 --- a/webapp/src/edu/cornell/mannlib/vitro/webapp/filestorage/backend/FileStorageImpl.java +++ b/webapp/src/edu/cornell/mannlib/vitro/webapp/filestorage/backend/FileStorageImpl.java @@ -285,6 +285,11 @@ public class FileStorageImpl implements FileStorage { /** * {@inheritDoc} + * + *

+ * If deleting this file leaves its parent directory empty, that directory + * will be deleted. This repeats, up to (but not including) the root + * directory. */ @Override public boolean deleteFile(String id) throws IOException { @@ -302,9 +307,54 @@ public class FileStorageImpl implements FileStorage { + "', file location '" + file + "'"); } + deleteEmptyParents(file); + return true; } + /** + * We have deleted this file. If the parent directory is now empty, delete + * it. Then check its parent in turn. This continues until we find a parent + * that we will not delete, either because it is not empty, or because it is + * the file storage root. + */ + private void deleteEmptyParents(File file) { + File parent = file.getParentFile(); + if (parent == null) { + log.warn("This is crazy. How can file '" + file.getAbsolutePath() + + "' have no parent?"); + return; + } + + if (parent.equals(rootDir)) { + log.trace("Not deleting the root directory."); + return; + } + + File[] children = parent.listFiles(); + if (children == null) { + log.warn("This is crazy. How can file '" + parent.getAbsolutePath() + + "' not be a directory?"); + return; + } + + if (children.length > 0) { + log.trace("Directory '" + parent.getAbsolutePath() + + "' is not empty. Not deleting."); + return; + } + + log.trace("Deleting empty directory '" + parent.getAbsolutePath() + "'"); + parent.delete(); + if (parent.exists()) { + log.warn("Failed to delete directory '" + parent.getAbsolutePath() + + "'"); + return; + } + + deleteEmptyParents(parent); + } + /** * {@inheritDoc} *