Add NoZone support
[mdsal.git] / model / ietf / ietf-type-util / src / main / java / org / opendaylight / mdsal / model / ietf / util / AbstractIetfInetUtil.java
index 7781d6fc75c569bf5edb79374cce609ac5795174..51e9638791c933f8a1f8e4f9ca9efa1260622d8b 100644 (file)
@@ -9,47 +9,89 @@ package org.opendaylight.mdsal.model.ietf.util;
 
 import com.google.common.annotations.Beta;
 import com.google.common.base.Preconditions;
+import com.google.common.net.InetAddresses;
 import java.net.Inet4Address;
 import java.net.Inet6Address;
 import java.net.InetAddress;
 import java.net.UnknownHostException;
+import java.util.AbstractMap.SimpleImmutableEntry;
+import java.util.Map.Entry;
 import javax.annotation.Nonnull;
+import javax.annotation.Nullable;
 import org.opendaylight.yangtools.yang.binding.util.StringValueObjectFactory;
 
 /**
  * A set of utility methods to efficiently instantiate various ietf-inet-types DTOs.
- *
- * FIXME: IPv6 addresses are not emitted in canonical format as specified by the model.
  */
 @Beta
-public abstract class AbstractIetfInetUtil<A4, P4, A6, P6, A> {
-    private final StringValueObjectFactory<A4> address4Factory;
+public abstract class AbstractIetfInetUtil<A4, A4NZ extends A4, P4, A6, A6NZ extends A6, P6, A, ANZ, P> {
+    protected static final int INET4_LENGTH = 4;
+    protected static final int INET6_LENGTH = 16;
+    private final StringValueObjectFactory<A4NZ> nozone4Factory;
     private final StringValueObjectFactory<P4> prefix4Factory;
-    private final StringValueObjectFactory<A6> address6Factory;
+    private final StringValueObjectFactory<A6NZ> nozone6Factory;
     private final StringValueObjectFactory<P6> prefix6Factory;
 
-    protected AbstractIetfInetUtil(final Class<A4> addr4Class, final Class<P4> prefix4Class,
-            final Class<A6> addr6Class, final Class<P6> prefix6Class) {
-        this.address4Factory = StringValueObjectFactory.create(addr4Class, "0.0.0.0");
+    protected AbstractIetfInetUtil(final Class<A4NZ> nozone4Class, final Class<P4> prefix4Class,
+            final Class<A6NZ> nozone6Class, final Class<P6> prefix6Class) {
+        this.nozone4Factory = StringValueObjectFactory.create(nozone4Class, "0.0.0.0");
         this.prefix4Factory = StringValueObjectFactory.create(prefix4Class, "0.0.0.0/0");
-        this.address6Factory = StringValueObjectFactory.create(addr6Class, "::0");
+        this.nozone6Factory = StringValueObjectFactory.create(nozone6Class, "::0");
         this.prefix6Factory = StringValueObjectFactory.create(prefix6Class, "::0/0");
     }
 
-    protected abstract A ipv4Address(A4 addr);
-    protected abstract A ipv6Address(A6 addr);
+    @Nonnull protected abstract A ipv4Address(@Nonnull A4 addr);
+    @Nonnull protected abstract A ipv6Address(@Nonnull A6 addr);
+    @Nonnull protected abstract ANZ ipv4AddressNoZone(@Nonnull A4NZ addr);
+    @Nonnull protected abstract ANZ ipv6AddressNoZone(@Nonnull A6NZ addr);
+
+    @Nonnull protected abstract P ipv4Prefix(@Nonnull P4 addr);
+    @Nonnull protected abstract P ipv6Prefix(@Nonnull P6 addr);
+    @Nullable protected abstract A4 maybeIpv4Address(@Nonnull A addr);
+    @Nullable protected abstract A6 maybeIpv6Address(@Nonnull A addr);
+    @Nonnull protected abstract String ipv4AddressString(@Nonnull A4 addr);
+    @Nonnull protected abstract String ipv6AddressString(@Nonnull A6 addr);
+    @Nonnull protected abstract String ipv4PrefixString(@Nonnull P4 prefix);
+    @Nonnull protected abstract String ipv6PrefixString(@Nonnull P6 prefix);
 
+    /**
+     * Create an IpAddress by interpreting input bytes as an IPv4 or IPv6 address, based on array length.
+     *
+     * @param bytes 4-byte (IPv4) or 6-byte (IPv6) array
+     * @return An IpAddress object
+     * @throws IllegalArgumentException if bytes has length different from 4 or 6
+     * @throws NullPointerException if bytes is null
+     */
     @Nonnull public final A ipAddressFor(@Nonnull final byte[] bytes) {
         switch (bytes.length) {
-            case 4:
+            case INET4_LENGTH:
                 return ipv4Address(ipv4AddressFor(bytes));
-            case 16:
+            case INET6_LENGTH:
                 return ipv6Address(ipv6AddressFor(bytes));
             default:
                 throw new IllegalArgumentException("Invalid array length " + bytes.length);
         }
     }
 
+    /**
+     * Create an IpAddress by interpreting input bytes as an IPv4 or IPv6 address, based on array length.
+     *
+     * @param bytes 4-byte (IPv4) or 6-byte (IPv6) array
+     * @return A no-zone IpAddress object
+     * @throws IllegalArgumentException if bytes has length different from 4 or 6
+     * @throws NullPointerException if bytes is null
+     */
+    @Nonnull public final ANZ ipAddressNoZoneFor(@Nonnull final byte[] bytes) {
+        switch (bytes.length) {
+            case INET4_LENGTH:
+                return ipv4AddressNoZone(ipv4AddressFor(bytes));
+            case INET6_LENGTH:
+                return ipv6AddressNoZone(ipv6AddressFor(bytes));
+            default:
+                throw new IllegalArgumentException("Invalid array length " + bytes.length);
+        }
+    }
+
     @Nonnull public final A ipAddressFor(@Nonnull final InetAddress addr) {
         Preconditions.checkNotNull(addr, "Address must not be null");
         if (addr instanceof Inet4Address) {
@@ -61,6 +103,77 @@ public abstract class AbstractIetfInetUtil<A4, P4, A6, P6, A> {
         }
     }
 
+    @Nonnull public final ANZ ipAddressNoZoneFor(@Nonnull final InetAddress addr) {
+        Preconditions.checkNotNull(addr, "Address must not be null");
+        if (addr instanceof Inet4Address) {
+            return ipv4AddressNoZone(ipv4AddressFor(addr));
+        } else if (addr instanceof Inet6Address) {
+            return ipv6AddressNoZone(ipv6AddressFor(addr));
+        } else {
+            throw new IllegalArgumentException("Unhandled address " + addr);
+        }
+    }
+
+    /**
+     * Create an IpPrefix by combining the address with a mask. The address
+     * bytes are interpreted as an address and the specified mask is concatenated to
+     * it. The address bytes are not masked.
+     *
+     * @param bytes Input address as a 4-byte (IPv4) or 16-byte (IPv6) array
+     * @param mask Prefix mask
+     * @return An IpPrefix object
+     * @throws IllegalArgumentException if bytes has length different from 4 or 16 or if mask is not
+     *         in range 0-32 or 0-128 respectively
+     * @throws NullPointerException if bytes is null
+     */
+    @Nonnull public final P ipPrefixFor(@Nonnull final byte[] bytes, final int mask) {
+        switch (bytes.length) {
+            case INET4_LENGTH:
+                return ipv4Prefix(ipv4PrefixFor(bytes, mask));
+            case INET6_LENGTH:
+                return ipv6Prefix(ipv6PrefixFor(bytes, mask));
+            default:
+                throw new IllegalArgumentException("Invalid array length " + bytes.length);
+        }
+    }
+
+    @Nonnull public final P ipPrefixFor(@Nonnull final InetAddress addr, final int mask) {
+        Preconditions.checkNotNull(addr, "Address must not be null");
+        if (addr instanceof Inet4Address) {
+            return ipv4Prefix(ipv4PrefixFor(addr, mask));
+        } else if (addr instanceof Inet6Address) {
+            return ipv6Prefix(ipv6PrefixFor(addr, mask));
+        } else {
+            throw new IllegalArgumentException("Unhandled address " + addr);
+        }
+    }
+
+    @Nonnull public final InetAddress inetAddressFor(@Nonnull final A addr) {
+        final A4 v4 = maybeIpv4Address(addr);
+        if (v4 != null) {
+            return inet4AddressFor(v4);
+        }
+        final A6 v6 = maybeIpv6Address(addr);
+        Preconditions.checkArgument(v6 != null, "Address %s is neither IPv4 nor IPv6", addr);
+        return inet6AddressFor(v6);
+    }
+
+    @Nonnull public final Inet4Address inet4AddressFor(@Nonnull final A4 addr) {
+        try {
+            return (Inet4Address) InetAddress.getByAddress(ipv4AddressBytes(addr));
+        } catch (UnknownHostException e) {
+            throw new IllegalArgumentException("Invalid address " + addr, e);
+        }
+    }
+
+    @Nonnull public final Inet6Address inet6AddressFor(@Nonnull final A6 addr) {
+        try {
+            return (Inet6Address) InetAddress.getByAddress(ipv6AddressBytes(addr));
+        } catch (UnknownHostException e) {
+            throw new IllegalArgumentException("Invalid address " + addr, e);
+        }
+    }
+
     /**
      * Create an Ipv4Address by interpreting input bytes as an IPv4 address.
      *
@@ -69,8 +182,8 @@ public abstract class AbstractIetfInetUtil<A4, P4, A6, P6, A> {
      * @throws IllegalArgumentException if bytes has length different from 4
      * @throws NullPointerException if bytes is null
      */
-    @Nonnull public final A4 ipv4AddressFor(@Nonnull final byte[] bytes) {
-        return address4Factory.newInstance(addressStringV4(bytes));
+    @Nonnull public final A4NZ ipv4AddressFor(@Nonnull final byte[] bytes) {
+        return nozone4Factory.newInstance(addressStringV4(bytes));
     }
 
     /**
@@ -81,10 +194,30 @@ public abstract class AbstractIetfInetUtil<A4, P4, A6, P6, A> {
      * @throws IllegalArgumentException if addr is not an {@link Inet4Address}
      * @throws NullPointerException if addr is null
      */
-    @Nonnull public final A4 ipv4AddressFor(@Nonnull final InetAddress addr) {
+    @Nonnull public final A4NZ ipv4AddressFor(@Nonnull final InetAddress addr) {
         Preconditions.checkNotNull(addr, "Address must not be null");
         Preconditions.checkArgument(addr instanceof Inet4Address, "Address has to be an Inet4Address");
-        return address4Factory.newInstance(addr.getHostAddress());
+        return nozone4Factory.newInstance(addr.getHostAddress());
+    }
+
+    @Nonnull public final A4NZ ipv4AddressFrom(@Nonnull final P4 prefix) {
+        return prefixToAddress(nozone4Factory, ipv4PrefixString(prefix));
+    }
+
+    @Nonnull public final byte[] ipv4AddressBytes(@Nonnull final A4 addr) {
+        /*
+         * This implementation relies heavily on the input string having been validated to comply with
+         * the Ipv4Address pattern, which may include a zone index.
+         */
+        final String str = ipv4AddressString(addr);
+        final int percent = str.indexOf('%');
+        return ipv4AddressBytes(str, percent == -1 ? str.length() : percent);
+    }
+
+    protected static final byte[] ipv4AddressBytes(@Nonnull final String str, final int length) {
+        final byte[] bytes = new byte[INET4_LENGTH];
+        Ipv4Utils.fillIpv4Bytes(bytes, 0, str, 0, length);
+        return bytes;
     }
 
     /**
@@ -115,6 +248,24 @@ public abstract class AbstractIetfInetUtil<A4, P4, A6, P6, A> {
         return prefix4Factory.newInstance(prefixStringV4(address, mask));
     }
 
+    @Nonnull public final P4 ipv4PrefixForShort(@Nonnull final byte[] address, final int mask) {
+        if (mask == 0) {
+            // Easy case, reuse the template
+            return prefix4Factory.getTemplate();
+        }
+
+        return v4PrefixForShort(address, 0, mask / Byte.SIZE + (mask % Byte.SIZE == 0 ? 0 : 1), mask);
+    }
+
+    @Nonnull public final P4 ipv4PrefixForShort(@Nonnull final byte[] array, final int startOffset, final int mask) {
+        if (mask == 0) {
+            // Easy case, reuse the template
+            return prefix4Factory.getTemplate();
+        }
+
+        return v4PrefixForShort(array, startOffset, mask / Byte.SIZE + (mask % Byte.SIZE == 0 ? 0 : 1), mask);
+    }
+
     /**
      * Create a /32 Ipv4Prefix for an {@link Inet4Address}
      *
@@ -145,6 +296,31 @@ public abstract class AbstractIetfInetUtil<A4, P4, A6, P6, A> {
         return prefix4Factory.newInstance(addr.getHostAddress() + '/' + mask);
     }
 
+    @Nonnull public final P4 ipv4PrefixFor(@Nonnull final A4 addr) {
+        Preconditions.checkNotNull(addr, "Address must not be null");
+        return prefix4Factory.newInstance(ipv4AddressString(addr) + "/32");
+    }
+
+    @Nonnull public final P4 ipv4PrefixFor(@Nonnull final A4 addr, final int mask) {
+        Preconditions.checkNotNull(addr, "Address must not be null");
+        Preconditions.checkArgument(mask >= 0 && mask <= 32, "Invalid mask %s", mask);
+        return prefix4Factory.newInstance(ipv4AddressString(addr) + '/' + mask);
+    }
+
+    @Nonnull public final Entry<A4NZ, Integer> splitIpv4Prefix(@Nonnull final P4 prefix) {
+        return splitPrefix(nozone4Factory, ipv4PrefixString(prefix));
+    }
+
+    @Nonnull public final byte[] ipv4PrefixToBytes(@Nonnull final P4 prefix) {
+        final String str = ipv4PrefixString(prefix);
+        final int slash = str.lastIndexOf('/');
+
+        final byte[] bytes = new byte[INET4_LENGTH + 1];
+        Ipv4Utils.fillIpv4Bytes(bytes, 0, str, 0, slash);
+        bytes[INET4_LENGTH] = (byte)Integer.parseInt(str.substring(slash + 1), 10);
+        return bytes;
+    }
+
     /**
      * Create an Ipv6Address by interpreting input bytes as an IPv6 address.
      *
@@ -153,8 +329,8 @@ public abstract class AbstractIetfInetUtil<A4, P4, A6, P6, A> {
      * @throws IllegalArgumentException if bytes has length different from 16
      * @throws NullPointerException if bytes is null
      */
-    @Nonnull public final A6 ipv6AddressFor(@Nonnull final byte[] bytes) {
-        return address6Factory.newInstance(addressStringV6(bytes));
+    @Nonnull public final A6NZ ipv6AddressFor(@Nonnull final byte[] bytes) {
+        return nozone6Factory.newInstance(addressStringV6(bytes));
     }
 
     /**
@@ -165,12 +341,29 @@ public abstract class AbstractIetfInetUtil<A4, P4, A6, P6, A> {
      * @throws IllegalArgumentException if addr is not an {@link Inet6Address}
      * @throws NullPointerException if addr is null
      */
-    @Nonnull public final A6 ipv6AddressFor(@Nonnull final InetAddress addr) {
+    @Nonnull public final A6NZ ipv6AddressFor(@Nonnull final InetAddress addr) {
         Preconditions.checkNotNull(addr, "Address must not be null");
         Preconditions.checkArgument(addr instanceof Inet6Address, "Address has to be an Inet6Address");
-        return address6Factory.newInstance(addr.getHostAddress());
+        return nozone6Factory.newInstance(addressStringV6(addr));
+    }
+
+    @Nonnull public final A6 ipv6AddressFrom(@Nonnull final P6 prefix) {
+        return prefixToAddress(nozone6Factory, ipv6PrefixString(prefix));
+    }
+
+    @Nonnull public final byte[] ipv6AddressBytes(@Nonnull final A6 addr) {
+        final String str = ipv6AddressString(addr);
+        final int percent = str.indexOf('%');
+        return ipv6AddressBytes(str, percent == -1 ? str.length() : percent);
+    }
+
+    protected static final byte[] ipv6AddressBytes(@Nonnull final String str, final int length) {
+        final byte[] bytes = new byte[INET6_LENGTH];
+        Ipv6Utils.fillIpv6Bytes(bytes, str, length);
+        return bytes;
     }
 
+
     /**
      * Create a /128 Ipv6Prefix by interpreting input bytes as an IPv6 address.
      *
@@ -188,7 +381,7 @@ public abstract class AbstractIetfInetUtil<A4, P4, A6, P6, A> {
      * bytes are interpreted as an address and the specified mask is concatenated to
      * it. The address bytes are not masked.
      *
-     * @param address Input address as a 4-byte array
+     * @param address Input address as a 16-byte array
      * @param mask Prefix mask
      * @return An Ipv6Prefix object
      * @throws IllegalArgumentException if bytes has length different from 16 or if mask is not in range 0-128
@@ -199,6 +392,25 @@ public abstract class AbstractIetfInetUtil<A4, P4, A6, P6, A> {
         return prefix6Factory.newInstance(addressStringV6(address) + '/' + mask);
     }
 
+    @Nonnull public final P6 ipv6PrefixForShort(@Nonnull final byte[] address, final int mask) {
+        return ipv6PrefixForShort(address, 0, mask);
+    }
+
+    @Nonnull public final P6 ipv6PrefixForShort(@Nonnull final byte[] array, final int startOffset, final int mask) {
+        if (mask == 0) {
+            // Easy case, reuse the template
+            return prefix6Factory.getTemplate();
+        }
+
+        Preconditions.checkArgument(mask > 0 && mask <= 128, "Invalid mask %s", mask);
+        final int size = mask / Byte.SIZE + (mask % Byte.SIZE == 0 ? 0 : 1);
+
+        // Until we can instantiate an IPv6 address for a partial array, use a temporary buffer
+        byte[] tmp = new byte[INET6_LENGTH];
+        System.arraycopy(array, startOffset, tmp, 0, size);
+        return ipv6PrefixFor(tmp, mask);
+    }
+
     /**
      * Create a /128 Ipv6Prefix by interpreting input bytes as an IPv4 address.
      *
@@ -208,7 +420,7 @@ public abstract class AbstractIetfInetUtil<A4, P4, A6, P6, A> {
      * @throws NullPointerException if addr is null
      */
     @Nonnull public final P6 ipv6PrefixFor(@Nonnull final InetAddress addr) {
-        return prefix6Factory.newInstance(addr.getHostAddress() + "/128");
+        return prefix6Factory.newInstance(addressStringV6(addr) + "/128");
     }
 
     /**
@@ -226,14 +438,48 @@ public abstract class AbstractIetfInetUtil<A4, P4, A6, P6, A> {
         Preconditions.checkNotNull(addr, "Address must not be null");
         Preconditions.checkArgument(addr instanceof Inet6Address, "Address has to be an Inet6Address");
         Preconditions.checkArgument(mask >= 0 && mask <= 128, "Invalid mask %s", mask);
-        return prefix6Factory.newInstance(addr.getHostAddress() + '/' + mask);
+        return prefix6Factory.newInstance(addressStringV6(addr) + '/' + mask);
+    }
+
+    @Nonnull public final P6 ipv6PrefixFor(@Nonnull final A6 addr) {
+        Preconditions.checkNotNull(addr, "Address must not be null");
+        return prefix6Factory.newInstance(ipv6AddressString(addr) + "/128");
+    }
+
+    @Nonnull public final P6 ipv6PrefixFor(@Nonnull final A6 addr, final int mask) {
+        Preconditions.checkNotNull(addr, "Address must not be null");
+        Preconditions.checkArgument(mask >= 0 && mask <= 128, "Invalid mask %s", mask);
+        return prefix6Factory.newInstance(ipv6AddressString(addr) + '/' + mask);
+    }
+
+    @Nonnull public final Entry<A6NZ, Integer> splitIpv6Prefix(@Nonnull final P6 prefix) {
+        return splitPrefix(nozone6Factory, ipv6PrefixString(prefix));
+    }
+
+    private static <T> T prefixToAddress(final StringValueObjectFactory<T> factory, final String str) {
+        return factory.newInstance(str.substring(0, str.lastIndexOf('/')));
+    }
+
+    private static <T> Entry<T, Integer> splitPrefix(final StringValueObjectFactory<T> factory, final String str) {
+        final int slash = str.lastIndexOf('/');
+        return new SimpleImmutableEntry<>(factory.newInstance(str.substring(0, slash)),
+                Integer.valueOf(str.substring(slash + 1)));
+    }
+
+    @Nonnull public final byte[] ipv6PrefixToBytes(@Nonnull final P6 prefix) {
+        final String str = ipv6PrefixString(prefix);
+        final byte[] bytes = new byte[INET6_LENGTH + 1];
+        final int slash = str.lastIndexOf('/');
+        Ipv6Utils.fillIpv6Bytes(bytes, str, slash);
+        bytes[INET6_LENGTH] = (byte)Integer.parseInt(str.substring(slash + 1), 10);
+        return bytes;
     }
 
     private static void appendIpv4String(final StringBuilder sb, final byte[] bytes) {
-        Preconditions.checkArgument(bytes.length == 4, "IPv4 address length is 4 bytes");
+        Preconditions.checkArgument(bytes.length == INET4_LENGTH, "IPv4 address length is 4 bytes");
 
         sb.append(Byte.toUnsignedInt(bytes[0]));
-        for (int i = 1; i < 4; ++i) {
+        for (int i = 1; i < INET4_LENGTH; ++i) {
             sb.append('.');
             sb.append(Byte.toUnsignedInt(bytes[i]));
         }
@@ -246,15 +492,19 @@ public abstract class AbstractIetfInetUtil<A4, P4, A6, P6, A> {
     }
 
     private static String addressStringV6(final byte[] bytes) {
-        Preconditions.checkArgument(bytes.length == 16, "IPv6 address length is 16 bytes");
+        Preconditions.checkArgument(bytes.length == INET6_LENGTH, "IPv6 address length is 16 bytes");
 
         try {
-            return Inet6Address.getByAddress(bytes).getHostAddress();
+            return addressStringV6(Inet6Address.getByAddress(bytes));
         } catch (UnknownHostException e) {
             throw new IllegalArgumentException(String.format("Invalid input %s", bytes), e);
         }
     }
 
+    private static String addressStringV6(final InetAddress addr) {
+        return InetAddresses.toAddrString(addr);
+    }
+
     private static String prefixStringV4(final byte[] bytes) {
         final StringBuilder sb = new StringBuilder(18);
         appendIpv4String(sb, bytes);
@@ -271,4 +521,32 @@ public abstract class AbstractIetfInetUtil<A4, P4, A6, P6, A> {
         sb.append(mask);
         return sb.toString();
     }
+
+    private P4 v4PrefixForShort(@Nonnull final byte[] array, final int startOffset, final int size, final int mask) {
+        if (startOffset == 0 && size == INET4_LENGTH && array.length == INET4_LENGTH) {
+            // Easy case, fall back to non-short
+            return ipv4PrefixFor(array, mask);
+        }
+
+        final StringBuilder sb = new StringBuilder(18);
+
+        // Add from address
+        sb.append(Byte.toUnsignedInt(array[startOffset]));
+        for (int i = 1; i < size; i++) {
+            sb.append('.');
+            sb.append(Byte.toUnsignedInt(array[startOffset + i]));
+        }
+
+        // Add zeros
+        for (int i = size; i < INET4_LENGTH; i++) {
+            sb.append(".0");
+        }
+
+        // Add mask
+        Preconditions.checkArgument(mask > 0 && mask <= 32, "Invalid mask %s", mask);
+        sb.append('/');
+        sb.append(mask);
+
+        return prefix4Factory.newInstance(sb.toString());
+    }
 }