Bug 6337: Add ByteBuf->String utility 92/43492/3
authorMilos Fabian <milfabia@cisco.com>
Tue, 9 Aug 2016 09:44:36 +0000 (11:44 +0200)
committerRobert Varga <nite@hq.sk>
Fri, 12 Aug 2016 12:35:54 +0000 (12:35 +0000)
New utility function convers input ByteBuf to byte array,
encode it with Base64 and convert to string.
The function can be useful when converting NLRI-based
route key to string representation.

Change-Id: I2adbb98da0d0841a2c4eafed841c457e05367c2e
Signed-off-by: Milos Fabian <milfabia@cisco.com>
util/src/main/java/org/opendaylight/protocol/util/ByteArray.java
util/src/test/java/org/opendaylight/protocol/util/ByteArrayTest.java

index 10f7f2424130e355ad36e7b4f064a4747390a720..aa84f6abe4a4d38690f0654043bf035882cad0c1 100644 (file)
@@ -8,6 +8,7 @@
 package org.opendaylight.protocol.util;
 
 import com.google.common.base.Preconditions;
+import com.google.common.io.BaseEncoding;
 import io.netty.buffer.ByteBuf;
 import java.io.File;
 import java.io.FileInputStream;
@@ -283,4 +284,14 @@ public final class ByteArray {
             return Arrays.toString(bytes);
         }
     }
+
+    /**
+     * Encode input ByteBuf with Base64 to string format.
+     *
+     * @param buffer Input ByteBuf
+     * @return String representation of encoded ByteBuf.
+     */
+    public static String encodeBase64(final ByteBuf buffer) {
+        return BaseEncoding.base64().encode(ByteArray.readAllBytes(buffer));
+    }
 }
index 0cea42d6823c8f933664aeeecd944af62eab8c01..4d017905f8f60089a3f92cc8568257edb7c0d7a0 100644 (file)
@@ -281,4 +281,10 @@ public class ByteArrayTest {
         }
     }
 
+    @Test
+    public void testEncodeBase64() {
+        final String result = ByteArray.encodeBase64(Unpooled.wrappedBuffer("abc123".getBytes()));
+        assertEquals("YWJjMTIz", result);
+    }
+
 }