Author: ritchiem
Date: Fri Oct  3 02:20:45 2008
New Revision: 701329

URL: http://svn.apache.org/viewvc?rev=701329&view=rev
Log:
QPID-1268 : Added additional deleteDirectory method that behaves like rmdir, 
modified delete to behave like rm. Added further tests for copy and delete. 
Encorporated review feedback from ASkinner.

Modified:
    
incubator/qpid/trunk/qpid/java/broker/src/test/java/org/apache/qpid/server/queue/AMQQueueFactoryTest.java
    
incubator/qpid/trunk/qpid/java/common/src/main/java/org/apache/qpid/util/FileUtils.java
    
incubator/qpid/trunk/qpid/java/common/src/test/java/org/apache/qpid/util/FileUtilsTest.java

Modified: 
incubator/qpid/trunk/qpid/java/broker/src/test/java/org/apache/qpid/server/queue/AMQQueueFactoryTest.java
URL: 
http://svn.apache.org/viewvc/incubator/qpid/trunk/qpid/java/broker/src/test/java/org/apache/qpid/server/queue/AMQQueueFactoryTest.java?rev=701329&r1=701328&r2=701329&view=diff
==============================================================================
--- 
incubator/qpid/trunk/qpid/java/broker/src/test/java/org/apache/qpid/server/queue/AMQQueueFactoryTest.java
 (original)
+++ 
incubator/qpid/trunk/qpid/java/broker/src/test/java/org/apache/qpid/server/queue/AMQQueueFactoryTest.java
 Fri Oct  3 02:20:45 2008
