1 /* Copyright (C)2013 Pantheon Technologies, s.r.o. All rights reserved. */
\r
3 package org.opendaylight.openflowjava.protocol.impl.util;
\r
5 import io.netty.buffer.ByteBuf;
\r
6 import io.netty.buffer.UnpooledByteBufAllocator;
\r
8 import java.util.Map;
\r
9 import java.util.Map.Entry;
\r
11 import org.opendaylight.openflowjava.protocol.impl.serialization.OFSerializer;
\r
12 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader;
\r
14 /** Class for common operations on ByteBuf
\r
16 * @author michal.polkorab
\r
18 public abstract class ByteBufUtils {
\r
21 * Converts ByteBuf into String
\r
22 * @param bb input ByteBuf
\r
25 public static String byteBufToHexString(ByteBuf bb) {
\r
26 StringBuffer sb = new StringBuffer();
\r
27 for (int i = 0; i < bb.readableBytes(); i++) {
\r
28 short b = bb.getUnsignedByte(i);
\r
29 sb.append(String.format("%02x ", b));
\r
31 return sb.toString();
\r
35 * Converts String into byte[]
\r
36 * @param hexSrc input String
\r
37 * @return byte[] filled with input data
\r
39 public static byte[] hexStringToBytes(String hexSrc) {
\r
40 String[] byteChips = hexSrc.split("\\s+");
\r
41 byte[] result = new byte[byteChips.length];
\r
42 for (int i = 0; i < byteChips.length; i++) {
\r
43 result[i] = (byte) Short.parseShort(byteChips[i], 16);
\r
49 * Creates ByteBuf filled with specified data
\r
50 * @param hexSrc input String of bytes in hex format
\r
51 * @return ByteBuf with specified hexString converted
\r
53 public static ByteBuf hexStringToByteBuf(String hexSrc) {
\r
54 ByteBuf out = UnpooledByteBufAllocator.DEFAULT.buffer();
\r
55 hexStringToByteBuf(hexSrc, out);
\r
60 * Creates ByteBuf filled with specified data
\r
61 * @param hexSrc input String of bytes in hex format
\r
62 * @param out ByteBuf with specified hexString converted
\r
64 public static void hexStringToByteBuf(String hexSrc, ByteBuf out) {
\r
65 out.writeBytes(hexStringToBytes(hexSrc));
\r
69 * Fills specified ByteBuf with 0 (zeros) of desired length, used for padding
\r
71 * @param out ByteBuf to be padded
\r
73 public static void padBuffer(int length, ByteBuf out) {
\r
74 for (int i = 0; i < length; i++) {
\r
80 * Create standard OF header
\r
81 * @param factory serialization factory
\r
82 * @param message POJO
\r
83 * @param out writing buffer
\r
85 public static void writeOFHeader(OFSerializer<?> factory, OfHeader message, ByteBuf out) {
\r
86 out.writeByte(message.getVersion());
\r
87 out.writeByte(factory.getMessageType());
\r
88 out.writeShort(factory.computeLength());
\r
89 out.writeInt(message.getXid().intValue());
\r
94 * Fills the bitmask from boolean map where key is bit position
\r
95 * @param booleanMap bit to boolean mapping
\r
98 public static int fillBitMaskFromMap(Map<Integer, Boolean> booleanMap) {
\r
101 for (Entry<Integer, Boolean> iterator : booleanMap.entrySet()) {
\r
102 if (iterator.getValue() != null && iterator.getValue().booleanValue()) {
\r
103 bitmask |= 1 << iterator.getKey();
\r