Use a constant append string
[mdsal.git] / model / ietf / ietf-type-util / src / main / java / org / opendaylight / mdsal / model / ietf / util / AbstractIetfInetUtil.java
1 /*
2  * Copyright (c) 2016 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 package org.opendaylight.mdsal.model.ietf.util;
9
10 import com.google.common.annotations.Beta;
11 import com.google.common.base.Preconditions;
12 import com.google.common.net.InetAddresses;
13 import com.google.common.primitives.UnsignedBytes;
14 import java.net.Inet4Address;
15 import java.net.Inet6Address;
16 import java.net.InetAddress;
17 import java.net.UnknownHostException;
18 import java.util.AbstractMap.SimpleImmutableEntry;
19 import java.util.Map.Entry;
20 import javax.annotation.Nonnull;
21 import org.opendaylight.yangtools.yang.binding.util.StringValueObjectFactory;
22
23 /**
24  * A set of utility methods to efficiently instantiate various ietf-inet-types DTOs.
25  */
26 @Beta
27 public abstract class AbstractIetfInetUtil<A4, P4, A6, P6, A> {
28     private static final int INET4_LENGTH = 4;
29     private static final int INET6_LENGTH = 16;
30     private final StringValueObjectFactory<A4> address4Factory;
31     private final StringValueObjectFactory<P4> prefix4Factory;
32     private final StringValueObjectFactory<A6> address6Factory;
33     private final StringValueObjectFactory<P6> prefix6Factory;
34
35     protected AbstractIetfInetUtil(final Class<A4> addr4Class, final Class<P4> prefix4Class,
36             final Class<A6> addr6Class, final Class<P6> prefix6Class) {
37         this.address4Factory = StringValueObjectFactory.create(addr4Class, "0.0.0.0");
38         this.prefix4Factory = StringValueObjectFactory.create(prefix4Class, "0.0.0.0/0");
39         this.address6Factory = StringValueObjectFactory.create(addr6Class, "::0");
40         this.prefix6Factory = StringValueObjectFactory.create(prefix6Class, "::0/0");
41     }
42
43     protected abstract A ipv4Address(A4 addr);
44     protected abstract A ipv6Address(A6 addr);
45     protected abstract String ipv4AddressString(A4 addr);
46     protected abstract String ipv6AddressString(A6 addr);
47     protected abstract String ipv4PrefixString(P4 prefix);
48     protected abstract String ipv6PrefixString(P6 prefix);
49
50     @Nonnull public final A ipAddressFor(@Nonnull final byte[] bytes) {
51         switch (bytes.length) {
52             case 4:
53                 return ipv4Address(ipv4AddressFor(bytes));
54             case 16:
55                 return ipv6Address(ipv6AddressFor(bytes));
56             default:
57                 throw new IllegalArgumentException("Invalid array length " + bytes.length);
58         }
59     }
60
61     @Nonnull public final A ipAddressFor(@Nonnull final InetAddress addr) {
62         Preconditions.checkNotNull(addr, "Address must not be null");
63         if (addr instanceof Inet4Address) {
64             return ipv4Address(ipv4AddressFor(addr));
65         } else if (addr instanceof Inet6Address) {
66             return ipv6Address(ipv6AddressFor(addr));
67         } else {
68             throw new IllegalArgumentException("Unhandled address " + addr);
69         }
70     }
71
72     /**
73      * Create an Ipv4Address by interpreting input bytes as an IPv4 address.
74      *
75      * @param bytes 4-byte array
76      * @return An Ipv4Address object
77      * @throws IllegalArgumentException if bytes has length different from 4
78      * @throws NullPointerException if bytes is null
79      */
80     @Nonnull public final A4 ipv4AddressFor(@Nonnull final byte[] bytes) {
81         return address4Factory.newInstance(addressStringV4(bytes));
82     }
83
84     /**
85      * Create an Ipv4Address by interpreting an {@link Inet4Address}.
86      *
87      * @param addr An {@link Inet4Address}
88      * @return An Ipv4Address object
89      * @throws IllegalArgumentException if addr is not an {@link Inet4Address}
90      * @throws NullPointerException if addr is null
91      */
92     @Nonnull public final A4 ipv4AddressFor(@Nonnull final InetAddress addr) {
93         Preconditions.checkNotNull(addr, "Address must not be null");
94         Preconditions.checkArgument(addr instanceof Inet4Address, "Address has to be an Inet4Address");
95         return address4Factory.newInstance(addr.getHostAddress());
96     }
97
98     @Nonnull public final A4 ipv4AddressFrom(@Nonnull final P4 prefix) {
99         return prefixToAddress(address4Factory, ipv4PrefixString(prefix));
100     }
101
102     @Nonnull public final byte[] ipv4AddressBytes(@Nonnull final A4 addr) {
103         /*
104          * This implementation relies heavily on the input string having been validated to comply with
105          * the Ipv4Address pattern, which may include a zone index.
106          */
107         final String str = ipv4AddressString(addr);
108         final byte[] bytes = new byte[INET4_LENGTH];
109         final int percent = str.indexOf('%');
110         Ipv4Utils.fillIpv4Bytes(bytes, 0, str, 0, percent == -1 ? str.length() : percent);
111         return bytes;
112     }
113
114     /**
115      * Create a /32 Ipv4Prefix by interpreting input bytes as an IPv4 address.
116      *
117      * @param bytes four-byte array
118      * @return An Ipv4Prefix object
119      * @throws IllegalArgumentException if bytes has length different from 4
120      * @throws NullPointerException if bytes is null
121      */
122     @Nonnull public final P4 ipv4PrefixFor(@Nonnull final byte[] bytes) {
123         return prefix4Factory.newInstance(prefixStringV4(bytes));
124     }
125
126     /**
127      * Create a Ipv4Prefix by combining the address with a mask. The address
128      * bytes are interpreted as an address and the specified mask is concatenated to
129      * it. The address bytes are not masked, hence input <code>address = { 1, 2, 3, 4 }</code>
130      * and <code>mask=24</code> will result in <code>1.2.3.4/24</code>.
131      *
132      * @param address Input address as a 4-byte array
133      * @param mask Prefix mask
134      * @return An Ipv4Prefix object
135      * @throws IllegalArgumentException if bytes has length different from 4 or if mask is not in range 0-32
136      * @throws NullPointerException if bytes is null
137      */
138     @Nonnull public final P4 ipv4PrefixFor(@Nonnull final byte[] address, final int mask) {
139         return prefix4Factory.newInstance(prefixStringV4(address, mask));
140     }
141
142     @Nonnull public final P4 ipv4PrefixForShort(@Nonnull final byte[] address, final int mask) {
143         if (mask == 0) {
144             // Easy case, reuse the template
145             return prefix4Factory.getTemplate();
146         }
147
148         return v4PrefixForShort(address, 0, (mask / Byte.SIZE) + ((mask % Byte.SIZE == 0) ? 0 : 1), mask);
149     }
150
151     @Nonnull public final P4 ipv4PrefixForShort(@Nonnull final byte[] array, final int startOffset, final int mask) {
152         if (mask == 0) {
153             // Easy case, reuse the template
154             return prefix4Factory.getTemplate();
155         }
156
157         return v4PrefixForShort(array, startOffset, (mask / Byte.SIZE) + ((mask % Byte.SIZE == 0) ? 0 : 1), mask);
158     }
159
160     /**
161      * Create a /32 Ipv4Prefix for an {@link Inet4Address}
162      *
163      * @param addr An {@link Inet4Address}
164      * @return An Ipv4Prefix object
165      * @throws IllegalArgumentException if addr is not an Inet4Address
166      * @throws NullPointerException if adds is null
167      */
168     @Nonnull public final P4 ipv4PrefixFor(@Nonnull final InetAddress addr) {
169         Preconditions.checkNotNull(addr, "Address must not be null");
170         Preconditions.checkArgument(addr instanceof Inet4Address, "Address has to be an Inet4Address");
171         return prefix4Factory.newInstance(addr.getHostAddress() + "/32");
172     }
173
174     /**
175      * Create a Ipv4Prefix by combining the address with a mask. The address bytes are not masked.
176      *
177      * @param addr An {@link Inet4Address}
178      * @param mask Prefix mask
179      * @return An Ipv4Prefix object
180      * @throws IllegalArgumentException if addr is not an Inet4Address or if mask is not in range 0-32
181      * @throws NullPointerException if addr is null
182      */
183     @Nonnull public final P4 ipv4PrefixFor(@Nonnull final InetAddress addr, final int mask) {
184         Preconditions.checkNotNull(addr, "Address must not be null");
185         Preconditions.checkArgument(addr instanceof Inet4Address, "Address has to be an Inet4Address");
186         Preconditions.checkArgument(mask >= 0 && mask <= 32, "Invalid mask %s", mask);
187         return prefix4Factory.newInstance(addr.getHostAddress() + '/' + mask);
188     }
189
190     @Nonnull public final P4 ipv4PrefixFor(@Nonnull final A4 addr) {
191         Preconditions.checkNotNull(addr, "Address must not be null");
192         return prefix4Factory.newInstance(ipv4AddressString(addr) + "/32");
193     }
194
195     @Nonnull public final P4 ipv4PrefixFor(@Nonnull final A4 addr, final int mask) {
196         Preconditions.checkNotNull(addr, "Address must not be null");
197         Preconditions.checkArgument(mask >= 0 && mask <= 32, "Invalid mask %s", mask);
198         return prefix4Factory.newInstance(ipv4AddressString(addr) + '/' + mask);
199     }
200
201     @Nonnull public final Entry<A4, Integer> splitIpv4Prefix(@Nonnull final P4 prefix) {
202         return splitPrefix(address4Factory, ipv4PrefixString(prefix));
203     }
204
205     @Nonnull public final byte[] ipv4PrefixToBytes(@Nonnull final P4 prefix) {
206         final String str = ipv4PrefixString(prefix);
207         final int slash = str.lastIndexOf('/');
208
209         final byte[] bytes = new byte[INET4_LENGTH + 1];
210         Ipv4Utils.fillIpv4Bytes(bytes, 0, str, 0, slash);
211         bytes[INET4_LENGTH] = (byte)Integer.parseInt(str.substring(slash + 1), 10);
212         return bytes;
213     }
214
215     /**
216      * Create an Ipv6Address by interpreting input bytes as an IPv6 address.
217      *
218      * @param bytes 16-byte array
219      * @return An Ipv6Address object
220      * @throws IllegalArgumentException if bytes has length different from 16
221      * @throws NullPointerException if bytes is null
222      */
223     @Nonnull public final A6 ipv6AddressFor(@Nonnull final byte[] bytes) {
224         return address6Factory.newInstance(addressStringV6(bytes));
225     }
226
227     /**
228      * Create an Ipv6Address by interpreting an {@link Inet6Address}.
229      *
230      * @param addr An {@link Inet6Address}
231      * @return An Ipv6Address object
232      * @throws IllegalArgumentException if addr is not an {@link Inet6Address}
233      * @throws NullPointerException if addr is null
234      */
235     @Nonnull public final A6 ipv6AddressFor(@Nonnull final InetAddress addr) {
236         Preconditions.checkNotNull(addr, "Address must not be null");
237         Preconditions.checkArgument(addr instanceof Inet6Address, "Address has to be an Inet6Address");
238         return address6Factory.newInstance(addressStringV6(addr));
239     }
240
241     @Nonnull public final A6 ipv6AddressFrom(@Nonnull final P6 prefix) {
242         return prefixToAddress(address6Factory, ipv6PrefixString(prefix));
243     }
244
245     @Nonnull public final byte[] ipv6AddressBytes(@Nonnull final A6 addr) {
246         String str = ipv6AddressString(addr);
247         final int percent = str.indexOf('%');
248         if (percent != -1) {
249             str = str.substring(0, percent);
250         }
251
252         return InetAddresses.forString(str).getAddress();
253     }
254
255     /**
256      * Create a /128 Ipv6Prefix by interpreting input bytes as an IPv6 address.
257      *
258      * @param bytes four-byte array
259      * @return An Ipv6Prefix object
260      * @throws IllegalArgumentException if bytes has length different from 16
261      * @throws NullPointerException if bytes is null
262      */
263     @Nonnull public final P6 ipv6PrefixFor(@Nonnull final byte[] bytes) {
264         return prefix6Factory.newInstance(addressStringV6(bytes) + "/128");
265     }
266
267     /**
268      * Create a Ipv6Prefix by combining the address with a mask. The address
269      * bytes are interpreted as an address and the specified mask is concatenated to
270      * it. The address bytes are not masked.
271      *
272      * @param address Input address as a 4-byte array
273      * @param mask Prefix mask
274      * @return An Ipv6Prefix object
275      * @throws IllegalArgumentException if bytes has length different from 16 or if mask is not in range 0-128
276      * @throws NullPointerException if bytes is null
277      */
278     @Nonnull public final P6 ipv6PrefixFor(@Nonnull final byte[] address, final int mask) {
279         Preconditions.checkArgument(mask >= 0 && mask <= 128, "Invalid mask %s", mask);
280         return prefix6Factory.newInstance(addressStringV6(address) + '/' + mask);
281     }
282
283     @Nonnull public final P6 ipv6PrefixForShort(@Nonnull final byte[] address, final int mask) {
284         return ipv6PrefixForShort(address, 0, mask);
285     }
286
287     @Nonnull public final P6 ipv6PrefixForShort(@Nonnull final byte[] array, final int startOffset, final int mask) {
288         if (mask == 0) {
289             // Easy case, reuse the template
290             return prefix6Factory.getTemplate();
291         }
292
293         Preconditions.checkArgument(mask > 0 && mask <= 128, "Invalid mask %s", mask);
294         final int size = (mask / Byte.SIZE) + ((mask % Byte.SIZE == 0) ? 0 : 1);
295
296         // Until we can instantiate an IPv6 address for a partial array, use a temporary buffer
297         byte[] tmp = new byte[INET6_LENGTH];
298         System.arraycopy(array, startOffset, tmp, 0, size);
299         return ipv6PrefixFor(tmp, mask);
300     }
301
302     /**
303      * Create a /128 Ipv6Prefix by interpreting input bytes as an IPv4 address.
304      *
305      * @param addr an {@link Inet6Address}
306      * @return An Ipv6Prefix object
307      * @throws IllegalArgumentException if addr is not an Inet6Address or if mask is not in range 0-128
308      * @throws NullPointerException if addr is null
309      */
310     @Nonnull public final P6 ipv6PrefixFor(@Nonnull final InetAddress addr) {
311         return prefix6Factory.newInstance(addressStringV6(addr) + "/128");
312     }
313
314     /**
315      * Create a Ipv6Prefix by combining the address with a mask. The address
316      * bytes are interpreted as an address and the specified mask is concatenated to
317      * it. The address bytes are not masked.
318      *
319      * @param addr Input address
320      * @param mask Prefix mask
321      * @return An Ipv6Prefix object
322      * @throws IllegalArgumentException if addr is not an Inet6Address or if mask is not in range 0-128
323      * @throws NullPointerException if addr is null
324      */
325     @Nonnull public final P6 ipv6PrefixFor(@Nonnull final InetAddress addr, final int mask) {
326         Preconditions.checkNotNull(addr, "Address must not be null");
327         Preconditions.checkArgument(addr instanceof Inet6Address, "Address has to be an Inet6Address");
328         Preconditions.checkArgument(mask >= 0 && mask <= 128, "Invalid mask %s", mask);
329         return prefix6Factory.newInstance(addressStringV6(addr) + '/' + mask);
330     }
331
332     @Nonnull public final P6 ipv6PrefixFor(@Nonnull final A6 addr) {
333         Preconditions.checkNotNull(addr, "Address must not be null");
334         return prefix6Factory.newInstance(ipv6AddressString(addr) + "/128");
335     }
336
337     @Nonnull public final P6 ipv6PrefixFor(@Nonnull final A6 addr, final int mask) {
338         Preconditions.checkNotNull(addr, "Address must not be null");
339         Preconditions.checkArgument(mask >= 0 && mask <= 128, "Invalid mask %s", mask);
340         return prefix6Factory.newInstance(ipv6AddressString(addr) + '/' + mask);
341     }
342
343     @Nonnull public final Entry<A6, Integer> splitIpv6Prefix(@Nonnull final P6 prefix) {
344         return splitPrefix(address6Factory, ipv6PrefixString(prefix));
345     }
346
347     private static <T> T prefixToAddress(final StringValueObjectFactory<T> factory, final String str) {
348         return factory.newInstance(str.substring(0, str.lastIndexOf('/')));
349     }
350
351     private static <T> Entry<T, Integer> splitPrefix(final StringValueObjectFactory<T> factory, final String str) {
352         final int slash = str.lastIndexOf('/');
353         return new SimpleImmutableEntry<>(factory.newInstance(str.substring(0, slash)),
354                 Integer.valueOf(str.substring(slash + 1)));
355     }
356
357     @Nonnull public final byte[] ipv6PrefixToBytes(@Nonnull final P6 prefix) {
358         final String str = ipv6PrefixString(prefix);
359         final int slash = str.lastIndexOf('/');
360
361         final byte[] bytes = new byte[INET6_LENGTH + 1];
362         System.arraycopy(InetAddresses.forString(str.substring(0, slash)).getAddress(), 0, bytes, 0, INET6_LENGTH);
363         bytes[INET6_LENGTH] = (byte)Integer.parseInt(str.substring(slash + 1), 10);
364         return bytes;
365     }
366
367     private static void appendIpv4String(final StringBuilder sb, final byte[] bytes) {
368         Preconditions.checkArgument(bytes.length == INET4_LENGTH, "IPv4 address length is 4 bytes");
369
370         sb.append(UnsignedBytes.toInt(bytes[0]));
371         for (int i = 1; i < INET4_LENGTH; ++i) {
372             sb.append('.');
373             sb.append(UnsignedBytes.toInt(bytes[i]));
374         }
375     }
376
377     private static String addressStringV4(final byte[] bytes) {
378         final StringBuilder sb = new StringBuilder(15);
379         appendIpv4String(sb, bytes);
380         return sb.toString();
381     }
382
383     private static String addressStringV6(final byte[] bytes) {
384         Preconditions.checkArgument(bytes.length == INET6_LENGTH, "IPv6 address length is 16 bytes");
385
386         try {
387             return addressStringV6(Inet6Address.getByAddress(bytes));
388         } catch (UnknownHostException e) {
389             throw new IllegalArgumentException(String.format("Invalid input %s", bytes), e);
390         }
391     }
392
393     private static String addressStringV6(final InetAddress addr) {
394         return InetAddresses.toAddrString(addr);
395     }
396
397     private static String prefixStringV4(final byte[] bytes) {
398         final StringBuilder sb = new StringBuilder(18);
399         appendIpv4String(sb, bytes);
400         sb.append("/32");
401         return sb.toString();
402     }
403
404     private static String prefixStringV4(final byte[] bytes, final int mask) {
405         Preconditions.checkArgument(mask >= 0 && mask <= 32, "Invalid mask %s", mask);
406
407         final StringBuilder sb = new StringBuilder(18);
408         appendIpv4String(sb, bytes);
409         sb.append('/');
410         sb.append(mask);
411         return sb.toString();
412     }
413
414     private P4 v4PrefixForShort(@Nonnull final byte[] array, final int startOffset, final int size, final int mask) {
415         if (startOffset == 0 && size == INET4_LENGTH && array.length == INET4_LENGTH) {
416             // Easy case, fall back to non-short
417             return ipv4PrefixFor(array, mask);
418         }
419
420         final StringBuilder sb = new StringBuilder(18);
421
422         // Add from address
423         sb.append(UnsignedBytes.toInt(array[startOffset]));
424         for (int i = 1; i < size; i++) {
425             sb.append('.');
426             sb.append(UnsignedBytes.toInt(array[startOffset + i]));
427         }
428
429         // Add zeros
430         for (int i = size; i < INET4_LENGTH; i++) {
431             sb.append(".0");
432         }
433
434         // Add mask
435         Preconditions.checkArgument(mask > 0 && mask <= 32, "Invalid mask %s", mask);
436         sb.append('/');
437         sb.append(mask);
438
439         return prefix4Factory.newInstance(sb.toString());
440     }
441 }