commons-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From ggreg...@apache.org
Subject svn commit: r1637888 - in /commons/proper/codec/trunk/src: changes/changes.xml main/java/org/apache/commons/codec/binary/Hex.java main/java/org/apache/commons/codec/binary/StringUtils.java test/java/org/apache/commons/codec/binary/HexTest.java
Date Mon, 10 Nov 2014 15:29:03 GMT
Author: ggregory
Date: Mon Nov 10 15:29:02 2014
New Revision: 1637888

URL: http://svn.apache.org/r1637888
Log:
[CODEC-194] Support java.nio.ByteBuffer in org.apache.commons.codec.binary.Hex.

Modified:
    commons/proper/codec/trunk/src/changes/changes.xml
    commons/proper/codec/trunk/src/main/java/org/apache/commons/codec/binary/Hex.java
    commons/proper/codec/trunk/src/main/java/org/apache/commons/codec/binary/StringUtils.java
    commons/proper/codec/trunk/src/test/java/org/apache/commons/codec/binary/HexTest.java

Modified: commons/proper/codec/trunk/src/changes/changes.xml
URL: http://svn.apache.org/viewvc/commons/proper/codec/trunk/src/changes/changes.xml?rev=1637888&r1=1637887&r2=1637888&view=diff
==============================================================================
--- commons/proper/codec/trunk/src/changes/changes.xml (original)
+++ commons/proper/codec/trunk/src/changes/changes.xml Mon Nov 10 15:29:02 2014
@@ -43,7 +43,7 @@ The <action> type attribute can be add,u
   </properties>
   <body>
     <release version="1.11" date="DD MM 2014" description="Feature and fix release.">
-      
+      <action dev="ggregory" type="add" issue="CODEC-194">Support java.nio.ByteBuffer
in org.apache.commons.codec.binary.Hex</action>         
     </release>   
     <release version="1.10" date="5 November 2014" description="Feature and fix release.">
       <action dev="ggregory" type="add" issue="CODEC-192" due-to="Thomas Neidhart">Add
Daitch-Mokotoff Soundex</action>   

Modified: commons/proper/codec/trunk/src/main/java/org/apache/commons/codec/binary/Hex.java
URL: http://svn.apache.org/viewvc/commons/proper/codec/trunk/src/main/java/org/apache/commons/codec/binary/Hex.java?rev=1637888&r1=1637887&r2=1637888&view=diff
==============================================================================
--- commons/proper/codec/trunk/src/main/java/org/apache/commons/codec/binary/Hex.java (original)
+++ commons/proper/codec/trunk/src/main/java/org/apache/commons/codec/binary/Hex.java Mon
Nov 10 15:29:02 2014
@@ -17,6 +17,7 @@
 
 package org.apache.commons.codec.binary;
 
+import java.nio.ByteBuffer;
 import java.nio.charset.Charset;
 
 import org.apache.commons.codec.BinaryDecoder;
