Fix bug on ByteBufUtils method serializeList
[openflowjava.git] / openflowjava-util / src / main / java / org / opendaylight / openflowjava / util / ByteBufUtils.java
1 /*
2  * Copyright (c) 2013 Pantheon Technologies s.r.o. and others. All rights reserved.
3  *
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
7  */
8
9
10 package org.opendaylight.openflowjava.util;
11
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;
18 import java.io.IOException;
19 import java.nio.ByteBuffer;
20 import java.util.List;
21 import java.util.Map;
22 import java.util.Map.Entry;
23 import org.opendaylight.openflowjava.protocol.api.util.EncodeConstants;
24 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IetfInetUtil;
25 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv4Address;
26 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv6Address;
27 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.IetfYangUtil;
28 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.MacAddress;
29 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader;
30
31 /** Class for common operations on ByteBuf
32  * @author michal.polkorab
33  * @author timotej.kubas
34  */
35 public abstract class ByteBufUtils {
36     public static final Splitter DOT_SPLITTER = Splitter.on('.');
37     public static final Splitter COLON_SPLITTER = Splitter.on(':');
38     private static final char[] HEX_CHARS = "0123456789ABCDEF".toCharArray();
39     private static final Splitter HEXSTRING_SPLITTER =  Splitter.onPattern("\\s+").omitEmptyStrings();
40     private static final Splitter HEXSTRING_NOSPACE_SPLITTER = Splitter.onPattern("(?<=\\G.{2})").omitEmptyStrings();
41
42     private ByteBufUtils() {
43         //not called
44     }
45
46     /**
47      * Converts ByteBuf into String
48      * @param bb input ByteBuf
49      * @return String
50      */
51     public static String byteBufToHexString(final ByteBuf bb) {
52         StringBuilder sb = new StringBuilder();
53         for (int i = bb.readerIndex(); i < (bb.readerIndex() + bb.readableBytes()); i++) {
54             sb.append(String.format(" %02x", bb.getUnsignedByte(i)));
55         }
56         return sb.toString().trim();
57     }
58
59     /**
60      * Converts String into byte[]
61      * @param hexSrc input String
62      * @return byte[] filled with input data
63      */
64     public static byte[] hexStringToBytes(final String hexSrc) {
65         return hexStringToBytes(hexSrc, true);
66     }
67
68     /**
69      * Converts String into byte[]
70      * @param hexSrc input String
71      * @param withSpaces if there are spaces in string
72      * @return byte[] filled with input data
73      */
74     public static byte[] hexStringToBytes(final String hexSrc, final boolean withSpaces) {
75         final Splitter splitter = withSpaces ? HEXSTRING_SPLITTER : HEXSTRING_NOSPACE_SPLITTER;
76         List<String> byteChips = Lists.newArrayList(splitter.split(hexSrc));
77         byte[] result = new byte[byteChips.size()];
78         int i = 0;
79         for (String chip : byteChips) {
80             result[i] = (byte) Short.parseShort(chip, 16);
81             i++;
82         }
83         return result;
84     }
85
86     /**
87      * Creates ByteBuf filled with specified data
88      * @param hexSrc input String of bytes in hex format
89      * @return ByteBuf with specified hexString converted
90      */
91     public static ByteBuf hexStringToByteBuf(final String hexSrc) {
92         ByteBuf out = UnpooledByteBufAllocator.DEFAULT.buffer();
93         hexStringToByteBuf(hexSrc, out);
94         return out;
95     }
96
97     /**
98      * Creates ByteBuf filled with specified data
99      * @param hexSrc input String of bytes in hex format
100      * @param out ByteBuf with specified hexString converted
101      */
102     public static void hexStringToByteBuf(final String hexSrc, final ByteBuf out) {
103         out.writeBytes(hexStringToBytes(hexSrc));
104     }
105
106     /**
107      * Fills specified ByteBuf with 0 (zeros) of desired length, used for padding
108      * @param length
109      * @param out ByteBuf to be padded
110      * @deprecated Use {@link ByteBuf#writeZero(int)} directly.
111      */
112     @Deprecated
113     public static void padBuffer(final int length, final ByteBuf out) {
114         out.writeZero(length);
115     }
116
117     /**
118      * Create standard OF header
119      * @param msgType message code
120      * @param message POJO
121      * @param out writing buffer
122      * @param length ofheader length
123      */
124     public static <E extends OfHeader> void writeOFHeader(final byte msgType, final E message, final ByteBuf out, final int length) {
125         out.writeByte(message.getVersion());
126         out.writeByte(msgType);
127         out.writeShort(length);
128         out.writeInt(message.getXid().intValue());
129     }
130
131     /**
132      * Write length standard OF header
133      * @param out writing buffer
134      */
135     public static void updateOFHeaderLength(final ByteBuf out) {
136         out.setShort(EncodeConstants.OFHEADER_LENGTH_INDEX, out.readableBytes());
137     }
138
139     /**
140      * Fills the bitmask from boolean map where key is bit position
141      * @param booleanMap bit to boolean mapping
142      * @return bit mask
143      */
144     public static int fillBitMaskFromMap(final Map<Integer, Boolean> booleanMap) {
145         int bitmask = 0;
146
147         for (Entry<Integer, Boolean> iterator : booleanMap.entrySet()) {
148             if (iterator.getValue() != null && iterator.getValue().booleanValue()) {
149                 bitmask |= 1 << iterator.getKey();
150             }
151         }
152         return bitmask;
153     }
154
155     /**
156      * Fills the bitmask from a set of bit values, starting at specified offset.
157      *
158      * @param offset Bit offset to start at
159      * @param values boolean bit values to fill
160      * @return Filled-in bitmask
161      */
162     public static int fillBitMask(final int offset, final boolean... values) {
163         int bitmask = 0;
164
165         int i = offset;
166         for (boolean v : values) {
167             if (v) {
168                 bitmask |= 1 << i;
169             }
170             ++i;
171         }
172
173         return bitmask;
174     }
175
176     /**
177      * Fills the bitmask from boolean list where key is bit position
178      * @param booleanList bit to boolean mapping
179      * @return bit mask
180      */
181     public static int[] fillBitMaskFromList(final List<Boolean> booleanList) {
182         int[] bitmask;
183         int index = 0;
184         int arrayIndex = 0;
185         if ((booleanList.size() % Integer.SIZE) != 0) {
186             bitmask = new int[booleanList.size() / Integer.SIZE + 1];
187         } else {
188             bitmask = new int[booleanList.size() / Integer.SIZE];
189         }
190         for (Boolean currElement : booleanList) {
191             if (currElement != null && currElement.booleanValue()) {
192                 bitmask[arrayIndex] |= 1 << index;
193             }
194             index++;
195             arrayIndex = index / Integer.SIZE;
196         }
197         return bitmask;
198     }
199
200     /**
201      * Converts byte array into String
202      * @param array input byte array
203      * @return String
204      */
205     public static String bytesToHexString(final byte[] array) {
206         StringBuilder sb = new StringBuilder();
207         for (byte element : array) {
208             sb.append(String.format(" %02x", element));
209         }
210         return sb.toString().trim();
211     }
212
213     private static int hexValue(final char c) {
214         if (c >= '0' && c <= '9') {
215             return c - '0';
216         }
217         if (c >= 'a' && c <= 'f') {
218             return c - 'a' + 10;
219         }
220         if (c >= 'A' && c <= 'F') {
221             return c - 'A' + 10;
222         }
223
224         throw new IllegalArgumentException(String.format("Invalid character '%s' encountered", c));
225     }
226
227     /**
228      * Converts macAddress to byte array.
229      * See also {@link org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.MacAddress}.
230      *
231      * @param macAddress
232      * @return byte representation of mac address
233      */
234     public static byte[] macAddressToBytes(final String macAddress) {
235         final byte[] result = new byte[EncodeConstants.MAC_ADDRESS_LENGTH];
236         final char[] mac = macAddress.toCharArray();
237
238         try {
239             int offset = 0;
240             for (int i = 0; i < EncodeConstants.MAC_ADDRESS_LENGTH - 1; ++i) {
241                 if (mac[offset + EncodeConstants.SIZE_OF_BYTE_IN_BYTES] == ':') {
242                     result[i] = UnsignedBytes.checkedCast(hexValue(mac[offset]));
243                     offset++;
244                 } else {
245                     result[i] = UnsignedBytes.checkedCast(
246                             (hexValue(mac[offset]) << 4) | hexValue(mac[offset +1]));
247                     offset += 2;
248                 }
249                 Preconditions.checkArgument(mac[offset] == ':', "Invalid value: %s", macAddress);
250                 offset++;
251             }
252
253             if (offset == (mac.length - 1)) {
254                 result[EncodeConstants.MAC_ADDRESS_LENGTH - 1] = UnsignedBytes.checkedCast(hexValue(mac[offset]));
255             } else {
256                 result[EncodeConstants.MAC_ADDRESS_LENGTH - 1] =
257                         UnsignedBytes.checkedCast(hexValue(mac[offset]) << 4 | hexValue(mac[offset +1]));
258                 offset++;
259             }
260             if (offset != (mac.length -1)) {
261                 throw new IllegalArgumentException("Incorrect MAC address length");
262             }
263         } catch (Exception e) {
264             throw new IllegalArgumentException("Unable to serialize MAC address for input: " + macAddress
265                     + ". \n" + e);
266         }
267         return result;
268     }
269
270     private static final void appendHexByte(final StringBuilder sb, final byte b) {
271         final int v = UnsignedBytes.toInt(b);
272         sb.append(HEX_CHARS[v >>> 4]);
273         sb.append(HEX_CHARS[v &  15]);
274     }
275
276     private static void appendHexUnsignedShort(final StringBuilder sb, final int val) {
277         sb.append(ByteBufUtils.HEX_CHARS[(val >>> 12) & 15]);
278         sb.append(ByteBufUtils.HEX_CHARS[(val >>>  8) & 15]);
279         sb.append(ByteBufUtils.HEX_CHARS[(val >>>  4) & 15]);
280         sb.append(ByteBufUtils.HEX_CHARS[ val         & 15]);
281     }
282
283     /**
284      * Converts a MAC address represented in bytes to String.
285      * See also {@link org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.MacAddress}.
286      *
287      * @param address
288      * @return String representation of a MAC address
289      */
290     public static String macAddressToString(final byte[] address) {
291         Preconditions.checkArgument(address.length == EncodeConstants.MAC_ADDRESS_LENGTH);
292
293         final StringBuilder sb = new StringBuilder(17);
294
295         appendHexByte(sb, address[0]);
296         for (int i = 1; i < EncodeConstants.MAC_ADDRESS_LENGTH; i++) {
297             sb.append(':');
298             appendHexByte(sb, address[i]);
299         }
300
301         return sb.toString();
302     }
303
304     /**
305      * Reads and parses null-terminated string from ByteBuf
306      * @param rawMessage
307      * @param length maximal length of String
308      * @return String with name of port
309      */
310     public static String decodeNullTerminatedString(final ByteBuf rawMessage, final int length) {
311         byte[] name = new byte[length];
312         rawMessage.readBytes(name);
313         return new String(name).trim();
314     }
315
316     /**
317      * Read an IPv4 address from a buffer and format it into dotted-quad string.
318      *
319      * @param buf Input buffer
320      * @return Dotted-quad string
321      */
322     public static String readIpv4Address(final ByteBuf buf) {
323         final StringBuilder sb = new StringBuilder(EncodeConstants.GROUPS_IN_IPV4_ADDRESS * 4 - 1);
324
325         sb.append(buf.readUnsignedByte());
326         for (int i = 1; i < EncodeConstants.GROUPS_IN_IPV4_ADDRESS; i++) {
327             sb.append('.');
328             sb.append(buf.readUnsignedByte());
329         }
330
331         return sb.toString();
332     }
333
334
335     /**
336      * Read an IPv6 address from a buffer and format it into a string of eight groups of four
337      * hexadecimal digits separated by colons.
338      *
339      * @param buf Input buffer
340      * @return IPv6 address in string format
341      */
342     public static String readIpv6Address(final ByteBuf buf) {
343         final StringBuilder sb = new StringBuilder(EncodeConstants.GROUPS_IN_IPV6_ADDRESS * 5 - 1);
344
345         appendHexUnsignedShort(sb, buf.readUnsignedShort());
346         for (int i = 1; i < EncodeConstants.GROUPS_IN_IPV6_ADDRESS; i++) {
347             sb.append(':');
348             appendHexUnsignedShort(sb, buf.readUnsignedShort());
349         }
350
351         return sb.toString();
352     }
353
354     public static Ipv4Address readIetfIpv4Address(final ByteBuf buf) {
355         final byte[] tmp = new byte[4];
356         buf.readBytes(tmp);
357         return IetfInetUtil.INSTANCE.ipv4AddressFor(tmp);
358     }
359
360     public static Ipv6Address readIetfIpv6Address(final ByteBuf buf) {
361         final byte[] tmp = new byte[16];
362         buf.readBytes(tmp);
363         return IetfInetUtil.INSTANCE.ipv6AddressFor(tmp);
364     }
365
366     public static MacAddress readIetfMacAddress(final ByteBuf buf) {
367         final byte[] tmp = new byte[EncodeConstants.MAC_ADDRESS_LENGTH];
368         buf.readBytes(tmp);
369         return IetfYangUtil.INSTANCE.macAddressFor(tmp);
370     }
371     
372     public static byte[] serializeList(final List<Short> list) throws IOException{
373         ByteBuffer byteBuffer = ByteBuffer.allocate(list.size() * 2);
374         for (Short aShort : list) {
375             byteBuffer.putShort(aShort);
376         }
377         return byteBuffer.array();
378     }
379 }