Fix for DIRMINA-1008: refactor fromHexString to be less tolerant
authorJeff MAURY <jeffmaury@apache.org>
Sun, 22 Mar 2015 21:08:44 +0000 (22:08 +0100)
committerJeff MAURY <jeffmaury@apache.org>
Sun, 22 Mar 2015 21:10:25 +0000 (22:10 +0100)
core/src/main/java/org/apache/mina/util/ByteBufferDumper.java
core/src/test/java/org/apache/mina/util/ByteBufferDumperTest.java

index e351a13..25f79e7 100644 (file)
@@ -143,7 +143,10 @@ public class ByteBufferDumper {
         ByteBuffer res = ByteBuffer.allocate(size);
 
         for (int i = 0; i < size; i++) {
-            int b = ((Character.digit(hex.charAt(i * 2), 16) << 4) | (Character.digit(hex.charAt(i * 2 + 1), 16)));
+            int b = Integer.parseInt(hex.substring(i, i + 2), 16);
+            if (Integer.highestOneBit(b) == 128) {
+              b = b - 256;
+            }
             res.put((byte) b);
         }
 
index e319521..00985bd 100644 (file)
@@ -92,4 +92,31 @@ public class ByteBufferDumperTest {
         bb.flip();
         assertEquals("000102FE", ByteBufferDumper.toHex(bb));
     }
+    
+    @Test
+    public void checkFromHexStringEmptyStringReturnsEmptyByteArray() {
+        ByteBuffer buffer = ByteBufferDumper.fromHexString("");
+        assertEquals(0, buffer.remaining());
+    }
+    
+    @Test
+    public void checkFromHexStringNormalStringReturnsByteArray() {
+        ByteBuffer buffer = ByteBufferDumper.fromHexString("ff");
+        assertEquals(1, buffer.remaining());
+        assertEquals(-1, buffer.get());
+    }
+    
+    @Test
+    public void checkFromHexStringNormalStringUppercaseReturnsByteArray() {
+        ByteBuffer buffer = ByteBufferDumper.fromHexString("FF");
+        assertEquals(1, buffer.remaining());
+        assertEquals(-1, buffer.get());
+    }
+    
+    @Test(expected=NumberFormatException.class)
+    public void checkFromHexStringInvalidStringReturnsException() {
+        ByteBuffer buffer = ByteBufferDumper.fromHexString("non-hexastring");
+        assertEquals(1, buffer.remaining());
+        assertEquals(-1, buffer.get());
+    }
 }