3f5e360005dccb1699ecd43f15a70909a29e7817
[openflowjava.git] / openflow-protocol-impl / src / main / java / org / opendaylight / openflowjava / protocol / impl / util / ByteBufUtils.java
1 /* Copyright (C)2013 Pantheon Technologies, s.r.o. All rights reserved. */\r
2 \r
3 package org.opendaylight.openflowjava.protocol.impl.util;\r
4 \r
5 import io.netty.buffer.ByteBuf;\r
6 import io.netty.buffer.UnpooledByteBufAllocator;\r
7 \r
8 /** Class for common operations on ByteBuf\r
9  *\r
10  * @author michal.polkorab\r
11  */\r
12 public abstract class ByteBufUtils {\r
13 \r
14     /**\r
15      * Converts ByteBuf into String\r
16      * @param bb input ByteBuf\r
17      * @return String\r
18      */\r
19     public static String byteBufToHexString(ByteBuf bb) {\r
20         StringBuffer sb = new StringBuffer();\r
21         for (int i = 0; i < bb.readableBytes(); i++) {\r
22             short b = bb.getUnsignedByte(i);\r
23             sb.append(String.format("%02x ", b));\r
24         }\r
25         return sb.toString();\r
26     }\r
27     \r
28     /**\r
29      * Converts String into byte[]\r
30      * @param hexSrc input String\r
31      * @return byte[] filled with input data\r
32      */\r
33     public static byte[] hexStringToBytes(String hexSrc) {\r
34         String[] byteChips = hexSrc.split("\\s+");\r
35         byte[] result = new byte[byteChips.length];\r
36         for (int i = 0; i < byteChips.length; i++) {\r
37             result[i] = (byte) Short.parseShort(byteChips[i], 16);\r
38         }\r
39         return result;\r
40     }\r
41     \r
42     /**\r
43      * Creates ByteBuf filled with specified data\r
44      * @param hexSrc input String of bytes in hex format\r
45      * @return ByteBuf with specified hexString converted\r
46      */\r
47     public static ByteBuf hexStringToByteBuf(String hexSrc) {\r
48         ByteBuf out = UnpooledByteBufAllocator.DEFAULT.buffer();\r
49         hexStringToByteBuf(hexSrc, out);\r
50         return out;\r
51     }\r
52     \r
53     /**\r
54      * Creates ByteBuf filled with specified data\r
55      * @param hexSrc input String of bytes in hex format\r
56      * @param out ByteBuf with specified hexString converted\r
57      */\r
58     public static void hexStringToByteBuf(String hexSrc, ByteBuf out) {\r
59         out.writeBytes(hexStringToBytes(hexSrc));\r
60     }\r
61     \r
62     /**\r
63      * Fills specified ByteBuf with 0 (zeros) of desired length, used for padding\r
64      * @param length\r
65      * @param out ByteBuf to be padded\r
66      */\r
67     public static void padBuffer(int length, ByteBuf out) {\r
68         for (int i = 0; i < length; i++) {\r
69             out.writeByte(0);\r
70         }\r
71     }\r
72 }\r