BUG-3225 : fix NPE
[bgpcep.git] / bgp / rib-impl / src / main / java / org / opendaylight / protocol / bgp / rib / impl / AbstractPeerRoleTracker.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.Optional;
11 import javax.annotation.Nonnull;
12 import javax.annotation.Nullable;
13 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.PeerRole;
14 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.bgp.rib.rib.Peer;
15 import org.opendaylight.yangtools.yang.binding.BindingMapping;
16 import org.opendaylight.yangtools.yang.common.QName;
17 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
18 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
19 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
20 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
21 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidateNode;
22 import org.slf4j.Logger;
23 import org.slf4j.LoggerFactory;
24
25 /**
26  * Maintains the mapping of PeerId -> Role. Subclasses get notified of changes and can do their
27  * own thing.
28  */
29 abstract class AbstractPeerRoleTracker {
30
31     private static final Logger LOG = LoggerFactory.getLogger(AbstractPeerRoleTracker.class);
32
33     public void onDataTreeChanged(final DataTreeCandidateNode change, final YangInstanceIdentifier peerPath) {
34         LOG.debug("Data Changed for Peer role {} path {}", change, peerPath);
35
36         // Check for removal
37         final Optional<NormalizedNode<?, ?>> maybePeerRole = change.getDataAfter();
38         final PeerRole role;
39         if (maybePeerRole.isPresent()) {
40             final LeafNode<?> peerRoleLeaf = (LeafNode<?>) maybePeerRole.get();
41             // We could go for a codec, but this is simpler and faster
42             role = PeerRole.valueOf(BindingMapping.getClassName((String) peerRoleLeaf.getValue()));
43         } else {
44             role = null;
45         }
46         peerRoleChanged(peerPath, role);
47     }
48
49     static final NodeIdentifier PEER_ROLE_NID = new NodeIdentifier(QName.cachedReference(QName.create(Peer.QNAME, "peer-role")));
50
51     protected AbstractPeerRoleTracker() {
52     }
53
54     /**
55      * Invoked whenever a peer role changes.
56      *
57      * @param peerPath Peer's path
58      * @param role Peer's new role, null indicates the peer has disappeared.
59      */
60     protected abstract void peerRoleChanged(@Nonnull YangInstanceIdentifier peerPath, @Nullable PeerRole role);
61 }