BGPCEP-754: Fix NPE and rework
[bgpcep.git] / bgp / rib-impl / src / main / java / org / opendaylight / protocol / bgp / rib / impl / BGPPeerTrackerImpl.java
1 /*
2  * Copyright (c) 2018 AT&T Intellectual Property. 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.collect.ImmutableList;
11 import java.util.HashMap;
12 import java.util.List;
13 import java.util.Map;
14 import javax.annotation.concurrent.GuardedBy;
15 import org.opendaylight.protocol.bgp.rib.spi.BGPPeerTracker;
16 import org.opendaylight.protocol.bgp.rib.spi.Peer;
17 import org.opendaylight.protocol.concepts.AbstractRegistration;
18 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev171207.PeerId;
19
20 public final class BGPPeerTrackerImpl implements BGPPeerTracker {
21     @GuardedBy("this")
22     private Map<PeerId, Peer> peers = new HashMap<>();
23     private ImmutableList<Peer> peersList;
24
25     @Override
26     public synchronized AbstractRegistration registerPeer(final Peer peer) {
27         this.peers.put(peer.getPeerId(), peer);
28         this.peersList = ImmutableList.copyOf(this.peers.values());
29         return new AbstractRegistration() {
30             @Override
31             protected void removeRegistration() {
32                 synchronized (BGPPeerTrackerImpl.this) {
33                     BGPPeerTrackerImpl.this.peers.remove(peer.getPeerId());
34                 }
35             }
36         };
37     }
38
39     @Override
40     public synchronized Peer getPeer(final PeerId peerId) {
41         return this.peers.get(peerId);
42     }
43
44     @Override
45     public synchronized List<Peer> getPeers() {
46         return this.peersList;
47     }
48 }