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.util;
12 import com.google.common.base.Preconditions;
13 import com.google.common.base.Splitter;
14 import com.google.common.collect.Lists;
15 import com.google.common.primitives.UnsignedBytes;
16 import io.netty.buffer.ByteBuf;
17 import io.netty.buffer.UnpooledByteBufAllocator;
19 import java.io.ByteArrayOutputStream;
20 import java.io.IOException;
21 import java.io.ObjectOutputStream;
22 import java.util.List;
24 import java.util.Map.Entry;
25 import org.opendaylight.openflowjava.protocol.api.util.EncodeConstants;
26 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IetfInetUtil;
27 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv4Address;
28 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv6Address;
29 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.IetfYangUtil;
30 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.MacAddress;
31 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader;
33 /** Class for common operations on ByteBuf
34 * @author michal.polkorab
35 * @author timotej.kubas
37 public abstract class ByteBufUtils {
38 public static final Splitter DOT_SPLITTER = Splitter.on('.');
39 public static final Splitter COLON_SPLITTER = Splitter.on(':');
40 private static final char[] HEX_CHARS = "0123456789ABCDEF".toCharArray();
41 private static final Splitter HEXSTRING_SPLITTER = Splitter.onPattern("\\s+").omitEmptyStrings();
42 private static final Splitter HEXSTRING_NOSPACE_SPLITTER = Splitter.onPattern("(?<=\\G.{2})").omitEmptyStrings();
44 private ByteBufUtils() {
49 * Converts ByteBuf into String
50 * @param bb input ByteBuf
53 public static String byteBufToHexString(final ByteBuf bb) {
54 StringBuilder sb = new StringBuilder();
55 for (int i = bb.readerIndex(); i < (bb.readerIndex() + bb.readableBytes()); i++) {
56 sb.append(String.format(" %02x", bb.getUnsignedByte(i)));
58 return sb.toString().trim();
62 * Converts String into byte[]
63 * @param hexSrc input String
64 * @return byte[] filled with input data
66 public static byte[] hexStringToBytes(final String hexSrc) {
67 return hexStringToBytes(hexSrc, true);
71 * Converts String into byte[]
72 * @param hexSrc input String
73 * @param withSpaces if there are spaces in string
74 * @return byte[] filled with input data
76 public static byte[] hexStringToBytes(final String hexSrc, final boolean withSpaces) {
77 final Splitter splitter = withSpaces ? HEXSTRING_SPLITTER : HEXSTRING_NOSPACE_SPLITTER;
78 List<String> byteChips = Lists.newArrayList(splitter.split(hexSrc));
79 byte[] result = new byte[byteChips.size()];
81 for (String chip : byteChips) {
82 result[i] = (byte) Short.parseShort(chip, 16);
89 * Creates ByteBuf filled with specified data
90 * @param hexSrc input String of bytes in hex format
91 * @return ByteBuf with specified hexString converted
93 public static ByteBuf hexStringToByteBuf(final String hexSrc) {
94 ByteBuf out = UnpooledByteBufAllocator.DEFAULT.buffer();
95 hexStringToByteBuf(hexSrc, out);
100 * Creates ByteBuf filled with specified data
101 * @param hexSrc input String of bytes in hex format
102 * @param out ByteBuf with specified hexString converted
104 public static void hexStringToByteBuf(final String hexSrc, final ByteBuf out) {
105 out.writeBytes(hexStringToBytes(hexSrc));
109 * Fills specified ByteBuf with 0 (zeros) of desired length, used for padding
111 * @param out ByteBuf to be padded
112 * @deprecated Use {@link ByteBuf#writeZero(int)} directly.
115 public static void padBuffer(final int length, final ByteBuf out) {
116 out.writeZero(length);
120 * Create standard OF header
121 * @param msgType message code
122 * @param message POJO
123 * @param out writing buffer
124 * @param length ofheader length
126 public static <E extends OfHeader> void writeOFHeader(final byte msgType, final E message, final ByteBuf out, final int length) {
127 out.writeByte(message.getVersion());
128 out.writeByte(msgType);
129 out.writeShort(length);
130 out.writeInt(message.getXid().intValue());
134 * Write length standard OF header
135 * @param out writing buffer
137 public static void updateOFHeaderLength(final ByteBuf out) {
138 out.setShort(EncodeConstants.OFHEADER_LENGTH_INDEX, out.readableBytes());
142 * Fills the bitmask from boolean map where key is bit position
143 * @param booleanMap bit to boolean mapping
146 public static int fillBitMaskFromMap(final Map<Integer, Boolean> booleanMap) {
149 for (Entry<Integer, Boolean> iterator : booleanMap.entrySet()) {
150 if (iterator.getValue() != null && iterator.getValue().booleanValue()) {
151 bitmask |= 1 << iterator.getKey();
158 * Fills the bitmask from a set of bit values, starting at specified offset.
160 * @param offset Bit offset to start at
161 * @param values boolean bit values to fill
162 * @return Filled-in bitmask
164 public static int fillBitMask(final int offset, final boolean... values) {
168 for (boolean v : values) {
179 * Fills the bitmask from boolean list where key is bit position
180 * @param booleanList bit to boolean mapping
183 public static int[] fillBitMaskFromList(final List<Boolean> booleanList) {
187 if ((booleanList.size() % Integer.SIZE) != 0) {
188 bitmask = new int[booleanList.size() / Integer.SIZE + 1];
190 bitmask = new int[booleanList.size() / Integer.SIZE];
192 for (Boolean currElement : booleanList) {
193 if (currElement != null && currElement.booleanValue()) {
194 bitmask[arrayIndex] |= 1 << index;
197 arrayIndex = index / Integer.SIZE;
203 * Converts byte array into String
204 * @param array input byte array
207 public static String bytesToHexString(final byte[] array) {
208 StringBuilder sb = new StringBuilder();
209 for (byte element : array) {
210 sb.append(String.format(" %02x", element));
212 return sb.toString().trim();
215 private static int hexValue(final char c) {
216 if (c >= '0' && c <= '9') {
219 if (c >= 'a' && c <= 'f') {
222 if (c >= 'A' && c <= 'F') {
226 throw new IllegalArgumentException(String.format("Invalid character '%s' encountered", c));
230 * Converts macAddress to byte array.
231 * See also {@link org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.MacAddress}.
234 * @return byte representation of mac address
236 public static byte[] macAddressToBytes(final String macAddress) {
237 final byte[] result = new byte[EncodeConstants.MAC_ADDRESS_LENGTH];
238 final char[] mac = macAddress.toCharArray();
242 for (int i = 0; i < EncodeConstants.MAC_ADDRESS_LENGTH - 1; ++i) {
243 if (mac[offset + EncodeConstants.SIZE_OF_BYTE_IN_BYTES] == ':') {
244 result[i] = UnsignedBytes.checkedCast(hexValue(mac[offset]));
247 result[i] = UnsignedBytes.checkedCast(
248 (hexValue(mac[offset]) << 4) | hexValue(mac[offset +1]));
251 Preconditions.checkArgument(mac[offset] == ':', "Invalid value: %s", macAddress);
255 if (offset == (mac.length - 1)) {
256 result[EncodeConstants.MAC_ADDRESS_LENGTH - 1] = UnsignedBytes.checkedCast(hexValue(mac[offset]));
258 result[EncodeConstants.MAC_ADDRESS_LENGTH - 1] =
259 UnsignedBytes.checkedCast(hexValue(mac[offset]) << 4 | hexValue(mac[offset +1]));
262 if (offset != (mac.length -1)) {
263 throw new IllegalArgumentException("Incorrect MAC address length");
265 } catch (Exception e) {
266 throw new IllegalArgumentException("Unable to serialize MAC address for input: " + macAddress
272 private static final void appendHexByte(final StringBuilder sb, final byte b) {
273 final int v = UnsignedBytes.toInt(b);
274 sb.append(HEX_CHARS[v >>> 4]);
275 sb.append(HEX_CHARS[v & 15]);
278 private static void appendHexUnsignedShort(final StringBuilder sb, final int val) {
279 sb.append(ByteBufUtils.HEX_CHARS[(val >>> 12) & 15]);
280 sb.append(ByteBufUtils.HEX_CHARS[(val >>> 8) & 15]);
281 sb.append(ByteBufUtils.HEX_CHARS[(val >>> 4) & 15]);
282 sb.append(ByteBufUtils.HEX_CHARS[ val & 15]);
286 * Converts a MAC address represented in bytes to String.
287 * See also {@link org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.MacAddress}.
290 * @return String representation of a MAC address
292 public static String macAddressToString(final byte[] address) {
293 Preconditions.checkArgument(address.length == EncodeConstants.MAC_ADDRESS_LENGTH);
295 final StringBuilder sb = new StringBuilder(17);
297 appendHexByte(sb, address[0]);
298 for (int i = 1; i < EncodeConstants.MAC_ADDRESS_LENGTH; i++) {
300 appendHexByte(sb, address[i]);
303 return sb.toString();
307 * Reads and parses null-terminated string from ByteBuf
309 * @param length maximal length of String
310 * @return String with name of port
312 public static String decodeNullTerminatedString(final ByteBuf rawMessage, final int length) {
313 byte[] name = new byte[length];
314 rawMessage.readBytes(name);
315 return new String(name).trim();
319 * Read an IPv4 address from a buffer and format it into dotted-quad string.
321 * @param buf Input buffer
322 * @return Dotted-quad string
324 public static String readIpv4Address(final ByteBuf buf) {
325 final StringBuilder sb = new StringBuilder(EncodeConstants.GROUPS_IN_IPV4_ADDRESS * 4 - 1);
327 sb.append(buf.readUnsignedByte());
328 for (int i = 1; i < EncodeConstants.GROUPS_IN_IPV4_ADDRESS; i++) {
330 sb.append(buf.readUnsignedByte());
333 return sb.toString();
338 * Read an IPv6 address from a buffer and format it into a string of eight groups of four
339 * hexadecimal digits separated by colons.
341 * @param buf Input buffer
342 * @return IPv6 address in string format
344 public static String readIpv6Address(final ByteBuf buf) {
345 final StringBuilder sb = new StringBuilder(EncodeConstants.GROUPS_IN_IPV6_ADDRESS * 5 - 1);
347 appendHexUnsignedShort(sb, buf.readUnsignedShort());
348 for (int i = 1; i < EncodeConstants.GROUPS_IN_IPV6_ADDRESS; i++) {
350 appendHexUnsignedShort(sb, buf.readUnsignedShort());
353 return sb.toString();
356 public static Ipv4Address readIetfIpv4Address(final ByteBuf buf) {
357 final byte[] tmp = new byte[4];
359 return IetfInetUtil.INSTANCE.ipv4AddressFor(tmp);
362 public static Ipv6Address readIetfIpv6Address(final ByteBuf buf) {
363 final byte[] tmp = new byte[16];
365 return IetfInetUtil.INSTANCE.ipv6AddressFor(tmp);
368 public static MacAddress readIetfMacAddress(final ByteBuf buf) {
369 final byte[] tmp = new byte[EncodeConstants.MAC_ADDRESS_LENGTH];
371 return IetfYangUtil.INSTANCE.macAddressFor(tmp);
374 public static byte[] serializableList(final List<Short> list) throws IOException{
375 ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
376 ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
377 objectOutputStream.writeObject(list);
378 return byteArrayOutputStream.toByteArray();