Merge "BUG-2982 : moved path-attributes container to grouping"
[bgpcep.git] / bgp / rib-impl / src / main / java / org / opendaylight / protocol / bgp / rib / impl / RouterIds.java
1 /*
2  * Copyright (c) 2015 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.protocol.bgp.rib.impl;
9
10 import com.google.common.base.Preconditions;
11 import com.google.common.cache.CacheBuilder;
12 import com.google.common.cache.CacheLoader;
13 import com.google.common.cache.LoadingCache;
14 import com.google.common.net.InetAddresses;
15 import com.google.common.primitives.UnsignedInteger;
16 import javax.annotation.Nonnull;
17 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Ipv4Address;
18 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.PeerId;
19
20 final class RouterIds {
21     private static final LoadingCache<String, UnsignedInteger> ROUTER_IDS = CacheBuilder.newBuilder().weakValues().build(new CacheLoader<String, UnsignedInteger>() {
22         @Override
23         public UnsignedInteger load(final String key) {
24             return UnsignedInteger.fromIntBits(InetAddresses.coerceToInteger(InetAddresses.forString(key)));
25         }
26     });
27     private static final LoadingCache<PeerId, UnsignedInteger> BGP_ROUTER_IDS = CacheBuilder.newBuilder().weakValues().build(new CacheLoader<PeerId, UnsignedInteger>() {
28         @Override
29         public UnsignedInteger load(final PeerId key) {
30             return routerIdForAddress(key.getValue().substring(BGP_PREFIX.length()));
31         }
32     });
33     private static final String BGP_PREFIX = "bgp://";
34
35     private RouterIds() {
36         throw new UnsupportedOperationException();
37     }
38
39     /**
40      * Get a router ID in unsigned integer format from an Ipv4Address. This implementation uses an internal
41      * cache, so the objects can be expected to perform quickly when compared with equals and similar.
42      *
43      * @param address Router ID as a dotted-quad
44      * @return Router ID as an {@link UnsignedInteger}
45      */
46     public static UnsignedInteger routerIdForAddress(@Nonnull final String address) {
47         return ROUTER_IDS.getUnchecked(address);
48     }
49
50     public static UnsignedInteger routerIdForPeerId(@Nonnull final PeerId peerId) {
51         Preconditions.checkArgument(peerId.getValue().startsWith(BGP_PREFIX), "Unhandled peer ID %s", peerId);
52         return BGP_ROUTER_IDS.getUnchecked(peerId);
53     }
54
55     public static PeerId createPeerId(@Nonnull final Ipv4Address address) {
56         return new PeerId(BGP_PREFIX + address.getValue());
57     }
58 }