Browse Source

Merging change r1131330 for HADOOP-7342 from trunk

git-svn-id: https://svn.apache.org/repos/asf/hadoop/common/branches/yahoo-merge@1134074 13f79535-47bb-0310-9956-ffa450edef68
Suresh Srinivas 14 years ago
parent
commit
fa5db9331a

+ 3 - 0
CHANGES.txt

@@ -6,6 +6,9 @@ Trunk (unreleased changes)
 
   NEW FEATURES
 
+    HADOOP-7342. Add an utility API in FileUtil for JDK File.list
+    avoid NPEs on File.list() (Bharath Mundlapudi via mattf)
+
     HADOOP-6994. Api to get delegation token in AbstractFileSystem. (jitendra)
 
     HADOOP-7171. Support UGI in FileContext API. (jitendra)

+ 19 - 0
src/java/org/apache/hadoop/fs/FileUtil.java

@@ -707,4 +707,23 @@ public class FileUtil {
       }
     }
   }
+  
+  /**
+   * A wrapper for {@link File#list()}. This java.io API returns null 
+   * when a dir is not a directory or for any I/O error. Instead of having
+   * null check everywhere File#list() is used, we will add utility API
+   * to get around this problem. For the majority of cases where we prefer 
+   * an IOException to be thrown.
+   * @param dir directory for which listing should be performed
+   * @return list of file names or empty string list
+   * @exception IOException for invalid directory or for a bad disk.
+   */
+  public static String[] list(File dir) throws IOException {
+    String[] fileNames = dir.list();
+    if(fileNames == null) {
+      throw new IOException("Invalid directory or I/O error occurred for dir: "
+                + dir.toString());
+    }
+    return fileNames;
+  }  
 }

+ 28 - 0
src/test/core/org/apache/hadoop/fs/TestFileUtil.java

@@ -117,6 +117,34 @@ public class TestFileUtil {
     }
   }
 
+
+  @Test
+  public void testListAPI() throws IOException {
+    setupDirs();
+    //Test existing files case 
+    String[] files = FileUtil.list(partitioned);
+    Assert.assertEquals("Unexpected number of pre-existing files", 2, files.length);
+
+    //Test existing directory with no files case 
+    File newDir = new File(tmp.getPath(),"test");
+    newDir.mkdir();
+    Assert.assertTrue("Failed to create test dir", newDir.exists());
+    files = FileUtil.list(newDir);
+    Assert.assertEquals("New directory unexpectedly contains files", 0, files.length);
+    newDir.delete();
+    Assert.assertFalse("Failed to delete test dir", newDir.exists());
+    
+    //Test non-existing directory case, this throws 
+    //IOException
+    try {
+      files = FileUtil.list(newDir);
+      Assert.fail("IOException expected on list() for non-existent dir "
+          + newDir.toString());
+    } catch(IOException ioe) {
+      //Expected an IOException
+    }
+  }
+  
   @After
   public void tearDown() throws IOException {
     FileUtil.fullyDelete(del);