Fixed FIXME on MAC address serialization
[openflowjava.git] / util / src / main / java / org / opendaylight / openflowjava / util / ByteBufUtils.java
index f03f19638427b12bb9a065cb4b367203723bc9a2..444cffc504ad9ffcdcc2e571f15d599012c603f0 100644 (file)
@@ -226,24 +226,40 @@ public abstract class ByteBufUtils {
      * @param macAddress
      * @return byte representation of mac address
      * @see {@link MacAddress}
-     *
-     * FIXME: this method does not support shortened values, e.g.
-     *        "0:1:2:3:4:5", only "00:11:22:33:44:55".
      */
     public static byte[] macAddressToBytes(final String macAddress) {
         final byte[] result = new byte[EncodeConstants.MAC_ADDRESS_LENGTH];
         final char[] mac = macAddress.toCharArray();
 
-        int offset = 0;
-        for (int i = 0; i < EncodeConstants.MAC_ADDRESS_LENGTH - 1; ++i) {
-            result[i] = UnsignedBytes.checkedCast(
-                    (hexValue(mac[offset++]) << 4) | hexValue(mac[offset++]));
-            Preconditions.checkArgument(mac[offset] == ':', "Invalid value: %s", macAddress);
-            offset++;
-        }
+        try {
+            int offset = 0;
+            for (int i = 0; i < EncodeConstants.MAC_ADDRESS_LENGTH - 1; ++i) {
+                if (mac[offset + EncodeConstants.SIZE_OF_BYTE_IN_BYTES] == ':') {
+                    result[i] = UnsignedBytes.checkedCast(hexValue(mac[offset]));
+                    offset++;
+                } else {
+                    result[i] = UnsignedBytes.checkedCast(
+                            (hexValue(mac[offset]) << 4) | hexValue(mac[offset +1]));
+                    offset += 2;
+                }
+                Preconditions.checkArgument(mac[offset] == ':', "Invalid value: %s", macAddress);
+                offset++;
+            }
 
-        result[EncodeConstants.MAC_ADDRESS_LENGTH - 1] =
-                UnsignedBytes.checkedCast(hexValue(mac[offset++]) << 4 | hexValue(mac[offset]));
+            if (offset == (mac.length - 1)) {
+                result[EncodeConstants.MAC_ADDRESS_LENGTH - 1] = UnsignedBytes.checkedCast(hexValue(mac[offset]));
+            } else {
+                result[EncodeConstants.MAC_ADDRESS_LENGTH - 1] =
+                        UnsignedBytes.checkedCast(hexValue(mac[offset]) << 4 | hexValue(mac[offset +1]));
+                offset++;
+            }
+            if (offset != (mac.length -1)) {
+                throw new IllegalArgumentException("Incorrect MAC address length");
+            }
+        } catch (Exception e) {
+            throw new IllegalArgumentException("Unable to serialize MAC address for input: " + macAddress
+                    + ". \n" + e);
+        }
         return result;
     }