Use ByteBuf.readRetainedSlice()
[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 java.util.List;
12 import java.util.ListIterator;
13 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv4Address;
14 import org.opendaylight.yangtools.yang.common.Uint32;
15
16 /**
17  * IP conversion utilities.
18  *
19  * @author msunal
20  */
21 public final class IpConverter {
22     private static final Splitter SPLITTER = Splitter.on('.').trimResults().omitEmptyStrings();
23
24     private IpConverter() {
25     }
26
27     public static long ipv4AddressToLong(final Ipv4Address ipv4Address) {
28         long result = 0 ;
29         List<String> splittedAddress = SPLITTER.splitToList(ipv4Address.getValue());
30
31         int maxIndex = splittedAddress.size() - 1;
32         ListIterator<String> listIter = splittedAddress.listIterator();
33         while (listIter.hasNext()) {
34             String current = listIter.next();
35             int index = splittedAddress.indexOf(current);
36             result |= Long.parseLong(current) << (maxIndex - index) * 8;
37         }
38         return result & 0xFFFFFFFF;
39     }
40
41     public static Ipv4Address longToIpv4Address(final Uint32 ip) {
42         return longToIpv4Address(ip.toJava());
43     }
44
45     public static Ipv4Address longToIpv4Address(final long ip) {
46         long tmpIp = ip;
47         StringBuilder sb = new StringBuilder(15);
48         for (int i = 0; i < 4; i++) {
49             sb.insert(0, Long.toString(tmpIp & 0xff));
50             if (i < 3) {
51                 sb.insert(0, '.');
52             }
53             tmpIp >>= 8;
54         }
55         return new Ipv4Address(sb.toString());
56     }
57
58 }