瀏覽代碼

HADOOP-6224. Add a method to WritableUtils supported a bounded read of an
encoded String. Contributed by Jothi Padmanabhan


git-svn-id: https://svn.apache.org/repos/asf/hadoop/common/trunk@810384 13f79535-47bb-0310-9956-ffa450edef68

Christopher Douglas 16 年之前
父節點
當前提交
9ea11c5fb3
共有 2 個文件被更改,包括 29 次插入1 次删除
  1. 4 1
      CHANGES.txt
  2. 25 0
      src/java/org/apache/hadoop/io/WritableUtils.java

+ 4 - 1
CHANGES.txt

@@ -507,7 +507,10 @@ Trunk (unreleased changes)
 
     HADOOP-6184. Provide an API to dump Configuration in a JSON format.
     (V.V.Chaitanya Krishna via yhemanth)
- 
+
+    HADOOP-6224. Add a method to WritableUtils performing a bounded read of an
+    encoded String. (Jothi Padmanabhan via cdouglas)
+
   OPTIMIZATIONS
 
     HADOOP-5595. NameNode does not need to run a replicator to choose a

+ 25 - 0
src/java/org/apache/hadoop/io/WritableUtils.java

@@ -415,4 +415,29 @@ public final class WritableUtils  {
     }
     return out.getData();
   }
+
+  /**
+   * Read a string, but check it for sanity. The format consists of a vint
+   * followed by the given number of bytes.
+   * @param in the stream to read from
+   * @param maxLength the largest acceptable length of the encoded string
+   * @return the bytes as a string
+   * @throws IOException if reading from the DataInput fails
+   * @throws IllegalArgumentException if the encoded byte size for string 
+             is negative or larger than maxSize. Only the vint is read.
+   */
+  public static String readStringSafely(DataInput in,
+                                        int maxLength
+                                        ) throws IOException, 
+                                                 IllegalArgumentException {
+    int length = readVInt(in);
+    if (length < 0 || length > maxLength) {
+      throw new IllegalArgumentException("Encoded byte size for String was " + length + 
+                                         ", which is outside of 0.." +
+                                         maxLength + " range.");
+    }
+    byte [] bytes = new byte[length];
+    in.readFully(bytes, 0, length);
+    return Text.decode(bytes);
+  }
 }