@@ -110,6 +111,20 @@ public class Hex implements BinaryEncode
     }
 
     /**
+     * Converts a byte buffer into an array of characters representing the hexadecimal values
of each byte in order.
+     * The returned array will be double the length of the passed array, as it takes two
characters to represent any
+     * given byte.
+     *
+     * @param data
+     *            a byte buffer to convert to Hex characters
+     * @return A char[] containing hexadecimal characters
+     * @since 1.11
+     */
+    public static char[] encodeHex(final ByteBuffer data) {
+        return encodeHex(data, true);
+    }
+
+    /**
      * Converts an array of bytes into an array of characters representing the hexadecimal
values of each byte in order.
      * The returned array will be double the length of the passed array, as it takes two
characters to represent any
      * given byte.
@@ -126,6 +141,22 @@ public class Hex implements BinaryEncode
     }
 
     /**
+     * Converts a byte buffer into an array of characters representing the hexadecimal values
of each byte in order.
+     * The returned array will be double the length of the passed array, as it takes two
characters to represent any
+     * given byte.
+     *
+     * @param data
+     *            a byte buffer to convert to Hex characters
+     * @param toLowerCase
+     *            <code>true</code> converts to lowercase, <code>false</code>
to uppercase
+     * @return A char[] containing hexadecimal characters
+     * @since 1.11
+     */
+    public static char[] encodeHex(final ByteBuffer data, final boolean toLowerCase) {
+        return encodeHex(data, toLowerCase ? DIGITS_LOWER : DIGITS_UPPER);
+    }
+
+    /**
      * Converts an array of bytes into an array of characters representing the hexadecimal
values of each byte in order.
      * The returned array will be double the length of the passed array, as it takes two
characters to represent any
      * given byte.
@@ -149,6 +180,22 @@ public class Hex implements BinaryEncode
     }
 
     /**
+     * Converts a byte buffer into an array of characters representing the hexadecimal values
of each byte in order.
+     * The returned array will be double the length of the passed array, as it takes two
characters to represent any
+     * given byte.
+     *
+     * @param data
+     *            a byte buffer to convert to Hex characters
+     * @param toDigits
+     *            the output alphabet
+     * @return A char[] containing hexadecimal characters
+     * @since 1.11
+     */
+    protected static char[] encodeHex(final ByteBuffer data, final char[] toDigits) {
+        return encodeHex(data.array(), toDigits);
+    }
+
+    /**
      * Converts an array of bytes into a String representing the hexadecimal values of each
byte in order. The returned
      * String will be double the length of the passed array, as it takes two characters to
represent any given byte.
      *
@@ -162,6 +209,19 @@ public class Hex implements BinaryEncode
     }
 
     /**
+     * Converts a byte buffer into a String representing the hexadecimal values of each byte
in order. The returned
+     * String will be double the length of the passed array, as it takes two characters to
represent any given byte.
+     *
+     * @param data
+     *            a byte buffer to convert to Hex characters
+     * @return A String containing hexadecimal characters
+     * @since 1.11
+     */
+    public static String encodeHexString(final ByteBuffer data) {
+        return new String(encodeHex(data));
+    }
+
+    /**
      * Converts a hexadecimal character to an integer.
      *
      * @param ch
@@ -233,12 +293,29 @@ public class Hex implements BinaryEncode
     }
 
     /**
+     * Converts a buffer of character bytes representing hexadecimal values into an array
of bytes of those same values.
+     * The returned array will be half the length of the passed array, as it takes two characters
to represent any given
+     * byte. An exception is thrown if the passed char array has an odd number of elements.
+     *
+     * @param buffer
+     *            An array of character bytes containing hexadecimal digits
+     * @return A byte array containing binary data decoded from the supplied byte array (representing
characters).
+     * @throws DecoderException
+     *             Thrown if an odd number of characters is supplied to this function
+     * @see #decodeHex(char[])
+     * @since 1.11
+     */
+    public byte[] decode(final ByteBuffer buffer) throws DecoderException {
+        return decodeHex(new String(buffer.array(), getCharset()).toCharArray());
+    }
+
+    /**
      * Converts a String or an array of character bytes representing hexadecimal values into
an array of bytes of those
      * same values. The returned array will be half the length of the passed String or array,
as it takes two characters
      * to represent any given byte. An exception is thrown if the passed char array has an
odd number of elements.
      *
      * @param object
-     *            A String or, an array of character bytes containing hexadecimal digits
+     *            A String, ByteBuffer, byte[], or an array of character bytes containing
hexadecimal digits
      * @return A byte array containing binary data decoded from the supplied byte array (representing
characters).
      * @throws DecoderException
      *             Thrown if an odd number of characters is supplied to this function or
the object is not a String or
@@ -247,11 +324,18 @@ public class Hex implements BinaryEncode
      */
     @Override
     public Object decode(final Object object) throws DecoderException {
-        try {
-            final char[] charArray = object instanceof String ? ((String) object).toCharArray()
: (char[]) object;
-            return decodeHex(charArray);
-        } catch (final ClassCastException e) {
-            throw new DecoderException(e.getMessage(), e);
+        if (object instanceof String) {
+            return decode(((String) object).toCharArray());
+        } else if (object instanceof byte[]) {
+            return decode((byte[]) object);
+        } else if (object instanceof ByteBuffer) {
+            return decode((ByteBuffer) object);
+        } else {
+            try {
+                return decodeHex((char[]) object);
+            } catch (final ClassCastException e) {
+                throw new DecoderException(e.getMessage(), e);
+            }
         }
     }
 
@@ -276,6 +360,25 @@ public class Hex implements BinaryEncode
     }
 
     /**
+     * Converts byte buffer into an array of bytes for the characters representing the hexadecimal
values of each
+     * byte in order. The returned array will be double the length of the passed array, as
it takes two characters to
+     * represent any given byte.
+     * <p>
+     * The conversion from hexadecimal characters to the returned bytes is performed with
the charset named by
+     * {@link #getCharset()}.
+     * </p>
+     *
+     * @param array
+     *            a byte buffer to convert to Hex characters
+     * @return A byte[] containing the bytes of the hexadecimal characters
+     * @see #encodeHex(byte[])
+     * @since 1.11
+     */
+    public byte[] encode(final ByteBuffer array) {
+        return encodeHexString(array).getBytes(this.getCharset());
+    }
+
+    /**
      * Converts a String or an array of bytes into an array of characters representing the
hexadecimal values of each
      * byte in order. The returned array will be double the length of the passed String or
array, as it takes two
      * characters to represent any given byte.
@@ -285,7 +388,7 @@ public class Hex implements BinaryEncode
      * </p>
      *
      * @param object
-     *            a String, or byte[] to convert to Hex characters
+     *            a String, ByteBuffer, or byte[] to convert to Hex characters
      * @return A char[] containing hexadecimal characters
      * @throws EncoderException
      *             Thrown if the given object is not a String or byte[]
@@ -293,13 +396,19 @@ public class Hex implements BinaryEncode
      */
     @Override
     public Object encode(final Object object) throws EncoderException {
-        try {
-            final byte[] byteArray = object instanceof String ?
-                                   ((String) object).getBytes(this.getCharset()) : (byte[])
object;
-            return encodeHex(byteArray);
-        } catch (final ClassCastException e) {
-            throw new EncoderException(e.getMessage(), e);
+        byte[] byteArray;
+        if (object instanceof String) {
+            byteArray = ((String) object).getBytes(this.getCharset());
+        } else if (object instanceof ByteBuffer) {
+            byteArray = ((ByteBuffer) object).array();
+        } else {
+            try {
+                byteArray = (byte[]) object;
+            } catch (final ClassCastException e) {
+                throw new EncoderException(e.getMessage(), e);
+            }
         }
+        return encodeHex(byteArray);
     }
 
     /**

Modified: commons/proper/codec/trunk/src/main/java/org/apache/commons/codec/binary/StringUtils.java
URL: http://svn.apache.org/viewvc/commons/proper/codec/trunk/src/main/java/org/apache/commons/codec/binary/StringUtils.java?rev=1637888&r1=1637887&r2=1637888&view=diff
==============================================================================
--- commons/proper/codec/trunk/src/main/java/org/apache/commons/codec/binary/StringUtils.java
(original)
+++ commons/proper/codec/trunk/src/main/java/org/apache/commons/codec/binary/StringUtils.java
Mon Nov 10 15:29:02 2014
@@ -18,6 +18,7 @@
 package org.apache.commons.codec.binary;
 
 import java.io.UnsupportedEncodingException;
+import java.nio.ByteBuffer;
 import java.nio.charset.Charset;
 
 import org.apache.commons.codec.CharEncoding;
@@ -97,6 +98,41 @@ public class StringUtils {
     }
 
     /**
+     * Calls {@link String#getBytes(Charset)}
+     *
+     * @param string
+     *            The string to encode (if null, return null).
+     * @param charset
+     *            The {@link Charset} to encode the <code>String</code>
+     * @return the encoded bytes
+     * @since 1.11
+     */
+    private static ByteBuffer getByteBuffer(final String string, final Charset charset) {
+        if (string == null) {
+            return null;
+        }
+        return ByteBuffer.wrap(string.getBytes(charset));
+    }
+
+    /**
+     * Encodes the given string into a byte buffer using the UTF-8 charset, storing the result
into a new byte
+     * array.
+     *
+     * @param string
+     *            the String to encode, may be <code>null</code>
+     * @return encoded bytes, or <code>null</code> if the input string was <code>null</code>
+     * @throws NullPointerException
+     *             Thrown if {@link Charsets#UTF_8} is not initialized, which should never
happen since it is
+     *             required by the Java platform specification.
+     * @see <a href="http://download.oracle.com/javase/6/docs/api/java/nio/charset/Charset.html">Standard
charsets</a>
+     * @see #getBytesUnchecked(String, String)
+     * @since 1.11
+     */
+    public static ByteBuffer getByteBufferUtf8(final String string) {
+        return getByteBuffer(string, Charsets.UTF_8);
+    }
+
+    /**
      * Encodes the given string into a sequence of bytes using the ISO-8859-1 charset, storing
the result into a new
      * byte array.
      *

Modified: commons/proper/codec/trunk/src/test/java/org/apache/commons/codec/binary/HexTest.java
URL: http://svn.apache.org/viewvc/commons/proper/codec/trunk/src/test/java/org/apache/commons/codec/binary/HexTest.java?rev=1637888&r1=1637887&r2=1637888&view=diff
==============================================================================
--- commons/proper/codec/trunk/src/test/java/org/apache/commons/codec/binary/HexTest.java
(original)
+++ commons/proper/codec/trunk/src/test/java/org/apache/commons/codec/binary/HexTest.java
Mon Nov 10 15:29:02 2014
@@ -29,6 +29,7 @@ import java.nio.charset.UnsupportedChars
 import java.util.Arrays;
 import java.util.Random;
 
+import org.apache.commons.codec.Charsets;
 import org.apache.commons.codec.DecoderException;
 import org.apache.commons.codec.EncoderException;
 import org.junit.Assert;
@@ -134,7 +135,8 @@ public class HexTest {
      * @throws UnsupportedEncodingException
      * @throws DecoderException
      */
-    private void testCustomCharset(final String name, final String parent) throws UnsupportedEncodingException,
DecoderException {
+    private void testCustomCharset(final String name, final String parent) throws UnsupportedEncodingException,
+            DecoderException {
         if (charsetSanityCheck(name) == false) {
             return;
         }
@@ -153,8 +155,8 @@ public class HexTest {
         Assert.assertTrue(Arrays.equals(expectedHexStringBytes, actualEncodedBytes));
         // test 2
         String actualStringFromBytes = new String(actualEncodedBytes, name);
-        assertEquals(name + ", expectedHexString=" + expectedHexString + ", actualStringFromBytes="
+ actualStringFromBytes,
-                expectedHexString, actualStringFromBytes);
+        assertEquals(name + ", expectedHexString=" + expectedHexString + ", actualStringFromBytes="
+
+                actualStringFromBytes, expectedHexString, actualStringFromBytes);
         // second test:
         final Hex utf8Codec = new Hex();
         expectedHexString = "48656c6c6f20576f726c64";
@@ -168,7 +170,7 @@ public class HexTest {
         assertEquals(name, sourceString, actualStringFromBytes);
     }
 
-    @Test(expected=UnsupportedCharsetException.class)
+    @Test(expected = UnsupportedCharsetException.class)
     public void testCustomCharsetBadName() {
         new Hex(BAD_ENCODING_NAME);
     }
@@ -204,6 +206,11 @@ public class HexTest {
     }
 
     @Test
+    public void testDecodeByteBufferEmpty() throws DecoderException {
+        assertTrue(Arrays.equals(new byte[0], new Hex().decode(ByteBuffer.allocate(0))));
+    }
+
+    @Test
     public void testDecodeCharArrayEmpty() throws DecoderException {
         assertTrue(Arrays.equals(new byte[0], Hex.decodeHex(new char[0])));
     }
@@ -211,7 +218,19 @@ public class HexTest {
     @Test
     public void testDecodeByteArrayOddCharacters() {
         try {
-            new Hex().decode(new byte[]{65});
+            new Hex().decode(new byte[] { 65 });
+            fail("An exception wasn't thrown when trying to decode an odd number of characters");
+        } catch (final DecoderException e) {
+            // Expected exception
+        }
+    }
+
+    @Test
+    public void testDecodeByteBufferOddCharacters() {
+        ByteBuffer buffer = ByteBuffer.allocate(1);
+        buffer.put((byte) 65);
+        try {
+            new Hex().decode(buffer);
             fail("An exception wasn't thrown when trying to decode an odd number of characters");
         } catch (final DecoderException e) {
             // Expected exception
@@ -221,7 +240,7 @@ public class HexTest {
     @Test
     public void testDecodeClassCastException() {
         try {
-            new Hex().decode(new int[]{65});
+            new Hex().decode(new int[] { 65 });
             fail("An exception wasn't thrown when trying to decode.");
         } catch (final DecoderException e) {
             // Expected exception
@@ -230,17 +249,17 @@ public class HexTest {
 
     @Test
     public void testDecodeHexCharArrayOddCharacters1() {
-        checkDecodeHexCharArrayOddCharacters(new char[]{'A'});
+        checkDecodeHexCharArrayOddCharacters(new char[] { 'A' });
     }
 
     @Test
     public void testDecodeHexCharArrayOddCharacters3() {
-        checkDecodeHexCharArrayOddCharacters(new char[]{'A', 'B', 'C'});
+        checkDecodeHexCharArrayOddCharacters(new char[] { 'A', 'B', 'C' });
     }
 
     @Test
     public void testDecodeHexCharArrayOddCharacters5() {
-        checkDecodeHexCharArrayOddCharacters(new char[]{'A', 'B', 'C', 'D', 'E'});
+        checkDecodeHexCharArrayOddCharacters(new char[] { 'A', 'B', 'C', 'D', 'E' });
     }
 
     @Test
@@ -259,9 +278,19 @@ public class HexTest {
     }
 
     @Test
+    public void testDecodeByteArrayObjectEmpty() throws DecoderException {
+        assertTrue(Arrays.equals(new byte[0], (byte[]) new Hex().decode((Object) new byte[0])));
+    }
+
+    @Test
+    public void testDecodeByteBufferObjectEmpty() throws DecoderException {
+        assertTrue(Arrays.equals(new byte[0], (byte[]) new Hex().decode((Object) ByteBuffer.allocate(0))));
+    }
+
+    @Test
     public void testEncodeClassCastException() {
         try {
-            new Hex().encode(new int[]{65});
+            new Hex().encode(new int[] { 65 });
             fail("An exception wasn't thrown when trying to encode.");
         } catch (final EncoderException e) {
             // Expected exception
@@ -308,6 +337,12 @@ public class HexTest {
     }
 
     @Test
+    public void testEncodeHexByteBufferEmpty() throws EncoderException {
+        assertTrue(Arrays.equals(new char[0], Hex.encodeHex(ByteBuffer.allocate(0))));
+        assertTrue(Arrays.equals(new byte[0], new Hex().encode(ByteBuffer.allocate(0))));
+    }
+
+    @Test
     public void testEncodeHexByteArrayHelloWorldLowerCaseHex() {
         final byte[] b = StringUtils.getBytesUtf8("Hello World");
         final String expected = "48656c6c6f20576f726c64";
@@ -321,6 +356,19 @@ public class HexTest {
     }
 
     @Test
+    public void testEncodeHexByteBufferHelloWorldLowerCaseHex() {
+        final ByteBuffer b = StringUtils.getByteBufferUtf8("Hello World");
+        final String expected = "48656c6c6f20576f726c64";
+        char[] actual;
+        actual = Hex.encodeHex(b);
+        assertEquals(expected, new String(actual));
+        actual = Hex.encodeHex(b, true);
+        assertEquals(expected, new String(actual));
+        actual = Hex.encodeHex(b, false);
+        assertFalse(expected.equals(new String(actual)));
+    }
+
+    @Test
     public void testEncodeHexByteArrayHelloWorldUpperCaseHex() {
         final byte[] b = StringUtils.getBytesUtf8("Hello World");
         final String expected = "48656C6C6F20576F726C64";
@@ -334,17 +382,66 @@ public class HexTest {
     }
 
     @Test
+    public void testEncodeHexByteBufferHelloWorldUpperCaseHex() {
+        final ByteBuffer b = StringUtils.getByteBufferUtf8("Hello World");
+        final String expected = "48656C6C6F20576F726C64";
+        char[] actual;
+        actual = Hex.encodeHex(b);
+        assertFalse(expected.equals(new String(actual)));
+        actual = Hex.encodeHex(b, true);
+        assertFalse(expected.equals(new String(actual)));
+        actual = Hex.encodeHex(b, false);
+        assertTrue(expected.equals(new String(actual)));
+    }
+
+    @Test
     public void testEncodeHexByteArrayZeroes() {
         final char[] c = Hex.encodeHex(new byte[36]);
         assertEquals("000000000000000000000000000000000000000000000000000000000000000000000000",
new String(c));
     }
 
     @Test
+    public void testEncodeHexByteBufferZeroes() {
+        final char[] c = Hex.encodeHex(ByteBuffer.allocate(36));
+        assertEquals("000000000000000000000000000000000000000000000000000000000000000000000000",
new String(c));
+    }
+
+    @Test
     public void testEncodeStringEmpty() throws EncoderException {
         assertTrue(Arrays.equals(new char[0], (char[]) new Hex().encode("")));
     }
 
     @Test
+    public void testGetCharset() throws UnsupportedEncodingException, DecoderException {
+        Assert.assertEquals(Charsets.UTF_8, new Hex(Charsets.UTF_8).getCharset());
+    }
+
+    @Test
+    public void testGetCharsetName() throws UnsupportedEncodingException, DecoderException
{
+        Assert.assertEquals(Charsets.UTF_8.name(), new Hex(Charsets.UTF_8).getCharsetName());
+    }
+
+    @Test
+    public void testEncodeByteArrayEmpty() throws EncoderException {
+        assertTrue(Arrays.equals(new byte[0], new Hex().encode(new byte[0])));
+    }
+
+    @Test
+    public void testEncodeByteArrayObjectEmpty() throws EncoderException {
+        assertTrue(Arrays.equals(new char[0], (char[]) new Hex().encode((Object) new byte[0])));
+    }
+
+    @Test
+    public void testEncodeByteBufferEmpty() throws EncoderException {
+        assertTrue(Arrays.equals(new byte[0], new Hex().encode(ByteBuffer.allocate(0))));
+    }
+
+    @Test
+    public void testEncodeByteBufferObjectEmpty() throws EncoderException {
+        assertTrue(Arrays.equals(new char[0], (char[]) new Hex().encode((Object) ByteBuffer.allocate(0))));
+    }
+
+    @Test
     public void testRequiredCharset() throws UnsupportedEncodingException, DecoderException
{
         testCustomCharset("UTF-8", "testRequiredCharset");
         testCustomCharset("UTF-16", "testRequiredCharset");



Mime
View raw message