Merge "Drop Felix Gogo" into stable/boron
authorJozef Bacigal <jozef.bacigal@pantheon.tech>
Tue, 16 Aug 2016 11:16:19 +0000 (11:16 +0000)
committerGerrit Code Review <gerrit@opendaylight.org>
Tue, 16 Aug 2016 11:16:19 +0000 (11:16 +0000)
16 files changed:
applications/lldp-speaker/pom.xml
applications/lldp-speaker/src/main/java/org/opendaylight/openflowplugin/applications/lldpspeaker/LLDPSpeaker.java
applications/lldp-speaker/src/main/java/org/opendaylight/openflowplugin/applications/lldpspeaker/LLDPUtil.java
applications/lldp-speaker/src/main/java/org/opendaylight/openflowplugin/applications/lldpspeaker/NodeConnectorEventsObserver.java
applications/lldp-speaker/src/main/java/org/opendaylight/openflowplugin/applications/lldpspeaker/NodeConnectorInventoryEventTranslator.java
applications/lldp-speaker/src/main/java/org/opendaylight/openflowplugin/applications/lldpspeaker/OperationalStatusChangeService.java
applications/lldp-speaker/src/main/resources/org/opendaylight/blueprint/lldp-speaker.xml
applications/lldp-speaker/src/test/java/org/opendaylight/openflowplugin/applications/lldpspeaker/LLDPSpeakerTest.java
applications/lldp-speaker/src/test/java/org/opendaylight/openflowplugin/applications/lldpspeaker/NodeConnectorInventoryEventTranslatorTest.java
applications/lldp-speaker/src/test/java/org/opendaylight/openflowplugin/applications/lldpspeaker/TestUtils.java
applications/table-miss-enforcer/src/main/java/org/opendaylight/openflowplugin/applications/tableMissEnforcer/LLDPPacketPuntEnforcer.java
applications/table-miss-enforcer/src/main/resources/org/opendaylight/blueprint/table-miss-enforcer.xml
applications/table-miss-enforcer/src/test/java/org/opendaylight/openflowplugin/applications/tableMissEnforcer/LLDPDataChangeListenerTest.java
applications/topology-lldp-discovery/src/main/java/org/opendaylight/openflowplugin/applications/topology/lldp/LLDPDiscoveryListener.java
distribution/karaf/pom.xml
model/pom.xml

index 8977cf3c4751f4cce8d84c96881dbe712a4e7b39..d1c10e9de5a5c219d909bab17813fdf0fac5fdaa 100644 (file)
             <groupId>org.opendaylight.openflowplugin.model</groupId>
             <artifactId>model-flow-service</artifactId>
         </dependency>
+        <dependency>
+            <groupId>org.opendaylight.openflowplugin</groupId>
+            <artifactId>openflowplugin-common</artifactId>
+        </dependency>
         <dependency>
             <groupId>org.opendaylight.controller</groupId>
             <artifactId>config-api</artifactId>
index a7854072167122dd46442d1bd3dd7d3391e453f3..5c0f71fe923e4f6a72faa032998a6952da9a4b19 100644 (file)
@@ -34,24 +34,20 @@ import org.slf4j.LoggerFactory;
  * Objects of this class send LLDP frames over all flow-capable ports that can
  * be discovered through inventory.
  */
