Merge "Refactor nsh fields to new encoding"
[openflowplugin.git] / extension / openflowplugin-extension-nicira / src / main / java / org / opendaylight / openflowplugin / extension / vendor / nicira / convertor / IpConverter.java
1 /**
2  * Copyright (c) 2014 Cisco Systems, Inc. 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.openflowplugin.extension.vendor.nicira.convertor;
9
10 import com.google.common.base.Splitter;
11 import com.google.common.collect.Lists;
12 import java.util.List;
13 import java.util.ListIterator;
14 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv4Address;
15
16 /**
17  * IP conversion utilities.
18  *
19  * @author msunal
20  */
21 public final class IpConverter {
22     private IpConverter() {
23     }
24
25     public static long ipv4AddressToLong(Ipv4Address ipv4Address) {
26         long result = 0 ;
27         Iterable<String> splitted = Splitter.on('.')
28                 .trimResults()
29                 .omitEmptyStrings()
30                 .split(ipv4Address.getValue());
31
32         List<String> splittedAddress = Lists.newArrayList(splitted.iterator());
33         int maxIndex = splittedAddress.size() - 1;
34         ListIterator<String> listIter = splittedAddress.listIterator();
35         while (listIter.hasNext()) {
36             String current = listIter.next();
37             int index = splittedAddress.indexOf(current);
38             result |= Long.parseLong(current) << (maxIndex - index) * 8;
39         }
40         return result & 0xFFFFFFFF;
41     }
42
43     public static Ipv4Address longToIpv4Address(long ip) {
44         long tmpIp = ip;
45         StringBuilder sb = new StringBuilder(15);
46         for (int i = 0; i < 4; i++) {
47             sb.insert(0, Long.toString(tmpIp & 0xff));
48             if (i < 3) {
49                 sb.insert(0, '.');
50             }
51             tmpIp >>= 8;
52         }
53         return new Ipv4Address(sb.toString());
54     }
55
56 }