2 * Copyright (c) 2013 Pantheon Technologies s.r.o. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
10 package org.opendaylight.openflowjava.protocol.impl.util;
12 import io.netty.buffer.ByteBuf;
13 import io.netty.buffer.UnpooledByteBufAllocator;
15 import java.util.ArrayList;
16 import java.util.List;
18 import java.util.Map.Entry;
20 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev100924.MacAddress;
21 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader;
23 import com.google.common.base.Joiner;
24 import com.google.common.base.Preconditions;
25 import com.google.common.base.Splitter;
26 import com.google.common.collect.Lists;
27 import com.google.common.primitives.UnsignedBytes;
29 /** Class for common operations on ByteBuf
30 * @author michal.polkorab
31 * @author timotej.kubas
33 public abstract class ByteBufUtils {
34 public static final Splitter DOT_SPLITTER = Splitter.on('.');
35 public static final Joiner DOT_JOINER = Joiner.on(".");
36 public static final Splitter COLON_SPLITTER = Splitter.on(':');
37 public static final Joiner COLON_JOINER = Joiner.on(":");
38 private static final char[] HEX_CHARS = "0123456789ABCDEF".toCharArray();
41 * Converts ByteBuf into String
42 * @param bb input ByteBuf
45 public static String byteBufToHexString(final ByteBuf bb) {
46 StringBuffer sb = new StringBuffer();
47 for (int i = bb.readerIndex(); i < (bb.readerIndex() + bb.readableBytes()); i++) {
48 sb.append(String.format(" %02x", bb.getUnsignedByte(i)));
50 return sb.toString().trim();
54 * Converts String into byte[]
55 * @param hexSrc input String
56 * @return byte[] filled with input data
58 public static byte[] hexStringToBytes(final String hexSrc) {
59 return hexStringToBytes(hexSrc, true);
63 * Converts String into byte[]
64 * @param hexSrc input String
65 * @param withSpaces if there are spaces in string
66 * @return byte[] filled with input data
68 public static byte[] hexStringToBytes(final String hexSrc, final boolean withSpaces ) {
69 String splitPattern = "\\s+";
71 splitPattern = "(?<=\\G.{2})";
73 Iterable<String> tmp = Splitter.onPattern(splitPattern)
74 .omitEmptyStrings().split(hexSrc);
75 ArrayList<String> byteChips = Lists.newArrayList(tmp);
76 byte[] result = new byte[byteChips.size()];
78 for (String chip : byteChips) {
79 result[i] = (byte) Short.parseShort(chip, 16);
86 * Creates ByteBuf filled with specified data
87 * @param hexSrc input String of bytes in hex format
88 * @return ByteBuf with specified hexString converted
90 public static ByteBuf hexStringToByteBuf(final String hexSrc) {
91 ByteBuf out = UnpooledByteBufAllocator.DEFAULT.buffer();
92 hexStringToByteBuf(hexSrc, out);
97 * Creates ByteBuf filled with specified data
98 * @param hexSrc input String of bytes in hex format
99 * @param out ByteBuf with specified hexString converted
101 public static void hexStringToByteBuf(final String hexSrc, final ByteBuf out) {
102 out.writeBytes(hexStringToBytes(hexSrc));
106 * Fills specified ByteBuf with 0 (zeros) of desired length, used for padding
108 * @param out ByteBuf to be padded
109 * @deprecated Use {@link ByteBuf#writeZero(int)} directly.
112 public static void padBuffer(final int length, final ByteBuf out) {
113 out.writeZero(length);
117 * Create standard OF header
118 * @param msgType message code
119 * @param message POJO
120 * @param out writing buffer
121 * @param length ofheader length
123 public static <E extends OfHeader> void writeOFHeader(final byte msgType, final E message, final ByteBuf out, final int length) {
124 out.writeByte(message.getVersion());
125 out.writeByte(msgType);
126 out.writeShort(length);
127 out.writeInt(message.getXid().intValue());
131 * Write length standard OF header
132 * @param out writing buffer
134 public static void updateOFHeaderLength(final ByteBuf out) {
135 out.setShort(EncodeConstants.OFHEADER_LENGTH_INDEX, out.readableBytes());
139 * Fills the bitmask from boolean map where key is bit position
140 * @param booleanMap bit to boolean mapping
143 public static int fillBitMaskFromMap(final Map<Integer, Boolean> booleanMap) {
146 for (Entry<Integer, Boolean> iterator : booleanMap.entrySet()) {
147 if (iterator.getValue() != null && iterator.getValue().booleanValue()) {
148 bitmask |= 1 << iterator.getKey();
155 * Fills the bitmask from a set of bit values, starting at specified offset.
157 * @param offset Bit offset to start at
158 * @param values boolean bit values to fill
159 * @return Filled-in bitmask
161 public static int fillBitMask(final int offset, final boolean... values) {
165 for (boolean v : values) {
176 * Fills the bitmask from boolean list where key is bit position
177 * @param booleanList bit to boolean mapping
180 public static int[] fillBitMaskFromList(final List<Boolean> booleanList) {
184 if ((booleanList.size() % Integer.SIZE) != 0) {
185 bitmask = new int[booleanList.size() / Integer.SIZE + 1];
187 bitmask = new int[booleanList.size() / Integer.SIZE];
189 for (Boolean currElement : booleanList) {
190 if (currElement != null && currElement.booleanValue()) {
191 bitmask[arrayIndex] |= 1 << index;
194 arrayIndex = index / Integer.SIZE;
200 * Converts byte array into String
201 * @param array input byte array
204 public static String bytesToHexString(final byte[] array) {
205 StringBuffer sb = new StringBuffer();
206 for (byte element : array) {
207 sb.append(String.format(" %02x", element));
209 return sb.toString().trim();
212 private static int hexValue(final char c) {
213 if (c >= '0' && c <= '9') {
216 if (c >= 'a' && c <= 'f') {
219 if (c >= 'A' && c <= 'F') {
223 throw new IllegalArgumentException(String.format("Invalid character '%s' encountered", c));
227 * Converts macAddress to byte array
229 * @return byte representation of mac address
230 * @see {@link MacAddress}
232 * FIXME: this method does not support shortened values, e.g.
233 * "0:1:2:3:4:5", only "00:11:22:33:44:55".
235 public static byte[] macAddressToBytes(final String macAddress) {
236 final byte[] result = new byte[EncodeConstants.MAC_ADDRESS_LENGTH];
237 final char[] mac = macAddress.toCharArray();
240 for (int i = 0; i < EncodeConstants.MAC_ADDRESS_LENGTH - 1; ++i) {
241 result[i] = UnsignedBytes.checkedCast(
242 (hexValue(mac[offset++]) << 4) | hexValue(mac[offset++]));
243 Preconditions.checkArgument(mac[offset] == ':', "Invalid value: %s", macAddress);
247 result[EncodeConstants.MAC_ADDRESS_LENGTH - 1] =
248 UnsignedBytes.checkedCast(hexValue(mac[offset++]) << 4 | hexValue(mac[offset]));
252 private static final void appendByte(final StringBuilder sb, final byte b) {
253 final int v = UnsignedBytes.toInt(b);
254 sb.append(HEX_CHARS[v >> 4]);
255 sb.append(HEX_CHARS[v & 15]);
259 * Converts a MAC address represented in bytes to String
261 * @return String representation of a MAC address
262 * @see {@link MacAddress}
264 public static String macAddressToString(final byte[] address) {
265 Preconditions.checkArgument(address.length == EncodeConstants.MAC_ADDRESS_LENGTH);
267 final StringBuilder sb = new StringBuilder(17);
269 appendByte(sb, address[0]);
270 for (int i = 1; i < EncodeConstants.MAC_ADDRESS_LENGTH; i++) {
272 appendByte(sb, address[i]);
275 return sb.toString();
279 * Reads and parses null-terminated string from ByteBuf
281 * @param length maximal length of String
282 * @return String with name of port
284 public static String decodeNullTerminatedString(final ByteBuf rawMessage, final int length) {
285 byte[] name = new byte[length];
286 rawMessage.readBytes(name);
287 return new String(name).trim();