@@ -60,6 +60,8 @@
         {
             AMQQueueFactory.createAMQQueueImpl(new 
AMQShortString("testQueue"), false, new AMQShortString("owner"), false,
                                                _virtualHost, fieldTable);
+
+            //assert you get the right queue back
         }
         catch (AMQException e)
         {
@@ -82,6 +84,7 @@
         {
             AMQQueueFactory.createAMQQueueImpl(new 
AMQShortString("testQueue"), false, new AMQShortString("owner"), false,
                                                virtualHost, null);
+            //assert you get the right queue back
         }
         catch (AMQException e)
         {

Modified: 
incubator/qpid/trunk/qpid/java/common/src/main/java/org/apache/qpid/util/FileUtils.java
URL: 
http://svn.apache.org/viewvc/incubator/qpid/trunk/qpid/java/common/src/main/java/org/apache/qpid/util/FileUtils.java?rev=701329&r1=701328&r2=701329&view=diff
==============================================================================
--- 
incubator/qpid/trunk/qpid/java/common/src/main/java/org/apache/qpid/util/FileUtils.java
 (original)
+++ 
incubator/qpid/trunk/qpid/java/common/src/main/java/org/apache/qpid/util/FileUtils.java
 Fri Oct  3 02:20:45 2008
@@ -196,31 +196,107 @@
     /*
      * Deletes a given file
      */
-     public static void deleteFile(String filePath) throws IOException
+     public static boolean deleteFile(String filePath)
      {
-         delete(new File(filePath), false);
+         return delete(new File(filePath), false);
+     }
+
+    /*
+     * Deletes a given empty directory 
+     */
+     public static boolean deleteDirectory(String directoryPath)
+     {
+         File directory = new File(directoryPath);
+
+         if (directory.isDirectory())
+         {
+           if (directory.listFiles().length == 0)
+           {
+               return delete(directory, true);
+           }
+         }
+
+         return false;
      }
 
      /**
-      * Delete a given file, if a directory is specified and recursive set 
then delete the whole tree
-      * @param filePath the File object to start at
+      * Delete a given file/directory,
+      * A directory will always require the recursive flag to be set.
+      * if a directory is specified and recursive set then delete the whole 
tree
+      * @param file the File object to start at
       * @param recursive boolean to recurse if a directory is specified.
-      * @throws IOException
+      * @return <code>true</code> if and only if the file or directory is
+      *          successfully deleted; <code>false</code> otherwise
       */
-     public static void delete(File filePath, boolean recursive) throws 
IOException
+     public static boolean delete(File file, boolean recursive)
      {
-         if (filePath.isDirectory())
+         boolean success=true;
+
+         if (file.isDirectory())
          {
              if (recursive)
              {
-                 for (File subFile : filePath.listFiles())
-                 {
-                     delete(subFile, true);
+                 for (File subFile : file.listFiles())
+                 {                                     
+                     success = delete(subFile, true) & success ;
                  }
+
+                 return file.delete();
              }
+
+             return false;
          }
 
-         filePath.delete();
+         return success && file.delete();
      }
-    
+
+
+    public static class UnableToCopyException extends Exception
+    {
+        UnableToCopyException(String msg)
+        {
+            super(msg);
+        }
+    }
+
+    public static void copyRecursive(File source, File dst) throws 
FileNotFoundException, UnableToCopyException
+    {
+
+        if (!source.exists())
+        {
+            throw new FileNotFoundException("Unable to copy '" + 
source.toString() + "' as it does not exist.");
+        }
+
+        if (dst.exists() && !dst.isDirectory())
+        {
+            throw new IllegalArgumentException("Unable to copy '" + 
source.toString() + "' to '" + dst + "' a file with same name exists.");
+        }
+
+
+        if (source.isFile())
+        {
+            copy(source, dst);
+        }
+
+        //else we have a source directory
+        if (!dst.isDirectory() && !dst.mkdir())
+        {
+             throw new UnableToCopyException("Unable to create destination 
directory");
+        }
+
+
+        for (File file : source.listFiles())
+        {
+           if (file.isFile())
+           {
+               copy(file, new File(dst.toString() + File.separator + 
file.getName()));
+           }
+           else
+           {
+               copyRecursive(file, new File(dst + File.separator + 
file.getName()));
+           }
+        }
+
+
+    }
 }

Modified: 
incubator/qpid/trunk/qpid/java/common/src/test/java/org/apache/qpid/util/FileUtilsTest.java
URL: 
http://svn.apache.org/viewvc/incubator/qpid/trunk/qpid/java/common/src/test/java/org/apache/qpid/util/FileUtilsTest.java?rev=701329&r1=701328&r2=701329&view=diff
==============================================================================
--- 
incubator/qpid/trunk/qpid/java/common/src/test/java/org/apache/qpid/util/FileUtilsTest.java
 (original)
+++ 
incubator/qpid/trunk/qpid/java/common/src/test/java/org/apache/qpid/util/FileUtilsTest.java
 Fri Oct  3 02:20:45 2008
@@ -24,12 +24,161 @@
 
 import java.io.File;
 import java.io.IOException;
+import java.io.BufferedWriter;
+import java.io.FileWriter;
+import java.io.FileNotFoundException;
 
 public class FileUtilsTest extends TestCase
 {
-    public void testDelete()
+    private static final String COPY = "-Copy";
+    private static final String SUB = "-Sub";
+
+    /**
+     * Additional test for the copy method.
+     * Ensures that the directory count did increase by more than 1 after the 
copy.
+     */
+    public void testCopyFile()
     {
-        File test = new File("FileUtilsTest-testDelete");
+        final String TEST_DATA = 
"FileUtilsTest-testCopy-TestDataTestDataTestDataTestDataTestDataTestData";
+        String fileName = "FileUtilsTest-testCopy";
+        String fileNameCopy = fileName + COPY;
+
+        //Create initial file
+        File test = createTestFile(fileName, TEST_DATA);
+
+        //Check number of files before copy
+        File[] beforeCopyFileList = 
test.getAbsoluteFile().getParentFile().listFiles();
+        int beforeCopy = beforeCopyFileList.length;
+
+        //Perform Copy
+        FileUtils.copy(test, new File(fileNameCopy));
+
+        //Retrieve counts after copy
+        int afterCopy = new 
File(test.getAbsoluteFile().getParent()).listFiles().length;
+
+        int afterCopyFromCopy = new File(new 
File(fileNameCopy).getAbsoluteFile().getParent()).listFiles().length;
+
+        // Validate the copy counts
+        assertEquals("The file listing from the original and the copy differ 
in length.", afterCopy, afterCopyFromCopy);
+        assertEquals("The number of files did not increase.", beforeCopy + 1, 
afterCopy);
+        assertEquals("The number of files did not increase.", beforeCopy + 1, 
afterCopyFromCopy);
+
+        //Validate copy
+        // Load content
+        String copiedFileContent = FileUtils.readFileAsString(fileNameCopy);
+        assertEquals(TEST_DATA, copiedFileContent);
+
+        //Clean up
+        assertTrue("Unable to cleanup", FileUtils.deleteFile(fileNameCopy));
+
+        //Check file list after cleanup
+        File[] afterCleanup = new 
File(test.getAbsoluteFile().getParent()).listFiles();
+        checkFileLists(beforeCopyFileList, afterCleanup);
+
+        //Remove original file
+        assertTrue("Unable to cleanup", test.delete());
+    }
+
+    /**
+     * Create and Copy the following structure:
+     *
+     * testDirectory --+
+     * +-- testSubDirectory --+
+     * +-- testSubFile
+     * +-- File
+     *
+     * to testDirectory-Copy
+     *
+     * Validate that the file count in the copy is correct and contents of the 
copied files is correct.
+     */
+    public void testCopyRecursive()
+    {
+        final String TEST_DATA = 
"FileUtilsTest-testDirectoryCopy-TestDataTestDataTestDataTestDataTestDataTestData";
+        String fileName = "FileUtilsTest-testCopy";
+        String TEST_DIR = "testDirectoryCopy";
+
+        //Create Initial Structure
+        File testDir = new File(TEST_DIR);
+
+        //Check number of files before copy
+        File[] beforeCopyFileList = 
testDir.getAbsoluteFile().getParentFile().listFiles();
+
+        try
+        {
+            //Create Directories
+            assertTrue("Test directory already exists cannot test.", 
!testDir.exists());
+
+            if (!testDir.mkdir())
+            {
+                fail("Unable to make test Directory");
+            }
+
+            File testSubDir = new File(TEST_DIR + File.separator + TEST_DIR + 
SUB);
+            if (!testSubDir.mkdir())
+            {
+                fail("Unable to make test sub Directory");
+            }
+
+            //Create Files
+            createTestFile(testDir.toString() + File.separator + fileName, 
TEST_DATA);
+            createTestFile(testSubDir.toString() + File.separator + fileName + 
SUB, TEST_DATA);
+
+            //Perform Copy
+            File copyDir = new File(testDir.toString() + COPY);
+            try
+            {
+                FileUtils.copyRecursive(testDir, copyDir);
+            }
+            catch (FileNotFoundException e)
+            {
+                fail(e.getMessage());
+            }
+            catch (FileUtils.UnableToCopyException e)
+            {
+                fail(e.getMessage());
+            }
+
+            //Validate Copy
+            assertEquals("Copied directory should only have one file and one 
directory in it.", 2, copyDir.listFiles().length);
+
+            //Validate Copy File Contents
+            String copiedFileContent = 
FileUtils.readFileAsString(copyDir.toString() + File.separator + fileName);
+            assertEquals(TEST_DATA, copiedFileContent);
+
+            //Validate Name of Sub Directory
+            assertTrue("Expected subdirectory is not a directory", new 
File(copyDir.toString() + File.separator + TEST_DIR + SUB).isDirectory());
+
+            //Assert that it contains only one item
+            assertEquals("Copied sub directory should only have one directory 
in it.", 1, new File(copyDir.toString() + File.separator + TEST_DIR + 
SUB).listFiles().length);
+
+            //Validate content of Sub file
+            copiedFileContent = FileUtils.readFileAsString(copyDir.toString() 
+ File.separator + TEST_DIR + SUB + File.separator + fileName + SUB);
+            assertEquals(TEST_DATA, copiedFileContent);
+        }
+        finally
+        {
+            //Clean up source and copy directory.
+            assertTrue("Unable to cleanup", FileUtils.delete(testDir, true));
+            assertTrue("Unable to cleanup", FileUtils.delete(new File(TEST_DIR 
+ COPY), true));
+
+            //Check file list after cleanup
+            File[] afterCleanup = new 
File(testDir.getAbsoluteFile().getParent()).listFiles();
+            checkFileLists(beforeCopyFileList, afterCleanup);
+        }
+    }
+
+    /**
+     * Helper method to create a test file with a string content
+     *
+     * @param fileName  The fileName to use in the creation
+     * @param test_data The data to store in the file
+     *
+     * @return The File reference
+     */
+    private File createTestFile(String fileName, String test_data)
+    {
+        File test = new File(fileName);
+
         try
         {
             test.createNewFile();
@@ -39,64 +188,264 @@
             fail(e.getMessage());
         }
 
-        assertTrue("File does not exists", test.exists());
-        assertTrue("File is not a file", test.isFile());
+        BufferedWriter writer = null;
+        try
+        {
+            writer = new BufferedWriter(new FileWriter(test));
+            try
+            {
+                writer.write(test_data);
+            }
+            catch (IOException e)
+            {
+                fail(e.getMessage());
+            }
+        }
+        catch (IOException e)
+        {
+            fail(e.getMessage());
+        }
+        finally
+        {
+            try
+            {
+                if (writer != null)
+                {
+                    writer.close();
+                }
+            }
+            catch (IOException e)
+            {
+                fail(e.getMessage());
+            }
+        }
+
+        return test;
+    }
+
+    /**
+     * Test that deleteFile only deletes the specified file
+     */
+    public void testDeleteFile()
+    {
+        File test = new File("FileUtilsTest-testDelete");
+        //Record file count in parent directory to check it is not changed by 
delete
+        String path = test.getAbsolutePath();
+        File[] filesBefore = new File(path.substring(0, 
path.lastIndexOf(File.separator))).listFiles();
+        int fileCountBefore = filesBefore.length;
 
         try
         {
-            FileUtils.deleteFile("FileUtilsTest-testDelete");
+            test.createNewFile();
         }
         catch (IOException e)
         {
             fail(e.getMessage());
         }
 
+        assertTrue("File does not exists", test.exists());
+        assertTrue("File is not a file", test.isFile());
+
+        //Check that file creation can be seen on disk
+        int fileCountCreated =new File(path.substring(0, 
path.lastIndexOf(File.separator))).listFiles().length;
+        assertEquals("File creation was no registered", fileCountBefore + 1, 
fileCountCreated);
+
+        //Perform Delete
+        assertTrue("Unable to cleanup", 
FileUtils.deleteFile("FileUtilsTest-testDelete"));
+
         assertTrue("File exists after delete", !test.exists());
+
+        //Check that after deletion the file count is now accurate
+        File[] filesAfter = new File(path.substring(0, 
path.lastIndexOf(File.separator))).listFiles();
+        int fileCountAfter = filesAfter.length;
+        assertEquals("File creation was no registered", fileCountBefore, 
fileCountAfter);
+
+        checkFileLists(filesBefore, filesAfter);
     }
 
-    public void testRecursiveDelete()
+    /**
+     * Given two lists of File arrays ensure they are the same length and all 
entries in Before are in After
+     * @param filesBefore File[]
+     * @param filesAfter File[] 
+     */
+    private void checkFileLists(File[] filesBefore, File[] filesAfter)
+    {
+        assertEquals("File lists are unequal", filesBefore.length, 
filesAfter.length);
+
+        for (File fileBefore : filesBefore)
+        {
+            boolean found = false;
+
+            for (File fileAfter : filesAfter)
+            {
+                if 
(fileBefore.getAbsolutePath().equals(fileAfter.getAbsolutePath()))
+                {
+                    found = true;
+                    break;
+                }
+            }
+
+            assertTrue("File'" + fileBefore.getName() + "' was not in 
directory afterwards", found);
+        }
+    }
+
+    public void testNonRecursiveNonEmptyDirectoryDeleteFails()
     {
         String directoryName = "FileUtilsTest-testRecursiveDelete";
         File test = new File(directoryName);
 
+        //Record file count in parent directory to check it is not changed by 
delete
+        String path = test.getAbsolutePath();
+        File[] filesBefore = new File(path.substring(0, 
path.lastIndexOf(File.separator))).listFiles();
+        int fileCountBefore = filesBefore.length;
+        
         assertTrue("Directory exists", !test.exists());
 
         test.mkdir();
 
-        createSubDir(directoryName, 2, 4);
-
+        //Create a file in the directory
+        String fileName = test.getAbsolutePath() + File.separatorChar + 
"testFile";
+        File subFile = new File(fileName);
         try
         {
-            FileUtils.deleteFile("FileUtilsTest-testDelete");
+            subFile.createNewFile();
         }
         catch (IOException e)
         {
             fail(e.getMessage());
         }
 
-        assertTrue("File does not exist after file delete", test.exists());
+        //Try and delete the non-empty directory
+        assertFalse("Non Empty Directory was successfully deleted.", 
FileUtils.deleteDirectory(directoryName));
+
+        //Check directory is still there
+        assertTrue("Directory was deleted.", test.exists());
+
+
+        // Clean up
+        assertTrue("Unable to cleanup", FileUtils.delete(test, true));
+
+        //Check that after deletion the file count is now accurate
+        File[] filesAfter = new File(path.substring(0, 
path.lastIndexOf(File.separator))).listFiles();
+        int fileCountAfter = filesAfter.length;
+        assertEquals("File creation was no registered", fileCountBefore, 
fileCountAfter);
+
+        checkFileLists(filesBefore, filesAfter);
+    }
+
+    /**
+     * Test that an empty directory can be deleted with deleteDirectory
+     */
+    public void testEmptyDirectoryDelete()
+    {
+        String directoryName = "FileUtilsTest-testRecursiveDelete";
+        File test = new File(directoryName);
+
+        //Record file count in parent directory to check it is not changed by 
delete
+        String path = test.getAbsolutePath();
+        File[] filesBefore = new File(path.substring(0, 
path.lastIndexOf(File.separator))).listFiles();
+        int fileCountBefore = filesBefore.length;
+
+        assertTrue("Directory exists", !test.exists());
+
+        test.mkdir();
+
+        //Try and delete the empty directory
+        assertTrue("Non Empty Directory was successfully deleted.", 
FileUtils.deleteDirectory(directoryName));
+
+        //Check directory is still there
+        assertTrue("Directory was deleted.", !test.exists());
+
+        //Check that after deletion the file count is now accurate
+        File[] filesAfter = new File(path.substring(0, 
path.lastIndexOf(File.separator))).listFiles();
+        int fileCountAfter = filesAfter.length;
+        assertEquals("File creation was no registered", fileCountBefore, 
fileCountAfter);
+
+        checkFileLists(filesBefore, filesAfter);
+
+    }
+
+    /**
+     * Test that deleteDirectory on a non empty directory to complete 
+     */
+    public void testNonEmptyDirectoryDelete()
+    {
+        String directoryName = "FileUtilsTest-testRecursiveDelete";
+        File test = new File(directoryName);
+
+        assertTrue("Directory exists", !test.exists());
 
+        //Record file count in parent directory to check it is not changed by 
delete
+        String path = test.getAbsolutePath();
+        File[] filesBefore = new File(path.substring(0, 
path.lastIndexOf(File.separator))).listFiles();
+        int fileCountBefore = filesBefore.length;
+
+        test.mkdir();
+
+        //Create a file in the directory
+        String fileName = test.getAbsolutePath() + File.separatorChar + 
"testFile";
+        File subFile = new File(fileName);
         try
         {
-            FileUtils.delete(test, false);
+            subFile.createNewFile();
         }
         catch (IOException e)
         {
             fail(e.getMessage());
         }
-        
+
+        //Try and delete the non-empty directory non-recursively
+        assertFalse("Non Empty Directory was successfully deleted.", 
FileUtils.delete(test, false));
+
+        //Check directory is still there
+        assertTrue("Directory was deleted.", test.exists());
+
+        // Clean up
+        assertTrue("Unable to cleanup", FileUtils.delete(test, true));
+
+        //Check that after deletion the file count is now accurate
+        File[] filesAfter = new File(path.substring(0, 
path.lastIndexOf(File.separator))).listFiles();
+        int fileCountAfter = filesAfter.length;
+        assertEquals("File creation was no registered", fileCountBefore, 
fileCountAfter);
+
+        checkFileLists(filesBefore, filesAfter);
+
+    }
+
+    /**
+     * Test that a recursive delete successeds
+     */
+    public void testRecursiveDelete()
+    {
+        String directoryName = "FileUtilsTest-testRecursiveDelete";
+        File test = new File(directoryName);
+
+        assertTrue("Directory exists", !test.exists());
+
+        //Record file count in parent directory to check it is not changed by 
delete
+        String path = test.getAbsolutePath();
+        File[] filesBefore = new File(path.substring(0, 
path.lastIndexOf(File.separator))).listFiles();
+        int fileCountBefore = filesBefore.length;
+
+        test.mkdir();
+
+        createSubDir(directoryName, 2, 4);
+
+        assertFalse("Non recursive delete was able to directory", 
FileUtils.delete(test, false));
+
         assertTrue("File does not exist after non recursive delete", 
test.exists());
 
-        try
-        {
-            FileUtils.delete(test, true);
-        }
-        catch (IOException e)
-        {
-            fail(e.getMessage());
-        }
+        assertTrue("Unable to cleanup", FileUtils.delete(test, true));
+
         assertTrue("File  exist after recursive delete", !test.exists());
 
+        //Check that after deletion the file count is now accurate
+        File[] filesAfter = new File(path.substring(0, 
path.lastIndexOf(File.separator))).listFiles();
+        int fileCountAfter = filesAfter.length;
+        assertEquals("File creation was no registered", fileCountBefore, 
fileCountAfter);
+
+        checkFileLists(filesBefore, filesAfter);
+
     }
 
     private void createSubDir(String path, int directories, int files)


Reply via email to