-public class LLDPSpeaker implements AutoCloseable, NodeConnectorEventsObserver,
-        Runnable {
-
-    private static final Logger LOG = LoggerFactory
-            .getLogger(LLDPSpeaker.class);
+public class LLDPSpeaker implements AutoCloseable, NodeConnectorEventsObserver, Runnable {
+    private static final Logger LOG = LoggerFactory.getLogger(LLDPSpeaker.class);
     private static final long LLDP_FLOOD_PERIOD = 5;
 
     private final PacketProcessingService packetProcessingService;
     private final ScheduledExecutorService scheduledExecutorService;
-    private final Map<InstanceIdentifier<NodeConnector>, TransmitPacketInput> nodeConnectorMap = new ConcurrentHashMap<>();
+    private final Map<InstanceIdentifier<NodeConnector>, TransmitPacketInput> nodeConnectorMap =
+            new ConcurrentHashMap<>();
     private final ScheduledFuture<?> scheduledSpeakerTask;
     private final MacAddress addressDestionation;
     private volatile OperStatus operationalStatus = OperStatus.RUN;
 
-    public LLDPSpeaker(final PacketProcessingService packetProcessingService,
-            final MacAddress addressDestionation) {
-        this(packetProcessingService, Executors
-                .newSingleThreadScheduledExecutor(), addressDestionation);
+    public LLDPSpeaker(final PacketProcessingService packetProcessingService, final MacAddress addressDestionation) {
+        this(packetProcessingService, Executors.newSingleThreadScheduledExecutor(), addressDestionation);
     }
 
     public void setOperationalStatus(final OperStatus operationalStatus) {
@@ -67,17 +63,14 @@ public class LLDPSpeaker implements AutoCloseable, NodeConnectorEventsObserver,
     }
 
     public LLDPSpeaker(final PacketProcessingService packetProcessingService,
-            final ScheduledExecutorService scheduledExecutorService,
-            final MacAddress addressDestionation) {
+                       final ScheduledExecutorService scheduledExecutorService,
+                       final MacAddress addressDestionation) {
         this.addressDestionation = addressDestionation;
         this.scheduledExecutorService = scheduledExecutorService;
         scheduledSpeakerTask = this.scheduledExecutorService
-                .scheduleAtFixedRate(this, LLDP_FLOOD_PERIOD,
-                        LLDP_FLOOD_PERIOD, TimeUnit.SECONDS);
+                .scheduleAtFixedRate(this, LLDP_FLOOD_PERIOD,LLDP_FLOOD_PERIOD, TimeUnit.SECONDS);
         this.packetProcessingService = packetProcessingService;
-        LOG.info(
-                "LLDPSpeaker started, it will send LLDP frames each {} seconds",
-                LLDP_FLOOD_PERIOD);
+        LOG.info("LLDPSpeaker started, it will send LLDP frames each {} seconds", LLDP_FLOOD_PERIOD);
     }
 
     /**
@@ -97,17 +90,11 @@ public class LLDPSpeaker implements AutoCloseable, NodeConnectorEventsObserver,
     @Override
     public void run() {
         if (OperStatus.RUN.equals(operationalStatus)) {
-            LOG.debug("Sending LLDP frames to {} ports...", nodeConnectorMap
-                    .keySet().size());
-
-            for (InstanceIdentifier<NodeConnector> nodeConnectorInstanceId : nodeConnectorMap
-                    .keySet()) {
-                NodeConnectorId nodeConnectorId = InstanceIdentifier.keyOf(
-                        nodeConnectorInstanceId).getId();
-                LOG.trace("Sending LLDP through port {}",
-                        nodeConnectorId.getValue());
-                packetProcessingService.transmitPacket(nodeConnectorMap
-                        .get(nodeConnectorInstanceId));
+            LOG.debug("Sending LLDP frames to {} ports...", nodeConnectorMap.keySet().size());
+            for (InstanceIdentifier<NodeConnector> nodeConnectorInstanceId : nodeConnectorMap.keySet()) {
+                NodeConnectorId nodeConnectorId = InstanceIdentifier.keyOf(nodeConnectorInstanceId).getId();
+                LOG.trace("Sending LLDP through port {}", nodeConnectorId.getValue());
+                packetProcessingService.transmitPacket(nodeConnectorMap.get(nodeConnectorInstanceId));
             }
         }
     }
@@ -116,11 +103,9 @@ public class LLDPSpeaker implements AutoCloseable, NodeConnectorEventsObserver,
      * {@inheritDoc}
      */
     @Override
-    public void nodeConnectorAdded(
-            final InstanceIdentifier<NodeConnector> nodeConnectorInstanceId,
-            final FlowCapableNodeConnector flowConnector) {
-        NodeConnectorId nodeConnectorId = InstanceIdentifier.keyOf(
-                nodeConnectorInstanceId).getId();
+    public void nodeConnectorAdded(final InstanceIdentifier<NodeConnector> nodeConnectorInstanceId,
+                                   final FlowCapableNodeConnector flowConnector) {
+        NodeConnectorId nodeConnectorId = InstanceIdentifier.keyOf(nodeConnectorInstanceId).getId();
 
         // nodeConnectorAdded can be called even if we already sending LLDP
         // frames to
@@ -133,16 +118,14 @@ public class LLDPSpeaker implements AutoCloseable, NodeConnectorEventsObserver,
         }
 
         // Prepare to build LLDP payload
-        InstanceIdentifier<Node> nodeInstanceId = nodeConnectorInstanceId
-                .firstIdentifierOf(Node.class);
+        InstanceIdentifier<Node> nodeInstanceId = nodeConnectorInstanceId.firstIdentifierOf(Node.class);
         NodeId nodeId = InstanceIdentifier.keyOf(nodeInstanceId).getId();
         MacAddress srcMacAddress = flowConnector.getHardwareAddress();
         Long outputPortNo = flowConnector.getPortNumber().getUint32();
 
         // No need to send LLDP frames on local ports
         if (outputPortNo == null) {
-            LOG.trace("Port {} is local, not sending LLDP frames through it",
-                    nodeConnectorId.getValue());
+            LOG.trace("Port {} is local, not sending LLDP frames through it", nodeConnectorId.getValue());
             return;
         }
 
@@ -150,16 +133,14 @@ public class LLDPSpeaker implements AutoCloseable, NodeConnectorEventsObserver,
         TransmitPacketInput packet = new TransmitPacketInputBuilder()
                 .setEgress(new NodeConnectorRef(nodeConnectorInstanceId))
                 .setNode(new NodeRef(nodeInstanceId))
-                .setPayload(
-                        LLDPUtil.buildLldpFrame(nodeId, nodeConnectorId,
-                                srcMacAddress, outputPortNo,
-                                addressDestionation)).build();
+                .setPayload(LLDPUtil
+                        .buildLldpFrame(nodeId, nodeConnectorId, srcMacAddress, outputPortNo, addressDestionation))
+                .build();
 
         // Save packet to node connector id -> packet map to transmit it every 5
         // seconds
         nodeConnectorMap.put(nodeConnectorInstanceId, packet);
-        LOG.trace("Port {} added to LLDPSpeaker.nodeConnectorMap",
-                nodeConnectorId.getValue());
+        LOG.trace("Port {} added to LLDPSpeaker.nodeConnectorMap", nodeConnectorId.getValue());
 
         // Transmit packet for first time immediately
         packetProcessingService.transmitPacket(packet);
@@ -169,12 +150,10 @@ public class LLDPSpeaker implements AutoCloseable, NodeConnectorEventsObserver,
      * {@inheritDoc}
      */
     @Override
-    public void nodeConnectorRemoved(
-            final InstanceIdentifier<NodeConnector> nodeConnectorInstanceId) {
+    public void nodeConnectorRemoved(final InstanceIdentifier<NodeConnector> nodeConnectorInstanceId) {
         nodeConnectorMap.remove(nodeConnectorInstanceId);
-        NodeConnectorId nodeConnectorId = InstanceIdentifier.keyOf(
-                nodeConnectorInstanceId).getId();
-        LOG.trace("Port {} removed from LLDPSpeaker.nodeConnectorMap",
-                nodeConnectorId.getValue());
+        NodeConnectorId nodeConnectorId = InstanceIdentifier.keyOf(nodeConnectorInstanceId).getId();
+        LOG.trace("Port {} removed from LLDPSpeaker.nodeConnectorMap", nodeConnectorId.getValue());
     }
+
 }
index af7703ea6376772cabf96b9bdcef5226449b0518..163d1c922a99c29d9f83c569486400db46909edd 100644 (file)
@@ -10,6 +10,7 @@ package org.opendaylight.openflowplugin.applications.lldpspeaker;
 
 import static org.opendaylight.controller.liblldp.LLDPTLV.CUSTOM_TLV_SUB_TYPE_CUSTOM_SEC;
 import static org.opendaylight.openflowplugin.applications.topology.lldp.utils.LLDPDiscoveryUtils.getValueForLLDPPacketIntegrityEnsuring;
+
 import java.math.BigInteger;
 import java.security.NoSuchAlgorithmException;
 import org.apache.commons.lang3.StringUtils;
@@ -33,19 +34,21 @@ public final class LLDPUtil {
     private static final String OF_URI_PREFIX = "openflow:";
 
     static byte[] buildLldpFrame(final NodeId nodeId,
-            final NodeConnectorId nodeConnectorId, final MacAddress src, final Long outPortNo,
-            final MacAddress destinationAddress) {
+                                 final NodeConnectorId nodeConnectorId,
+                                 final MacAddress src,
+                                 final Long outPortNo,
+                                 final MacAddress destinationAddress) {
         // Create discovery pkt
         LLDP discoveryPkt = new LLDP();
 
         // Create LLDP ChassisID TLV
         BigInteger dataPathId = dataPathIdFromNodeId(nodeId);
-        byte[] cidValue = LLDPTLV
-                .createChassisIDTLVValue(colonize(bigIntegerToPaddedHex(dataPathId)));
+        byte[] cidValue = LLDPTLV.createChassisIDTLVValue(colonize(bigIntegerToPaddedHex(dataPathId)));
         LLDPTLV chassisIdTlv = new LLDPTLV();
         chassisIdTlv.setType(LLDPTLV.TLVType.ChassisID.getValue());
         chassisIdTlv.setType(LLDPTLV.TLVType.ChassisID.getValue())
-                .setLength((short) cidValue.length).setValue(cidValue);
+                    .setLength((short) cidValue.length)
+                    .setValue(cidValue);
         discoveryPkt.setChassisId(chassisIdTlv);
 
         // Create LLDP PortID TL
@@ -53,15 +56,15 @@ public final class LLDPUtil {
         byte[] pidValue = LLDPTLV.createPortIDTLVValue(hexString);
         LLDPTLV portIdTlv = new LLDPTLV();
         portIdTlv.setType(LLDPTLV.TLVType.PortID.getValue())
-                .setLength((short) pidValue.length).setValue(pidValue);
+                 .setLength((short) pidValue.length)
+                 .setValue(pidValue);
         portIdTlv.setType(LLDPTLV.TLVType.PortID.getValue());
         discoveryPkt.setPortId(portIdTlv);
 
         // Create LLDP TTL TLV
         byte[] ttl = new byte[] { (byte) 0x13, (byte) 0x37 };
         LLDPTLV ttlTlv = new LLDPTLV();
-        ttlTlv.setType(LLDPTLV.TLVType.TTL.getValue())
-                .setLength((short) ttl.length).setValue(ttl);
+        ttlTlv.setType(LLDPTLV.TLVType.TTL.getValue()).setLength((short) ttl.length).setValue(ttl);
         discoveryPkt.setTtl(ttlTlv);
 
         // Create LLDP SystemName TLV
@@ -69,15 +72,16 @@ public final class LLDPUtil {
         LLDPTLV systemNameTlv = new LLDPTLV();
         systemNameTlv.setType(LLDPTLV.TLVType.SystemName.getValue());
         systemNameTlv.setType(LLDPTLV.TLVType.SystemName.getValue())
-                .setLength((short) snValue.length).setValue(snValue);
+                     .setLength((short) snValue.length)
+                     .setValue(snValue);
         discoveryPkt.setSystemNameId(systemNameTlv);
 
         // Create LLDP Custom TLV
-        byte[] customValue = LLDPTLV.createCustomTLVValue(nodeConnectorId
-                .getValue());
+        byte[] customValue = LLDPTLV.createCustomTLVValue(nodeConnectorId.getValue());
         LLDPTLV customTlv = new LLDPTLV();
         customTlv.setType(LLDPTLV.TLVType.Custom.getValue())
-                .setLength((short) customValue.length).setValue(customValue);
+                 .setLength((short) customValue.length)
+                 .setValue(customValue);
         discoveryPkt.addCustomTLV(customTlv);
 
         //Create LLDP CustomSec TLV
@@ -87,8 +91,8 @@ public final class LLDPUtil {
             byte[] customSecValue = LLDPTLV.createCustomTLVValue(CUSTOM_TLV_SUB_TYPE_CUSTOM_SEC, pureValue);
             LLDPTLV customSecTlv = new LLDPTLV();
             customSecTlv.setType(LLDPTLV.TLVType.Custom.getValue())
-            .setLength((short)customSecValue.length)
-            .setValue(customSecValue);
+                        .setLength((short)customSecValue.length)
+                        .setValue(customSecValue);
             discoveryPkt.addCustomTLV(customSecTlv);
         } catch (NoSuchAlgorithmException e1) {
             LOG.info("LLDP extra authenticator creation failed: {}", e1.getMessage());
@@ -100,13 +104,12 @@ public final class LLDPUtil {
         byte[] sourceMac = HexEncode.bytesFromHexString(src.getValue());
         Ethernet ethPkt = new Ethernet();
         ethPkt.setSourceMACAddress(sourceMac)
-                .setEtherType(EtherTypes.LLDP.shortValue())
-                .setPayload(discoveryPkt);
+              .setEtherType(EtherTypes.LLDP.shortValue())
+              .setPayload(discoveryPkt);
         if (destinationAddress == null) {
             ethPkt.setDestinationMACAddress(LLDP.LLDPMulticastMac);
         } else {
-            ethPkt.setDestinationMACAddress(HexEncode
-                    .bytesFromHexString(destinationAddress.getValue()));
+            ethPkt.setDestinationMACAddress(HexEncode.bytesFromHexString(destinationAddress.getValue()));
         }
 
         try {
@@ -132,9 +135,9 @@ public final class LLDPUtil {
     }
 
     static byte[] buildLldpFrame(final NodeId nodeId,
-            final NodeConnectorId nodeConnectorId, final MacAddress srcMacAddress,
-            final Long outputPortNo) {
-        return buildLldpFrame(nodeId, nodeConnectorId, srcMacAddress,
-                outputPortNo, null);
+                                 final NodeConnectorId nodeConnectorId,
+                                 final MacAddress srcMacAddress,
+                                 final Long outputPortNo) {
+        return buildLldpFrame(nodeId, nodeConnectorId, srcMacAddress, outputPortNo, null);
     }
 }
index 490cf6ad2800cd9113fd13cf7f6adcee6161416c..665f36dcd2ff9132e0021f73ae927e2fe22b60b1 100644 (file)
@@ -25,7 +25,7 @@ public interface NodeConnectorEventsObserver {
      * @param nodeConnectorInstanceId Object that uniquely identify added node connector
      * @param flowConnector object containing almost all of details about node connector
      */
-    public void nodeConnectorAdded(InstanceIdentifier<NodeConnector> nodeConnectorInstanceId,
+    void nodeConnectorAdded(InstanceIdentifier<NodeConnector> nodeConnectorInstanceId,
                                    FlowCapableNodeConnector flowConnector);
 
     /**
@@ -34,5 +34,5 @@ public interface NodeConnectorEventsObserver {
      * the same removal event.
      * @param nodeConnectorInstanceId Object that uniquely identify added node connector
      */
-    public void nodeConnectorRemoved(InstanceIdentifier<NodeConnector> nodeConnectorInstanceId);
+    void nodeConnectorRemoved(InstanceIdentifier<NodeConnector> nodeConnectorInstanceId);
 }
index 71b3b3e6ce7c6c909e238e7b6fb77c16397aaa76..835dc97e5140ed0628cd3af2040db8b1b2bf73ad 100644 (file)
@@ -8,22 +8,25 @@
 
 package org.opendaylight.openflowplugin.applications.lldpspeaker;
 
+import com.google.common.collect.ImmutableSet;
 import com.google.common.collect.Iterables;
-
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNodeConnectorBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.port.rev130925.flow.capable.port.State;
+import java.util.Collection;
 import java.util.HashMap;
-import com.google.common.collect.ImmutableSet;
 import java.util.Map;
 import java.util.Set;
+import java.util.concurrent.Callable;
+import javax.annotation.Nonnull;
 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.controller.md.sal.binding.api.DataChangeListener;
-import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker;
-import org.opendaylight.controller.md.sal.common.api.data.AsyncDataChangeEvent;
+import org.opendaylight.controller.md.sal.binding.api.DataTreeChangeListener;
+import org.opendaylight.controller.md.sal.binding.api.DataTreeIdentifier;
+import org.opendaylight.controller.md.sal.binding.api.DataTreeModification;
 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
+import org.opendaylight.openflowplugin.common.wait.SimpleTaskRetryLooper;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNodeConnector;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNodeConnectorBuilder;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.port.rev130925.PortConfig;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.port.rev130925.PortState;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.port.rev130925.flow.capable.port.State;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.Nodes;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.node.NodeConnector;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
@@ -33,16 +36,14 @@ import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-
 /**
  * NodeConnectorInventoryEventTranslator is listening for changes in inventory operational DOM tree
  * and update LLDPSpeaker and topology.
  */
-public class NodeConnectorInventoryEventTranslator implements DataChangeListener, AutoCloseable {
-    /**
-     *
-     */
-    private static final InstanceIdentifier<State> II_TO_STATE 
+public class NodeConnectorInventoryEventTranslator<T extends DataObject>
+        implements DataTreeChangeListener<T>, AutoCloseable {
+
+    private static final InstanceIdentifier<State> II_TO_STATE
         = InstanceIdentifier.builder(Nodes.class)
             .child(Node.class)
             .child(NodeConnector.class)
@@ -57,111 +58,141 @@ public class NodeConnectorInventoryEventTranslator implements DataChangeListener
             .augmentation(FlowCapableNodeConnector.class)
             .build();
 
+    private static final long STARTUP_LOOP_TICK = 500L;
+    private static final int STARTUP_LOOP_MAX_RETRIES = 8;
     private static final Logger LOG = LoggerFactory.getLogger(NodeConnectorInventoryEventTranslator.class);
 
-    private final ListenerRegistration<DataChangeListener> dataChangeListenerRegistration;
-    private final ListenerRegistration<DataChangeListener> listenerOnPortStateRegistration;
+    private final ListenerRegistration<DataTreeChangeListener> dataChangeListenerRegistration;
+    private final ListenerRegistration<DataTreeChangeListener> listenerOnPortStateRegistration;
     private final Set<NodeConnectorEventsObserver> observers;
     private final Map<InstanceIdentifier<?>,FlowCapableNodeConnector> iiToDownFlowCapableNodeConnectors = new HashMap<>();
 
     public NodeConnectorInventoryEventTranslator(DataBroker dataBroker, NodeConnectorEventsObserver... observers) {
         this.observers = ImmutableSet.copyOf(observers);
-        dataChangeListenerRegistration = dataBroker.registerDataChangeListener(
-                LogicalDatastoreType.OPERATIONAL,
-                II_TO_FLOW_CAPABLE_NODE_CONNECTOR,
-                this, AsyncDataBroker.DataChangeScope.BASE);
-        listenerOnPortStateRegistration = dataBroker.registerDataChangeListener(
-                LogicalDatastoreType.OPERATIONAL,
-                II_TO_STATE,
-                this, AsyncDataBroker.DataChangeScope.SUBTREE);
+        final DataTreeIdentifier<T> dtiToNodeConnector =
+                new DataTreeIdentifier(LogicalDatastoreType.OPERATIONAL, II_TO_FLOW_CAPABLE_NODE_CONNECTOR);
+        final DataTreeIdentifier<T> dtiToNodeConnectorState =
+                new DataTreeIdentifier(LogicalDatastoreType.OPERATIONAL, II_TO_STATE);
+        final SimpleTaskRetryLooper looper = new SimpleTaskRetryLooper(STARTUP_LOOP_TICK, STARTUP_LOOP_MAX_RETRIES);
+        try {
+            dataChangeListenerRegistration = looper.loopUntilNoException(new Callable<ListenerRegistration<DataTreeChangeListener>>() {
+                @Override
+                public ListenerRegistration<DataTreeChangeListener> call() throws Exception {
+                    return dataBroker.registerDataTreeChangeListener(dtiToNodeConnector, NodeConnectorInventoryEventTranslator.this);
+                }
+            });
+            listenerOnPortStateRegistration = looper.loopUntilNoException(new Callable<ListenerRegistration<DataTreeChangeListener>>() {
+                @Override
+                public ListenerRegistration<DataTreeChangeListener> call() throws Exception {
+                    return dataBroker.registerDataTreeChangeListener(dtiToNodeConnectorState, NodeConnectorInventoryEventTranslator.this);
+                }
+            });
+        } catch (Exception e) {
+            LOG.error("DataTreeChangeListeners registration failed: {}", e);
+            throw new IllegalStateException("NodeConnectorInventoryEventTranslator startup failed!", e);
+        }
+        LOG.info("NodeConnectorInventoryEventTranslator has started.");
     }
 
     @Override
     public void close() {
-        dataChangeListenerRegistration.close();
-        listenerOnPortStateRegistration.close();
+        if (dataChangeListenerRegistration != null) {
+            dataChangeListenerRegistration.close();
+        }
+        if (listenerOnPortStateRegistration != null) {
+            listenerOnPortStateRegistration.close();
+        }
     }
 
     @Override
-    public void onDataChanged(AsyncDataChangeEvent<InstanceIdentifier<?>, DataObject> change) {
-        LOG.trace("Node connectors in inventory changed: {} created, {} updated, {} removed",
-                change.getCreatedData().size(), change.getUpdatedData().size(), change.getRemovedPaths().size());
-
-        // Iterate over created node connectors
-        for (Map.Entry<InstanceIdentifier<?>, DataObject> entry : change.getCreatedData().entrySet()) {
-            InstanceIdentifier<NodeConnector> nodeConnectorInstanceId =
-                    entry.getKey().firstIdentifierOf(NodeConnector.class);
-            if (compareIITail(entry.getKey(),II_TO_FLOW_CAPABLE_NODE_CONNECTOR)) {
-                FlowCapableNodeConnector flowConnector = (FlowCapableNodeConnector) entry.getValue();
-                if (!isPortDown(flowConnector)) {
-                    notifyNodeConnectorAppeared(nodeConnectorInstanceId, flowConnector);
-                } else {
-                    iiToDownFlowCapableNodeConnectors.put(nodeConnectorInstanceId, flowConnector);
-                }
+    public void onDataTreeChanged(@Nonnull Collection<DataTreeModification<T>> modifications) {
+        for(DataTreeModification modification : modifications) {
+            LOG.trace("Node connectors in inventory changed -> {}", modification.getRootNode().getModificationType());
+            switch (modification.getRootNode().getModificationType()) {
+                case WRITE:
+                    processAddedConnector(modification);
+                    break;
+                case SUBTREE_MODIFIED:
+                    processUpdatedConnector(modification);
+                    break;
+                case DELETE:
+                    processRemovedConnector(modification);
+                    break;
+                default:
+                    throw new IllegalArgumentException("Unhandled modification type: {}" +
+                            modification.getRootNode().getModificationType());
             }
         }
+    }
 
-        // Iterate over updated node connectors (port down state may change)
-        for (Map.Entry<InstanceIdentifier<?>, DataObject> entry : change.getUpdatedData().entrySet()) {
-            InstanceIdentifier<NodeConnector> nodeConnectorInstanceId =
-                    entry.getKey().firstIdentifierOf(NodeConnector.class);
-            if (compareIITail(entry.getKey(),II_TO_FLOW_CAPABLE_NODE_CONNECTOR)) {
-                FlowCapableNodeConnector flowConnector = (FlowCapableNodeConnector) entry.getValue();
-                if (isPortDown(flowConnector)) {
-                    notifyNodeConnectorDisappeared(nodeConnectorInstanceId);
-                } else {
-                    notifyNodeConnectorAppeared(nodeConnectorInstanceId, flowConnector);
-                }
-            } else if (compareIITail(entry.getKey(),II_TO_STATE)) {
-                FlowCapableNodeConnector flowNodeConnector = iiToDownFlowCapableNodeConnectors.get(nodeConnectorInstanceId);
-                if (flowNodeConnector != null) {
-                    State state = (State)entry.getValue();
-                    if (!state.isLinkDown()) {
-                        FlowCapableNodeConnectorBuilder flowCapableNodeConnectorBuilder = new FlowCapableNodeConnectorBuilder(flowNodeConnector);
-                        flowCapableNodeConnectorBuilder.setState(state);
-                        notifyNodeConnectorAppeared(nodeConnectorInstanceId, flowCapableNodeConnectorBuilder.build());
-                        iiToDownFlowCapableNodeConnectors.remove(nodeConnectorInstanceId);
-                    }
-                }
+    private void processAddedConnector(final DataTreeModification<T> modification) {
+        final InstanceIdentifier<T> identifier = modification.getRootPath().getRootIdentifier();
+        InstanceIdentifier<NodeConnector> nodeConnectorInstanceId =identifier.firstIdentifierOf(NodeConnector.class);
+        if (compareIITail(identifier, II_TO_FLOW_CAPABLE_NODE_CONNECTOR)) {
+            FlowCapableNodeConnector flowConnector = (FlowCapableNodeConnector) modification.getRootNode().getDataAfter();
+            if (!isPortDown(flowConnector)) {
+                notifyNodeConnectorAppeared(nodeConnectorInstanceId, flowConnector);
+            } else {
+                iiToDownFlowCapableNodeConnectors.put(nodeConnectorInstanceId, flowConnector);
             }
         }
+    }
 
-        // Iterate over removed node connectors
-        for (InstanceIdentifier<?> removed : change.getRemovedPaths()) {
-            if (compareIITail(removed,II_TO_FLOW_CAPABLE_NODE_CONNECTOR)) {
-                InstanceIdentifier<NodeConnector> nodeConnectorInstanceId = removed.firstIdentifierOf(NodeConnector.class);
+    private void processUpdatedConnector(final DataTreeModification<T> modification) {
+        final InstanceIdentifier<T> identifier = modification.getRootPath().getRootIdentifier();
+        InstanceIdentifier<NodeConnector> nodeConnectorInstanceId = identifier.firstIdentifierOf(NodeConnector.class);
+        if (compareIITail(identifier, II_TO_FLOW_CAPABLE_NODE_CONNECTOR)) {
+            FlowCapableNodeConnector flowConnector = (FlowCapableNodeConnector) modification.getRootNode().getDataAfter();
+            if (isPortDown(flowConnector)) {
                 notifyNodeConnectorDisappeared(nodeConnectorInstanceId);
+            } else {
+                notifyNodeConnectorAppeared(nodeConnectorInstanceId, flowConnector);
             }
+        } else if (compareIITail(identifier, II_TO_STATE)) {
+            FlowCapableNodeConnector flowNodeConnector = iiToDownFlowCapableNodeConnectors.get(nodeConnectorInstanceId);
+            if (flowNodeConnector != null) {
+                State state = (State) modification.getRootNode().getDataAfter();
+                if (!state.isLinkDown()) {
+                    FlowCapableNodeConnectorBuilder flowCapableNodeConnectorBuilder =
+                            new FlowCapableNodeConnectorBuilder(flowNodeConnector);
+                    flowCapableNodeConnectorBuilder.setState(state);
+                    notifyNodeConnectorAppeared(nodeConnectorInstanceId, flowCapableNodeConnectorBuilder.build());
+                    iiToDownFlowCapableNodeConnectors.remove(nodeConnectorInstanceId);
+                }
+            }
+        }
+    }
+
+    private void processRemovedConnector(final DataTreeModification<T> modification) {
+        final InstanceIdentifier<T> identifier = modification.getRootPath().getRootIdentifier();
+        if (compareIITail(identifier, II_TO_FLOW_CAPABLE_NODE_CONNECTOR)) {
+            InstanceIdentifier<NodeConnector> nodeConnectorInstanceId = identifier.firstIdentifierOf(NodeConnector.class);
+            notifyNodeConnectorDisappeared(nodeConnectorInstanceId);
         }
     }
 
-    /**
-     * @param key
-     * @param iiToFlowCapableNodeConnector
-     * @return
-     */
-    private boolean compareIITail(InstanceIdentifier<?> ii1,
-            InstanceIdentifier<?> ii2) {
+    private boolean compareIITail(final InstanceIdentifier<?> ii1, final InstanceIdentifier<?> ii2) {
         return Iterables.getLast(ii1.getPathArguments()).equals(Iterables.getLast(ii2.getPathArguments()));
     }
 
-    private static boolean isPortDown(FlowCapableNodeConnector flowCapableNodeConnector) {
+    private static boolean isPortDown(final FlowCapableNodeConnector flowCapableNodeConnector) {
         PortState portState = flowCapableNodeConnector.getState();
         PortConfig portConfig = flowCapableNodeConnector.getConfiguration();
-        return portState != null && portState.isLinkDown() ||
-                portConfig != null && portConfig.isPORTDOWN();
+        return portState != null && portState.isLinkDown()
+                || portConfig != null && portConfig.isPORTDOWN();
     }
 
-    private void notifyNodeConnectorAppeared(InstanceIdentifier<NodeConnector> nodeConnectorInstanceId,
-                                             FlowCapableNodeConnector flowConnector) {
+    private void notifyNodeConnectorAppeared(final InstanceIdentifier<NodeConnector> nodeConnectorInstanceId,
+                                             final FlowCapableNodeConnector flowConnector) {
         for (NodeConnectorEventsObserver observer : observers) {
             observer.nodeConnectorAdded(nodeConnectorInstanceId, flowConnector);
         }
     }
 
-    private void notifyNodeConnectorDisappeared(InstanceIdentifier<NodeConnector> nodeConnectorInstanceId) {
+    private void notifyNodeConnectorDisappeared(final InstanceIdentifier<NodeConnector> nodeConnectorInstanceId) {
         for (NodeConnectorEventsObserver observer : observers) {
             observer.nodeConnectorRemoved(nodeConnectorInstanceId);
         }
     }
+
 }
index f1bfd0be431f72f88f17b8da78a5e12ec3beb535..b322dbcbe3cbd7dc01bc6a1c53e4ea0637ba6c4a 100644 (file)
@@ -17,9 +17,6 @@ import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflow
 import org.opendaylight.yangtools.yang.common.RpcResult;
 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
 
-/**
- * Created by Martin Bobak mbobak@cisco.com on 11/20/14.
- */
 public class OperationalStatusChangeService implements LldpSpeakerService {
 
     private final LLDPSpeaker speakerInstance;
index 98fd805b4c97e5b439a81d05ce0c3ef63cc76b0b..ca8fa54dd97aae6a98ecf0fbb8c6045b31f63c14 100644 (file)
@@ -1,7 +1,7 @@
 <?xml version="1.0" encoding="UTF-8"?>
 <blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0"
            xmlns:odl="http://opendaylight.org/xmlns/blueprint/v1.0.0"
-        odl:use-default-for-reference-types="true">
+           odl:use-default-for-reference-types="true">
 
   <reference id="dataBroker" interface="org.opendaylight.controller.md.sal.binding.api.DataBroker"/>
 
index e02784f89ac710ba931a1fc75386148d791f1246..cd77668eac4caf326a5cf53d16851c64d11c714b 100644 (file)
@@ -19,7 +19,6 @@ import static org.mockito.Mockito.when;
 import java.util.concurrent.ScheduledExecutorService;
 import java.util.concurrent.ScheduledFuture;
 import java.util.concurrent.TimeUnit;
-
 import org.junit.Before;
 import org.junit.Test;
 import org.junit.runner.RunWith;
@@ -41,13 +40,13 @@ import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflow
 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
 
 /**
- * Tests for @{LLDPSpeaker} class.
+ * Tests for {@link LLDPSpeaker}.
  */
 @RunWith(MockitoJUnitRunner.class)
 public class LLDPSpeakerTest {
-    static InstanceIdentifier<NodeConnector> id;
-    static FlowCapableNodeConnector fcnc;
-    static TransmitPacketInput packet;
+    private static final InstanceIdentifier<NodeConnector> id;
+    private static final FlowCapableNodeConnector fcnc;
+    private static final TransmitPacketInput packet;
 
     static {
         MacAddress mac = new MacAddress("01:23:45:67:89:AB");
@@ -62,17 +61,16 @@ public class LLDPSpeakerTest {
     }
 
     @Mock
-    PacketProcessingService packetProcessingService;
+    private PacketProcessingService packetProcessingService;
     @Mock
-    ScheduledExecutorService scheduledExecutorService;
+    private ScheduledExecutorService scheduledExecutorService;
     @Mock
-    ScheduledFuture scheduledSpeakerTask;
+    private ScheduledFuture scheduledSpeakerTask;
 
-    MacAddress destinationMACAddress = null;
-    LLDPSpeaker lldpSpeaker;
+    private final MacAddress destinationMACAddress = null;
+    private LLDPSpeaker lldpSpeaker;
 
     @Before
-    @SuppressWarnings("unchecked")
     public void setUp() {
         when(
                 scheduledExecutorService.scheduleAtFixedRate(
@@ -143,7 +141,7 @@ public class LLDPSpeakerTest {
     }
 
     /**
-     * Test that when @{LLDPSpeaker#nodeConnectorAdded} is called multiple times
+     * Test that when {@link LLDPSpeaker#nodeConnectorAdded} is called multiple times
      * with same arguments, only the first one have effect.
      */
     @Test
@@ -161,12 +159,9 @@ public class LLDPSpeakerTest {
 
     /**
      * Test that lldpSpeaker cancels periodic LLDP flood task and stops
-     * 
-     * @{ScheduledExecutorService .
-     * @throws Exception
      */
     @Test
-    public void testCleanup() throws Exception {
+    public void testCleanup() {
         lldpSpeaker.close();
         verify(scheduledSpeakerTask, times(1)).cancel(true);
         verify(scheduledExecutorService, times(1)).shutdown();
index 3426d29fcccdc1a4bfb6b147cf2dbb5aa830bdb5..9ee90e653aa3184be59bd1b186c62c6ccce156ac 100644 (file)
@@ -8,68 +8,63 @@
 
 package org.opendaylight.openflowplugin.applications.lldpspeaker;
 
-import static org.mockito.Mockito.*;
-
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Map;
-import java.util.Set;
-import org.junit.*;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyZeroInteractions;
+import static org.mockito.Mockito.when;
+import static org.opendaylight.controller.md.sal.binding.api.DataObjectModification.ModificationType.DELETE;
+import static org.opendaylight.controller.md.sal.binding.api.DataObjectModification.ModificationType.SUBTREE_MODIFIED;
+import static org.opendaylight.controller.md.sal.binding.api.DataObjectModification.ModificationType.WRITE;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import org.junit.Before;
+import org.junit.Test;
 import org.junit.runner.RunWith;
 import org.mockito.Mock;
 import org.mockito.runners.MockitoJUnitRunner;
 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.controller.md.sal.binding.api.DataChangeListener;
-import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker;
-import org.opendaylight.controller.md.sal.common.api.data.AsyncDataChangeEvent;
+import org.opendaylight.controller.md.sal.binding.api.DataObjectModification;
+import org.opendaylight.controller.md.sal.binding.api.DataObjectModification.ModificationType;
+import org.opendaylight.controller.md.sal.binding.api.DataTreeIdentifier;
+import org.opendaylight.controller.md.sal.binding.api.DataTreeModification;
 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNodeConnector;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.node.NodeConnector;
-import org.opendaylight.yangtools.concepts.ListenerRegistration;
 import org.opendaylight.yangtools.yang.binding.DataObject;
 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
 
 
 /**
- * Tests for @{NodeConnectorInventoryEventTranslator} class.
+ * Tests for {@link NodeConnectorInventoryEventTranslator}.
  */
 @RunWith(MockitoJUnitRunner.class)
 public class NodeConnectorInventoryEventTranslatorTest {
-    static InstanceIdentifier<NodeConnector> id = TestUtils.createNodeConnectorId("openflow:1", "openflow:1:1");
-    static InstanceIdentifier<FlowCapableNodeConnector> iiToConnector = id.augmentation(FlowCapableNodeConnector.class);
-    static FlowCapableNodeConnector fcnc = TestUtils.createFlowCapableNodeConnector().build();
+    private static final InstanceIdentifier<NodeConnector> id = TestUtils.createNodeConnectorId("openflow:1", "openflow:1:1");
+    private static final InstanceIdentifier<FlowCapableNodeConnector> iiToConnector = id.augmentation(FlowCapableNodeConnector.class);
+    private static final FlowCapableNodeConnector fcnc = TestUtils.createFlowCapableNodeConnector().build();
 
-    @Mock DataBroker dataBroker;
-    @Mock ListenerRegistration<DataChangeListener> dataChangeListenerRegistration;
-    @Mock NodeConnectorEventsObserver eventsObserver;
-    @Mock NodeConnectorEventsObserver eventsObserver2;
+    @Mock
+    private NodeConnectorEventsObserver eventsObserver;
+    @Mock
+    private NodeConnectorEventsObserver eventsObserver2;
 
-    MockDataChangedEvent dataChangedEvent = new MockDataChangedEvent();
-    NodeConnectorInventoryEventTranslator translator;
+    private NodeConnectorInventoryEventTranslator translator;
 
     @Before
     public void setUp() {
-
-        when(dataBroker.registerDataChangeListener(
-                any(LogicalDatastoreType.class),
-                any(InstanceIdentifier.class),
-                any(DataChangeListener.class),
-                any(AsyncDataBroker.DataChangeScope.class)))
-                .thenReturn(dataChangeListenerRegistration);
-        translator = new NodeConnectorInventoryEventTranslator(dataBroker, eventsObserver, eventsObserver2);
+        translator = new NodeConnectorInventoryEventTranslator(mock(DataBroker.class), eventsObserver, eventsObserver2);
     }
 
     /**
-     * Test that checks if @{NodeConnectorEventsObserver#nodeConnectorAdded} is called
+     * Test that checks if {@link NodeConnectorEventsObserver#nodeConnectorAdded} is called
      * for each FlowCapableNodeConnector item that @{AsyncDataChangeEvent#getCreatedData} return.
      */
     @Test
     public void testNodeConnectorCreation() {
-        // Setup dataChangedEvent to mock new port creation in inventory
-        dataChangedEvent.created.put(iiToConnector, fcnc);
-
-        // Invoke NodeConnectorInventoryEventTranslator and check result
-        translator.onDataChanged(dataChangedEvent);
+        DataTreeModification dataTreeModification = setupDataTreeChange(WRITE, iiToConnector, fcnc);
+        translator.onDataTreeChanged(Collections.singleton(dataTreeModification));
         verify(eventsObserver).nodeConnectorAdded(id, fcnc);
     }
 
@@ -79,12 +74,8 @@ public class NodeConnectorInventoryEventTranslatorTest {
     @Test
     public void testNodeConnectorCreationLinkDown() {
         FlowCapableNodeConnector fcnc = TestUtils.createFlowCapableNodeConnector(true, false).build();
-
-        // Setup dataChangedEvent to mock new port creation in inventory
-        dataChangedEvent.created.put(id, fcnc);
-
-        // Invoke NodeConnectorInventoryEventTranslator and check result
-        translator.onDataChanged(dataChangedEvent);
+        DataTreeModification dataTreeModification = setupDataTreeChange(WRITE, id, fcnc);
+        translator.onDataTreeChanged(Collections.singleton(dataTreeModification));
         verifyZeroInteractions(eventsObserver);
     }
 
@@ -94,80 +85,63 @@ public class NodeConnectorInventoryEventTranslatorTest {
     @Test
     public void testNodeConnectorCreationAdminDown() {
         FlowCapableNodeConnector fcnc = TestUtils.createFlowCapableNodeConnector(false, true).build();
-
-        // Setup dataChangedEvent to mock new port creation in inventory
-        dataChangedEvent.created.put(id, fcnc);
-
-        // Invoke NodeConnectorInventoryEventTranslator and check result
-        translator.onDataChanged(dataChangedEvent);
+        DataTreeModification dataTreeModification = setupDataTreeChange(WRITE, id, fcnc);
+        translator.onDataTreeChanged(Collections.singleton(dataTreeModification));
         verifyZeroInteractions(eventsObserver);
     }
 
     /**
-     * Test that checks if @{NodeConnectorEventsObserver#nodeConnectorRemoved} is called
+     * Test that checks if {@link NodeConnectorEventsObserver#nodeConnectorRemoved} is called
      * for each FlowCapableNodeConnector item inside @{AsyncDataChangeEvent#getUpdatedData}
      * that have link down state.
      */
     @Test
     public void testNodeConnectorUpdateToLinkDown() {
         FlowCapableNodeConnector fcnc = TestUtils.createFlowCapableNodeConnector(true, false).build();
-
-        // Setup dataChangedEvent to mock link down
-        dataChangedEvent.updated.put(iiToConnector, fcnc);
-
-        // Invoke NodeConnectorInventoryEventTranslator and check result
-        translator.onDataChanged(dataChangedEvent);
+        DataTreeModification dataTreeModification = setupDataTreeChange(SUBTREE_MODIFIED, iiToConnector, fcnc);
+        translator.onDataTreeChanged(Collections.singleton(dataTreeModification));
         verify(eventsObserver).nodeConnectorRemoved(id);
     }
 
     /**
-     * Test that checks if @{NodeConnectorEventsObserver#nodeConnectorRemoved} is called
+     * Test that checks if {@link NodeConnectorEventsObserver#nodeConnectorRemoved} is called
      * for each FlowCapableNodeConnector item inside @{AsyncDataChangeEvent#getUpdatedData}
      * that have administrative down state.
      */
     @Test
     public void testNodeConnectorUpdateToAdminDown() {
         FlowCapableNodeConnector fcnc = TestUtils.createFlowCapableNodeConnector(false, true).build();
-
-        // Setup dataChangedEvent to mock link down and administrative port down
-        dataChangedEvent.updated.put(iiToConnector, fcnc);
-
-        // Invoke NodeConnectorInventoryEventTranslator and check result
-        translator.onDataChanged(dataChangedEvent);
+        DataTreeModification dataTreeModification = setupDataTreeChange(SUBTREE_MODIFIED, iiToConnector, fcnc);
+        translator.onDataTreeChanged(Collections.singleton(dataTreeModification));
         verify(eventsObserver).nodeConnectorRemoved(id);
     }
 
     /**
-     * Test that checks if @{NodeConnectorEventsObserver#nodeConnectorAdded} is called
+     * Test that checks if {@link NodeConnectorEventsObserver#nodeConnectorAdded} is called
      * for each FlowCapableNodeConnector item inside @{AsyncDataChangeEvent#getUpdatedData}
      * that have administrative up and link up state.
      */
     @Test
     public void testNodeConnectorUpdateToUp() {
-        // Setup dataChangedEvent to mock link up and administrative port up
-        dataChangedEvent.updated.put(iiToConnector, fcnc);
-
-        // Invoke NodeConnectorInventoryEventTranslator and check result
-        translator.onDataChanged(dataChangedEvent);
+        DataTreeModification dataTreeModification = setupDataTreeChange(SUBTREE_MODIFIED, iiToConnector, fcnc);
+        translator.onDataTreeChanged(Collections.singleton(dataTreeModification));
         verify(eventsObserver).nodeConnectorAdded(id, fcnc);
     }
 
     /**
-     * Test that checks if @{NodeConnectorEventsObserver#nodeConnectorRemoved} is called
+     * Test that checks if {@link NodeConnectorEventsObserver#nodeConnectorRemoved} is called
      * for each FlowCapableNodeConnector path that @{AsyncDataChangeEvent#getRemovedPaths} return.
      */
     @Test
     public void testNodeConnectorRemoval() {
-        // Setup dataChangedEvent to mock node connector removal
-        dataChangedEvent.removed.add(iiToConnector);
-
+        DataTreeModification dataTreeModification = setupDataTreeChange(DELETE, iiToConnector, null);
         // Invoke NodeConnectorInventoryEventTranslator and check result
-        translator.onDataChanged(dataChangedEvent);
+        translator.onDataTreeChanged(Collections.singleton(dataTreeModification));
         verify(eventsObserver).nodeConnectorRemoved(id);
     }
 
     /**
-     * Test that checks if @{NodeConnectorEventsObserver#nodeConnectorAdded} and
+     * Test that checks if {@link NodeConnectorEventsObserver#nodeConnectorAdded} and
      * @{NodeConnectorEventsObserver#nodeConnectorRemoved} are called for each
      * observer when multiple observers are registered for notifications.
      */
@@ -176,66 +150,32 @@ public class NodeConnectorInventoryEventTranslatorTest {
         // Create prerequisites
         InstanceIdentifier<NodeConnector> id2 = TestUtils.createNodeConnectorId("openflow:1", "openflow:1:2");
         InstanceIdentifier<FlowCapableNodeConnector> iiToConnector2 = id2.augmentation(FlowCapableNodeConnector.class);
-
-        // Setup dataChangedEvent to mock port creation and removal
-        dataChangedEvent.created.put(iiToConnector, fcnc);
-        dataChangedEvent.removed.add(iiToConnector2);
-
+        List<DataTreeModification> modifications = new ArrayList();
+        modifications.add(setupDataTreeChange(WRITE, iiToConnector, fcnc));
+        modifications.add(setupDataTreeChange(DELETE, iiToConnector2, null));
         // Invoke onDataChanged and check that both observers notified
-        translator.onDataChanged(dataChangedEvent);
+        translator.onDataTreeChanged(modifications);
         verify(eventsObserver).nodeConnectorAdded(id, fcnc);
         verify(eventsObserver).nodeConnectorRemoved(id2);
         verify(eventsObserver2).nodeConnectorAdded(id, fcnc);
         verify(eventsObserver2).nodeConnectorRemoved(id2);
     }
 
-    /**
-     * Test that @{ListenerRegistration} is closed when ${NodeConnectorInventoryEventTranslator#close}
-     * method is called.
-     * @throws Exception
-     */
     @Test
-    public void testCleanup() throws Exception {
-        // Trigger cleanup
+    public void tearDown() throws Exception {
         translator.close();
-
-        // Verify that ListenerRegistration to DOM events
-        verify(dataChangeListenerRegistration, times(2)).close();
     }
 
-    static class MockDataChangedEvent implements AsyncDataChangeEvent<InstanceIdentifier<?>, DataObject> {
-        Map<InstanceIdentifier<?>,DataObject> created = new HashMap<>();
-        Map<InstanceIdentifier<?>,DataObject> updated = new HashMap<>();
-        Set<InstanceIdentifier<?>> removed = new HashSet<>();
-
-        @Override
-        public Map<InstanceIdentifier<?>, DataObject> getCreatedData() {
-            return created;
-        }
-
-        @Override
-        public Map<InstanceIdentifier<?>, DataObject> getUpdatedData() {
-            return updated;
-        }
-
-        @Override
-        public Set<InstanceIdentifier<?>> getRemovedPaths() {
-            return removed;
-        }
-
-        @Override
-        public Map<InstanceIdentifier<?>, DataObject> getOriginalData() {
-            throw new UnsupportedOperationException("Not implemented by mock");
-        }
-
-        @Override
-        public DataObject getOriginalSubtree() {
-            throw new UnsupportedOperationException("Not implemented by mock");
-        }
-
-        @Override
-        public DataObject getUpdatedSubtree() {
-            throw new UnsupportedOperationException("Not implemented by mock");
-        }
+    private <T extends DataObject> DataTreeModification setupDataTreeChange(final ModificationType type,
+                                                            final InstanceIdentifier<T> ii,
+                                                            final FlowCapableNodeConnector connector) {
+        final DataTreeModification dataTreeModification = mock(DataTreeModification.class);
+        when(dataTreeModification.getRootNode()).thenReturn(mock(DataObjectModification.class));
+        DataTreeIdentifier<T> identifier = new DataTreeIdentifier(LogicalDatastoreType.OPERATIONAL, ii);
+        when(dataTreeModification.getRootNode().getModificationType()).thenReturn(type);
+        when(dataTreeModification.getRootPath()).thenReturn(identifier);
+        when(dataTreeModification.getRootNode().getDataAfter()).thenReturn(connector);
+        return dataTreeModification;
+
     }
 }
index 422f4e55dd50e105b1b3fd66fb0079e27eb000bb..e6ab666b65a0405e66194ed651f3d943068cf00c 100644 (file)
@@ -45,7 +45,7 @@ public class TestUtils {
         return createFlowCapableNodeConnector(false, false, mac, port);
     }
 
-    static FlowCapableNodeConnectorBuilder createFlowCapableNodeConnector(boolean linkDown, boolean adminDown,
+    private static FlowCapableNodeConnectorBuilder createFlowCapableNodeConnector(boolean linkDown, boolean adminDown,
                                                                           MacAddress mac, long port) {
         return new FlowCapableNodeConnectorBuilder()
                 .setHardwareAddress(mac)
index d2e726529928af633712157231047be9df54d9a8..31dacc2e266fdcee5981d6efa3862c4fe0b17a09 100644 (file)
@@ -1,5 +1,5 @@
-/*
- * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
+/**
+ * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
  *
  * This program and the accompanying materials are made available under the
  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
@@ -10,13 +10,15 @@ package org.opendaylight.openflowplugin.applications.tableMissEnforcer;
 
 import java.math.BigInteger;
 import java.util.ArrayList;
+import java.util.Collection;
 import java.util.List;
-import java.util.Set;
 import java.util.concurrent.Callable;
+import javax.annotation.Nonnull;
 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.controller.md.sal.binding.api.DataChangeListener;
-import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker;
-import org.opendaylight.controller.md.sal.common.api.data.AsyncDataChangeEvent;
+import org.opendaylight.controller.md.sal.binding.api.DataObjectModification.ModificationType;
+import org.opendaylight.controller.md.sal.binding.api.DataTreeChangeListener;
+import org.opendaylight.controller.md.sal.binding.api.DataTreeIdentifier;
+import org.opendaylight.controller.md.sal.binding.api.DataTreeModification;
 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
 import org.opendaylight.openflowplugin.api.OFConstants;
 import org.opendaylight.openflowplugin.common.wait.SimpleTaskRetryLooper;
@@ -47,13 +49,9 @@ import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeRef
 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.Nodes;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
 import org.opendaylight.yangtools.concepts.ListenerRegistration;
-import org.opendaylight.yangtools.yang.binding.DataObject;
 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
 
-/**
- * Created by Martin Bobak mbobak@cisco.com on 8/27/14.
- */
-public class LLDPPacketPuntEnforcer implements DataChangeListener {
+public class LLDPPacketPuntEnforcer implements AutoCloseable, DataTreeChangeListener<FlowCapableNode> {
     private static final long STARTUP_LOOP_TICK = 500L;
     private static final int STARTUP_LOOP_MAX_RETRIES = 8;
     private static final short TABLE_ID = (short) 0;
@@ -61,7 +59,7 @@ public class LLDPPacketPuntEnforcer implements DataChangeListener {
     private static final String DEFAULT_FLOW_ID = "42";
     private final SalFlowService flowService;
     private final DataBroker dataBroker;
-    private ListenerRegistration<DataChangeListener> dataChangeListenerRegistration;
+    private ListenerRegistration<DataTreeChangeListener> listenerRegistration;
 
     public LLDPPacketPuntEnforcer(SalFlowService flowService, DataBroker dataBroker) {
         this.flowService = flowService;
@@ -71,14 +69,13 @@ public class LLDPPacketPuntEnforcer implements DataChangeListener {
     public void start() {
         final InstanceIdentifier<FlowCapableNode> path = InstanceIdentifier.create(Nodes.class).child(Node.class).
                 augmentation(FlowCapableNode.class);
+        final DataTreeIdentifier<FlowCapableNode> identifier = new DataTreeIdentifier(LogicalDatastoreType.OPERATIONAL, path);
         SimpleTaskRetryLooper looper = new SimpleTaskRetryLooper(STARTUP_LOOP_TICK, STARTUP_LOOP_MAX_RETRIES);
         try {
-            dataChangeListenerRegistration = looper.loopUntilNoException(new Callable<ListenerRegistration<DataChangeListener>>() {
+            listenerRegistration = looper.loopUntilNoException(new Callable<ListenerRegistration<DataTreeChangeListener>>() {
                 @Override
-                public ListenerRegistration<DataChangeListener> call() throws Exception {
-                    return dataBroker.registerDataChangeListener(
-                            LogicalDatastoreType.OPERATIONAL,
-                            path, LLDPPacketPuntEnforcer.this, AsyncDataBroker.DataChangeScope.BASE);
+                public ListenerRegistration<DataTreeChangeListener> call() throws Exception {
+                    return dataBroker.registerDataTreeChangeListener(identifier, LLDPPacketPuntEnforcer.this);
                 }
             });
         } catch (Exception e) {
@@ -86,27 +83,25 @@ public class LLDPPacketPuntEnforcer implements DataChangeListener {
         }
     }
 
+    @Override
     public void close() {
-        if(dataChangeListenerRegistration != null) {
-            dataChangeListenerRegistration.close();
+        if(listenerRegistration != null) {
+            listenerRegistration.close();
         }
     }
 
     @Override
-    public void onDataChanged(AsyncDataChangeEvent<InstanceIdentifier<?>, DataObject> change) {
-        final Set<InstanceIdentifier<?>> changedDataKeys = change.getCreatedData().keySet();
-
-        if (changedDataKeys != null) {
-            for (InstanceIdentifier<?> key : changedDataKeys) {
+    public void onDataTreeChanged(@Nonnull final Collection<DataTreeModification<FlowCapableNode>> modifications) {
+        for (DataTreeModification modification : modifications) {
+            if (modification.getRootNode().getModificationType() == ModificationType.WRITE) {
                 AddFlowInputBuilder addFlowInput = new AddFlowInputBuilder(createFlow());
-                addFlowInput.setNode(new NodeRef(key.firstIdentifierOf(Node.class)));
+                addFlowInput.setNode(new NodeRef(modification.getRootPath().getRootIdentifier().firstIdentifierOf(Node.class)));
                 this.flowService.addFlow(addFlowInput.build());
             }
         }
     }
 
-
-    protected Flow createFlow() {
+    static Flow createFlow() {
         FlowBuilder flowBuilder = new FlowBuilder();
         flowBuilder.setMatch(new MatchBuilder().build());
         flowBuilder.setInstructions(createSendToControllerInstructions().build());
@@ -116,7 +111,6 @@ public class LLDPPacketPuntEnforcer implements DataChangeListener {
         flowBuilder.setBarrier(Boolean.FALSE);
         flowBuilder.setBufferId(OFConstants.OFP_NO_BUFFER);
         BigInteger value = BigInteger.valueOf(10L);
-        // BigInteger outputPort = BigInteger.valueOf(65535L);
         flowBuilder.setCookie(new FlowCookie(value));
         flowBuilder.setCookieMask(new FlowCookie(value));
         flowBuilder.setHardTimeout(0);
@@ -134,7 +128,7 @@ public class LLDPPacketPuntEnforcer implements DataChangeListener {
     }
 
     private static InstructionsBuilder createSendToControllerInstructions() {
-        List<Action> actionList = new ArrayList<Action>();
+        List<Action> actionList = new ArrayList<>();
         ActionBuilder ab = new ActionBuilder();
 
         OutputActionBuilder output = new OutputActionBuilder();
@@ -157,7 +151,7 @@ public class LLDPPacketPuntEnforcer implements DataChangeListener {
 
         // Put our Instruction in a list of Instructions
         InstructionsBuilder isb = new InstructionsBuilder();
-        List<Instruction> instructions = new ArrayList<Instruction>();
+        List<Instruction> instructions = new ArrayList<>();
         instructions.add(ib.build());
         isb.setInstruction(instructions);
         return isb;
index ff9ff6c2f026577b4f9843f8cc4b88799a354511..f644908dedfcbef673a73f4d06508d00a67d552b 100644 (file)
@@ -1,7 +1,7 @@
 <?xml version="1.0" encoding="UTF-8"?>
 <blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0"
            xmlns:odl="http://opendaylight.org/xmlns/blueprint/v1.0.0"
-        odl:use-default-for-reference-types="true">
+           odl:use-default-for-reference-types="true">
 
   <reference id="dataBroker" interface="org.opendaylight.controller.md.sal.binding.api.DataBroker"/>
 
index 94dd5975d6aab86f2f8be4766a95c0e48a42b742..08df369ef45a87282ba19683893a94b2af8f5e0d 100644 (file)
@@ -1,4 +1,4 @@
-/*
+/**
  * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
  *
  * This program and the accompanying materials are made available under the
@@ -10,38 +10,82 @@ package org.opendaylight.openflowplugin.applications.tableMissEnforcer;
 
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertNotNull;
+
+import java.util.Collections;
+import org.junit.After;
+import org.junit.Assert;
+import org.junit.Before;
 import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.ArgumentCaptor;
+import org.mockito.Captor;
 import org.mockito.Mock;
+import org.mockito.Mockito;
+import org.mockito.runners.MockitoJUnitRunner;
+import org.opendaylight.controller.md.sal.binding.api.DataBroker;
+import org.opendaylight.controller.md.sal.binding.api.DataObjectModification;
+import org.opendaylight.controller.md.sal.binding.api.DataObjectModification.ModificationType;
+import org.opendaylight.controller.md.sal.binding.api.DataTreeIdentifier;
+import org.opendaylight.controller.md.sal.binding.api.DataTreeModification;
+import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.OutputActionCase;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.list.Action;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNode;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.Flow;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.AddFlowInput;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.SalFlowService;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.flow.Instructions;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.instruction.ApplyActionsCase;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.list.Instruction;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.Nodes;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey;
+import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
 
 /**
- * Created by Martin Bobak mbobak@cisco.com on 8/29/14.
+ * Test for {@link LLDPPacketPuntEnforcer}.
  */
+@RunWith(MockitoJUnitRunner.class)
 public class LLDPDataChangeListenerTest {
-
+    private LLDPPacketPuntEnforcer lldpPacketPuntEnforcer;
+    private final static InstanceIdentifier<Node> nodeIID = InstanceIdentifier.create(Nodes.class)
+            .child(Node.class, new NodeKey(new NodeId("testnode:1")));
     @Mock
-    private static SalFlowService flowService;
+    private SalFlowService flowService;
+    @Mock
+    private DataTreeModification<FlowCapableNode> dataTreeModification;
+    @Captor
+    private ArgumentCaptor<AddFlowInput> addFlowInputCaptor;
+
+    @Before
+    public void setUp() {
+        lldpPacketPuntEnforcer = new LLDPPacketPuntEnforcer(flowService, Mockito.mock(DataBroker.class));
+        final DataTreeIdentifier<FlowCapableNode> identifier = new DataTreeIdentifier(LogicalDatastoreType.OPERATIONAL, nodeIID);
+        Mockito.when(dataTreeModification.getRootPath()).thenReturn(identifier);
+        Mockito.when(dataTreeModification.getRootNode()).thenReturn(Mockito.mock(DataObjectModification.class));
+        Mockito.when(dataTreeModification.getRootNode().getModificationType()).thenReturn(ModificationType.WRITE);
+    }
 
-    /**
-     * Test method for {@link org.opendaylight.openflowplugin.applications.tableMissEnforcer.LLDPPacketPuntEnforcer#createFlow()}
-     * which ensures that LLDPDataChangeListener creates proper flow for
-     */
     @Test
-    public void testCreateFlow() {
-        LLDPPacketPuntEnforcer lldpDataChangeListener = new LLDPPacketPuntEnforcer(flowService, null);
-        evaluateFlow(lldpDataChangeListener.createFlow());
+    public void testOnDataTreeChanged() {
+        lldpPacketPuntEnforcer.onDataTreeChanged(Collections.singleton(dataTreeModification));
+        Mockito.verify(flowService).addFlow(addFlowInputCaptor.capture());
+        AddFlowInput captured = addFlowInputCaptor.getValue();
+        Assert.assertEquals(nodeIID, captured.getNode().getValue());
     }
 
-    private static void evaluateFlow(final Flow flow) {
+    @Test
+    public void testCreateFlow() {
+        final Flow flow = lldpPacketPuntEnforcer.createFlow();
         evaluateInstructions(flow.getInstructions());
     }
 
+    @After
+    public void tearDown() {
+        lldpPacketPuntEnforcer.close();
+    }
+
     private static void evaluateInstructions(final Instructions instructions) {
         assertNotNull(instructions.getInstruction());
         assertEquals(1, instructions.getInstruction().size());
index 097d0edc4ebc0089c11375afa782ad9577ccb387..43225b987028b82f20baf4416a71dd9d3fbd1425 100644 (file)
@@ -1,4 +1,4 @@
-/*
+/**
  * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
  *
  * This program and the accompanying materials are made available under the
@@ -14,12 +14,8 @@ import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.topology.discovery.rev
 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorRef;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.packet.service.rev130709.PacketProcessingListener;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.packet.service.rev130709.PacketReceived;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
 
 public class LLDPDiscoveryListener implements PacketProcessingListener {
-    private static final Logger LOG = LoggerFactory.getLogger(LLDPDiscoveryListener.class);
-
     private final LLDPLinkAger lldpLinkAger;
     private final NotificationProviderService notificationService;
 
index 22315d8ede5377d83be0f4bc0c2d6e724ad1a603..de79211792d247f98a13e2079a67b66a83274f10 100644 (file)
@@ -2,7 +2,7 @@
 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
   <modelVersion>4.0.0</modelVersion>
   <parent>
-    <groupId>org.opendaylight.controller</groupId>
+    <groupId>org.opendaylight.odlparent</groupId>
     <artifactId>karaf-parent</artifactId>
     <version>1.7.0-SNAPSHOT</version>
     <relativePath></relativePath>
index d6856d203c5ca80cb5c84aab539d190ddca9531e..82dbce337c9687197f51f2bb2ad515691e763642 100644 (file)
       <groupId>org.opendaylight.mdsal.model</groupId>
       <artifactId>ietf-yang-types-20130715</artifactId>
     </dependency>
-    <dependency>
-      <groupId>org.opendaylight.mdsal.model</groupId>
-      <artifactId>ietf-yang-types-20130715</artifactId>
-    </dependency>
     <dependency>
       <groupId>org.opendaylight.mdsal.model</groupId>
       <artifactId>yang-ext</artifactId>