Use YANG java files instead of the old model TELSDN-474 #close
[lispflowmapping.git] / mappingservice / implementation / src / main / java / org / opendaylight / lispflowmapping / implementation / util / MaskUtil.java
1 package org.opendaylight.lispflowmapping.implementation.util;
2
3 import java.net.Inet4Address;
4 import java.net.Inet6Address;
5 import java.net.InetAddress;
6 import java.net.UnknownHostException;
7 import java.nio.ByteBuffer;
8
9 import org.opendaylight.lispflowmapping.implementation.serializer.LispAFIConvertor;
10 import org.opendaylight.yang.gen.v1.lispflowmapping.rev131031.LispIpv4Address;
11 import org.opendaylight.yang.gen.v1.lispflowmapping.rev131031.LispIpv6Address;
12 import org.opendaylight.yang.gen.v1.lispflowmapping.rev131031.lispaddress.lispaddresscontainer.Address;
13
14 public class MaskUtil {
15
16     public static boolean isMaskable(Address address) {
17         if (address instanceof LispIpv4Address || address instanceof LispIpv6Address) {
18             return true;
19         }
20         return false;
21     }
22
23     public static Address normalize(Address address, int mask) {
24         try {
25             if (address instanceof LispIpv4Address) {
26                 return LispAFIConvertor.asIPAfiAddress(normalizeIP(Inet4Address.getByName(((LispIpv4Address) address).getIpv4Address().getValue()),
27                         mask).getHostAddress());
28             }
29             if (address instanceof LispIpv6Address) {
30                 return LispAFIConvertor.asIPv6AfiAddress(normalizeIP(Inet6Address.getByName(((LispIpv6Address) address).getIpv6Address().getValue()),
31                         mask).getHostAddress());
32             }
33
34         } catch (UnknownHostException e) {
35             return null;
36         }
37         return null;
38     }
39
40     private static InetAddress normalizeIP(InetAddress address, int mask) throws UnknownHostException {
41         ByteBuffer byteRepresentation = ByteBuffer.wrap(address.getAddress());
42         byte b = (byte) 0xff;
43         for (int i = 0; i < byteRepresentation.array().length; i++) {
44             if (mask >= 8)
45                 byteRepresentation.put(i, (byte) (b & byteRepresentation.get(i)));
46
47             else if (mask > 0) {
48                 byteRepresentation.put(i, (byte) ((byte) (b << (8 - mask)) & byteRepresentation.get(i)));
49             } else {
50                 byteRepresentation.put(i, (byte) (0 & byteRepresentation.get(i)));
51             }
52
53             mask -= 8;
54         }
55         return InetAddress.getByAddress(byteRepresentation.array());
56     }
57
58     public static int getMaxMask(Address address) {
59         if (address instanceof LispIpv4Address) {
60             return 32;
61         }
62         if (address instanceof LispIpv6Address) {
63             return 128;
64         }
65         return -1;
66     }
67
68 }