Fix checkstyle violations in utils 28/69028/2
authorTom Pantelis <tompantelis@gmail.com>
Fri, 2 Mar 2018 23:15:58 +0000 (18:15 -0500)
committerStephen Kitt <skitt@redhat.com>
Mon, 5 Mar 2018 14:01:20 +0000 (14:01 +0000)
NotifyingDataChangeListener is fixed to be thread-safe, with
ConcurrentHashMap-backed sets and volatile fields where necessary.

Change-Id: Ic740e964c7fbcb53caf091475e3032ad29284677
Signed-off-by: Tom Pantelis <tompantelis@gmail.com>
18 files changed:
utils/hwvtepsouthbound-utils/src/main/java/org/opendaylight/ovsdb/utils/hwvtepsouthbound/utils/HwvtepSouthboundUtils.java
utils/mdsal-utils/src/main/java/org/opendaylight/ovsdb/utils/mdsal/utils/MdsalObject.java
utils/mdsal-utils/src/main/java/org/opendaylight/ovsdb/utils/mdsal/utils/MdsalUtils.java
utils/mdsal-utils/src/main/java/org/opendaylight/ovsdb/utils/mdsal/utils/MdsalUtilsAsync.java
utils/mdsal-utils/src/main/java/org/opendaylight/ovsdb/utils/mdsal/utils/NotifyingDataChangeListener.java
utils/mdsal-utils/src/main/java/org/opendaylight/ovsdb/utils/mdsal/utils/TransactionElement.java
utils/mdsal-utils/src/main/java/org/opendaylight/ovsdb/utils/mdsal/utils/TransactionHistory.java
utils/mdsal-utils/src/main/java/org/opendaylight/ovsdb/utils/mdsal/utils/TransactionType.java
utils/mdsal-utils/src/test/java/org/opendaylight/ovsdb/utils/mdsal/utils/MdsalUtilsAsyncTest.java
utils/mdsal-utils/src/test/java/org/opendaylight/ovsdb/utils/mdsal/utils/MdsalUtilsTest.java
utils/ovsdb-it-utils/src/main/java/org/opendaylight/ovsdb/utils/ovsdb/it/utils/DockerOvs.java
utils/ovsdb-it-utils/src/main/java/org/opendaylight/ovsdb/utils/ovsdb/it/utils/ItConstants.java
utils/ovsdb-it-utils/src/main/java/org/opendaylight/ovsdb/utils/ovsdb/it/utils/NodeInfo.java
utils/ovsdb-it-utils/src/main/java/org/opendaylight/ovsdb/utils/ovsdb/it/utils/ProcUtils.java
utils/servicehelper/src/main/java/org/opendaylight/ovsdb/utils/servicehelper/ServiceHelper.java
utils/servicehelper/src/test/java/org/opendaylight/ovsdb/utils/servicehelper/ServiceHelperTest.java
utils/southbound-utils/src/main/java/org/opendaylight/ovsdb/utils/southbound/utils/SouthboundUtils.java
utils/southbound-utils/src/test/java/org/opendaylight/ovsdb/utils/southbound/utils/SouthboundUtilsTest.java

index 0ce720fe2c36904c5eeadc48f3f0e3b2ccdc2572..05fc11cf3f603ea0193ba7f434bc94f09ac25e89 100644 (file)
@@ -10,7 +10,6 @@ package org.opendaylight.ovsdb.utils.hwvtepsouthbound.utils;
 
 import org.opendaylight.ovsdb.hwvtepsouthbound.HwvtepSouthboundConstants;
 import org.opendaylight.ovsdb.hwvtepsouthbound.HwvtepSouthboundMapper;
-import org.opendaylight.ovsdb.utils.mdsal.utils.MdsalUtils;
 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress;
 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.PortNumber;
 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Uri;
@@ -29,13 +28,10 @@ import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-public class HwvtepSouthboundUtils {
+public final class HwvtepSouthboundUtils {
     private static final Logger LOG = LoggerFactory.getLogger(HwvtepSouthboundUtils.class);
-    private static final int HWVTEP_UPDATE_TIMEOUT = 1000;
-    private final MdsalUtils mdsalUtils;
 
-    public HwvtepSouthboundUtils(MdsalUtils mdsalUtils) {
-        this.mdsalUtils = mdsalUtils;
+    private HwvtepSouthboundUtils() {
     }
 
     public static NodeId createNodeId(IpAddress ip, PortNumber port) {
index f8beee69408c87e977e6d4a937a1af7fe11b119e..3d1caff65fe02346186720a690c5ca3eba6d9048 100644 (file)
@@ -22,9 +22,6 @@ public class MdsalObject {
 
     @Override
     public String toString() {
-        return "MdsalObject{" +
-                "dataObject=" + dataObject +
-                ", iid=" + iid +
-                '}';
+        return "MdsalObject{" + "dataObject=" + dataObject + ", iid=" + iid + '}';
     }
 }
index f5354abf1d8a6ff8ca300ce15347f5185053ade5..50f833e09025053e4d629dbe0ca890616dec71a3 100644 (file)
@@ -22,9 +22,11 @@ import org.slf4j.LoggerFactory;
 
 public class MdsalUtils {
     private static final Logger LOG = LoggerFactory.getLogger(MdsalUtils.class);
-    private DataBroker databroker = null;
     private static int MDSAL_MAX_READ_TRIALS = Integer.getInteger("mdsalutil.max.tries", 30);
     private static int MDSAL_READ_SLEEP_INTERVAL_MS = Integer.getInteger("mdsalutil.sleep.between.mdsal.reads", 1000);
+
+    private final DataBroker databroker;
+
     /**
      * Class constructor setting the data broker.
      *
index 358a6af20835e56e984121e75beae3c67364f9bf..5dab7541d38bfb1b32f4a2ec5ece022e40df6d08 100644 (file)
@@ -12,6 +12,7 @@ import com.google.common.base.Optional;
 import com.google.common.util.concurrent.CheckedFuture;
 import com.google.common.util.concurrent.FutureCallback;
 import com.google.common.util.concurrent.Futures;
+import com.google.common.util.concurrent.MoreExecutors;
 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
 import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
 import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
@@ -185,7 +186,7 @@ public class MdsalUtilsAsync {
             }
 
             @Override
-            public void onFailure(final Throwable t) {
+            public void onFailure(final Throwable ex) {
                 transaction.close();
             }
         };
@@ -204,7 +205,8 @@ public class MdsalUtilsAsync {
      * @param operationDesc
      *            A description of the transaction to commit.
      */
-    void assignDefaultCallback(final CheckedFuture<Void, TransactionCommitFailedException> transactionFuture, final String operationDesc) {
+    void assignDefaultCallback(final CheckedFuture<Void, TransactionCommitFailedException> transactionFuture,
+            final String operationDesc) {
         Futures.addCallback(transactionFuture, new FutureCallback<Void>() {
             @Override
             public void onSuccess(final Void result) {
@@ -212,10 +214,10 @@ public class MdsalUtilsAsync {
             }
 
             @Override
-            public void onFailure(final Throwable t) {
-                LOG.error("Transaction({}) {} FAILED!", operationDesc, t);
-                throw new IllegalStateException("  Transaction(" + operationDesc + ") not committed correctly", t);
+            public void onFailure(final Throwable ex) {
+                LOG.error("Transaction({}) {} FAILED!", operationDesc, ex);
+                throw new IllegalStateException("  Transaction(" + operationDesc + ") not committed correctly", ex);
             }
-        });
+        }, MoreExecutors.directExecutor());
     }
 }
index 455dbefb246e567d7293b7b7a7de21f11cb14ecd..683e75cf4737da69260336c53ac2fd12335d568e 100644 (file)
@@ -8,9 +8,9 @@
 package org.opendaylight.ovsdb.utils.mdsal.utils;
 
 import java.util.Collection;
-import java.util.HashSet;
 import java.util.List;
 import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
 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.DataTreeChangeListener;
@@ -30,23 +30,25 @@ import org.slf4j.LoggerFactory;
  */
 public class NotifyingDataChangeListener implements AutoCloseable, DataTreeChangeListener<DataObject> {
     private static final Logger LOG = LoggerFactory.getLogger(NotifyingDataChangeListener.class);
-    private LogicalDatastoreType type;
-    private final Set<InstanceIdentifier<?>> createdIids = new HashSet<>();
-    private final Set<InstanceIdentifier<?>> removedIids = new HashSet<>();
-    private final Set<InstanceIdentifier<?>> updatedIids = new HashSet<>();
-    private InstanceIdentifier<?> iid;
-    private final static int RETRY_WAIT = 100;
-    private final static int MDSAL_TIMEOUT_OPERATIONAL = 10000;
-    private final static int MDSAL_TIMEOUT_CONFIG = 1000;
-    private ListenerRegistration<?> listenerRegistration;
-    private List<NotifyingDataChangeListener> waitList = null;
-    private int mdsalTimeout = MDSAL_TIMEOUT_OPERATIONAL;
-    private Boolean listen;
+    private static final int RETRY_WAIT = 100;
+    private static final int MDSAL_TIMEOUT_OPERATIONAL = 10000;
+    private static final int MDSAL_TIMEOUT_CONFIG = 1000;
+
     public static final int BIT_CREATE = 1;
     public static final int BIT_UPDATE = 2;
     public static final int BIT_DELETE = 4;
     public static final int BIT_ALL = 7;
-    private int mask;
+
+    private final Set<InstanceIdentifier<?>> createdIids = ConcurrentHashMap.newKeySet();
+    private final Set<InstanceIdentifier<?>> removedIids = ConcurrentHashMap.newKeySet();
+    private final Set<InstanceIdentifier<?>> updatedIids = ConcurrentHashMap.newKeySet();
+    private final List<NotifyingDataChangeListener> waitList;
+    private ListenerRegistration<?> listenerRegistration;
+    private int mdsalTimeout = MDSAL_TIMEOUT_OPERATIONAL;
+    private volatile InstanceIdentifier<?> iid;
+    private volatile  LogicalDatastoreType type;
+    private volatile boolean listen;
+    private volatile int mask;
 
     public NotifyingDataChangeListener(LogicalDatastoreType type, int mask,
                                        InstanceIdentifier<?> iid, List<NotifyingDataChangeListener> waitList) {
@@ -55,7 +57,8 @@ public class NotifyingDataChangeListener implements AutoCloseable, DataTreeChang
     }
 
     /**
-     * Create a new NotifyingDataChangeListener
+     * Create a new NotifyingDataChangeListener.
+     *
      * @param type DataStore type
      * @param iid of the md-sal object we're waiting for
      * @param waitList for tracking outstanding changes
@@ -79,19 +82,20 @@ public class NotifyingDataChangeListener implements AutoCloseable, DataTreeChang
 
     /**
      * Completely reset the state of this NotifyingDataChangeListener.
-     * @param type DataStore type
-     * @param iid of the md-sal object we're waiting for
-     * @throws Exception
+     *
+     * @param newType DataStore type
+     * @param newIid of the md-sal object we're waiting for
+     * @throws Exception on failure
      */
-    public void modify(LogicalDatastoreType type, InstanceIdentifier<?> iid) throws Exception {
+    public void modify(LogicalDatastoreType newType, InstanceIdentifier<?> newIid) throws Exception {
         this.close();
         this.clear();
-        this.type = type;
-        this.iid = iid;
+        this.type = newType;
+        this.iid = newIid;
     }
 
-    public void setlisten(Boolean listen) {
-        this.listen = listen;
+    public void setlisten(boolean value) {
+        this.listen = value;
     }
 
     public void setMask(int mask) {
@@ -136,16 +140,16 @@ public class NotifyingDataChangeListener implements AutoCloseable, DataTreeChang
         }
     }
 
-    public boolean isCreated(InstanceIdentifier<?> iid) {
-        return createdIids.remove(iid);
+    public boolean isCreated(InstanceIdentifier<?> path) {
+        return createdIids.remove(path);
     }
 
-    public boolean isUpdated(InstanceIdentifier<?> iid) {
-        return updatedIids.remove(iid);
+    public boolean isUpdated(InstanceIdentifier<?> path) {
+        return updatedIids.remove(path);
     }
 
-    public boolean isRemoved(InstanceIdentifier<?> iid) {
-        return removedIids.remove(iid);
+    public boolean isRemoved(InstanceIdentifier<?> path) {
+        return removedIids.remove(path);
     }
 
     public void clear() {
@@ -166,12 +170,12 @@ public class NotifyingDataChangeListener implements AutoCloseable, DataTreeChang
 
     public void waitForCreation(long timeout) throws InterruptedException {
         synchronized (this) {
-            long _start = System.currentTimeMillis();
+            long start = System.currentTimeMillis();
             LOG.info("Waiting for {} DataChanged creation on {}", type, iid);
-            while (!isCreated(iid) && System.currentTimeMillis() - _start < timeout) {
+            while (!isCreated(iid) && System.currentTimeMillis() - start < timeout) {
                 wait(RETRY_WAIT);
             }
-            LOG.info("Woke up, waited {}ms for creation of {}", System.currentTimeMillis() - _start, iid);
+            LOG.info("Woke up, waited {}ms for creation of {}", System.currentTimeMillis() - start, iid);
         }
     }
 
@@ -181,12 +185,12 @@ public class NotifyingDataChangeListener implements AutoCloseable, DataTreeChang
 
     public void waitForUpdate(long timeout) throws InterruptedException {
         synchronized (this) {
-            long _start = System.currentTimeMillis();
+            long start = System.currentTimeMillis();
             LOG.info("Waiting for {} DataChanged update on {}", type, iid);
-            while (!isUpdated(iid) && System.currentTimeMillis() - _start < timeout) {
+            while (!isUpdated(iid) && System.currentTimeMillis() - start < timeout) {
                 wait(RETRY_WAIT);
             }
-            LOG.info("Woke up, waited {}ms for update of {}", System.currentTimeMillis() - _start, iid);
+            LOG.info("Woke up, waited {}ms for update of {}", System.currentTimeMillis() - start, iid);
         }
     }
 
@@ -196,27 +200,25 @@ public class NotifyingDataChangeListener implements AutoCloseable, DataTreeChang
 
     public void waitForDeletion(long timeout) throws InterruptedException {
         synchronized (this) {
-            long _start = System.currentTimeMillis();
+            long start = System.currentTimeMillis();
             LOG.info("Waiting for {} DataChanged deletion on {}", type, iid);
-            while (!isRemoved(iid) && System.currentTimeMillis() - _start < timeout) {
+            while (!isRemoved(iid) && System.currentTimeMillis() - start < timeout) {
                 wait(RETRY_WAIT);
             }
-            LOG.info("Woke up, waited {}ms for deletion of {}", System.currentTimeMillis() - _start, iid);
+            LOG.info("Woke up, waited {}ms for deletion of {}", System.currentTimeMillis() - start, iid);
         }
     }
 
     @Override
-    public void close() throws Exception {
+    public void close() {
         if (listenerRegistration != null) {
-            try {
-                listenerRegistration.close();
-            } catch (final Exception ex) {
-                LOG.warn("Failed to close registration {}, iid {}", listenerRegistration, iid, ex);
-            }
+            listenerRegistration.close();
         }
+
         if (waitList != null) {
             waitList.remove(this);
         }
+
         listenerRegistration = null;
     }
 }
index 18c695b043f23b7021eb3d59ecc59fea91508b90..6ffaa0b389e914f74c8f54eb17636304cfa04360 100644 (file)
@@ -9,9 +9,9 @@
 package org.opendaylight.ovsdb.utils.mdsal.utils;
 
 public class TransactionElement {
-    private long date;
-    private TransactionType transactionType;
-    private Object data;
+    private final long date;
+    private final TransactionType transactionType;
+    private final Object data;
 
     public TransactionElement(TransactionType transactionType, Object data) {
         this.data = data;
@@ -33,10 +33,6 @@ public class TransactionElement {
 
     @Override
     public String toString() {
-        return "TransactionElement{" +
-                "date=" + date +
-                ", transactionType=" + transactionType +
-                ", data=" + data +
-                '}';
+        return "TransactionElement{" + "date=" + date + ", transactionType=" + transactionType + ", data=" + data + '}';
     }
 }
index ec45cb84fc43c7545b431ac254c01403641a2413..692e57ae845202288d6c33757c39e9b17f06fe3d 100644 (file)
@@ -8,14 +8,12 @@
 
 package org.opendaylight.ovsdb.utils.mdsal.utils;
 
+import java.util.ArrayList;
 import org.opendaylight.yangtools.yang.binding.DataObject;
 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.util.ArrayList;
 
 public class TransactionHistory extends ArrayList<TransactionElement> {
+    private static final long serialVersionUID = 1L;
 
     private final int capacity;
     private final int watermark;
index e061358e477591ee526c5d0268b3317efe44ecfd..6f5482285ab258269b2c7771a9dc437ecc22f79b 100644 (file)
@@ -8,11 +8,6 @@
 
 package org.opendaylight.ovsdb.utils.mdsal.utils;
 
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.util.ArrayList;
-
 public enum TransactionType {
     ADD,
     UPDATE,
index 1548b2f8b237ac00a06dd88297b6aa7ca70f8615..567de12cee823cc48ea17d6158a76f3f6dddc4b2 100644 (file)
@@ -16,7 +16,7 @@ import com.google.common.base.Optional;
 import com.google.common.util.concurrent.CheckedFuture;
 import com.google.common.util.concurrent.FutureCallback;
 import com.google.common.util.concurrent.Futures;
-import java.util.Arrays;
+import com.google.common.util.concurrent.MoreExecutors;
 import java.util.Collections;
 import java.util.concurrent.ExecutionException;
 import org.junit.Before;
@@ -52,7 +52,7 @@ public class MdsalUtilsAsyncTest extends AbstractDataBrokerTest {
 
     private static final NodeId NODE_ID = new NodeId("test");
     private static final NodeKey NODE_KEY =  new NodeKey(NODE_ID);
-    private static final Node data = new NodeBuilder().setKey(NODE_KEY).setNodeId(NODE_ID).build();
+    private static final Node DATA = new NodeBuilder().setKey(NODE_KEY).setNodeId(NODE_ID).build();
 
     private static final InstanceIdentifier<Node> TEST_IID = InstanceIdentifier
             .create(NetworkTopology.class)
@@ -67,12 +67,14 @@ public class MdsalUtilsAsyncTest extends AbstractDataBrokerTest {
 
     @Test
     public void testDelete() {
-        final CheckedFuture<Void, TransactionCommitFailedException> fut = mdsalUtilsAsync.put(LogicalDatastoreType.CONFIGURATION, TEST_IID, data);
+        final CheckedFuture<Void, TransactionCommitFailedException> fut = mdsalUtilsAsync.put(
+                LogicalDatastoreType.CONFIGURATION, TEST_IID, DATA);
         Futures.addCallback(fut, new FutureCallback<Void>() {
 
             @Override
             public void onSuccess(final Void result) {
-                final CheckedFuture<Void, TransactionCommitFailedException> future = mdsalUtilsAsync.delete(LogicalDatastoreType.CONFIGURATION, TEST_IID);
+                final CheckedFuture<Void, TransactionCommitFailedException> future =
+                        mdsalUtilsAsync.delete(LogicalDatastoreType.CONFIGURATION, TEST_IID);
                 Futures.addCallback(future, new FutureCallback<Void>() {
 
                     @Override
@@ -81,31 +83,37 @@ public class MdsalUtilsAsyncTest extends AbstractDataBrokerTest {
                     }
 
                     @Override
-                    public void onFailure(final Throwable t) {
-                        fail(t.getMessage());
+                    public void onFailure(final Throwable ex) {
+                        fail(ex.getMessage());
                     }
-                });
+                }, MoreExecutors.directExecutor());
             }
+
             @Override
-            public void onFailure(final Throwable t) {
-                fail(t.getMessage());
+            public void onFailure(final Throwable ex) {
+                fail(ex.getMessage());
             }
-        });
+        }, MoreExecutors.directExecutor());
     }
 
     @Test
     public void testPutWithoutCallback() {
         final String operationDesc = "testPut";
-        final SupportingNode supportingNodeBuilder1 = new SupportingNodeBuilder().setKey(new SupportingNodeKey(new NodeId("id1"), TOPOLOGY_TEST)).build();
-        final SupportingNode supportingNodeBuilder2 = new SupportingNodeBuilder().setKey(new SupportingNodeKey(new NodeId("id2"), TOPOLOGY_TEST)).build();
+        final SupportingNode supportingNodeBuilder1 = new SupportingNodeBuilder().setKey(
+                new SupportingNodeKey(new NodeId("id1"), TOPOLOGY_TEST)).build();
+        final SupportingNode supportingNodeBuilder2 = new SupportingNodeBuilder().setKey(
+                new SupportingNodeKey(new NodeId("id2"), TOPOLOGY_TEST)).build();
 
-        final Node data1 = new NodeBuilder(data).setSupportingNode(Collections.singletonList(supportingNodeBuilder1)).build();
-        final Node data2 = new NodeBuilder(data).setSupportingNode(Collections.singletonList(supportingNodeBuilder2)).build();
+        final Node data1 = new NodeBuilder(DATA).setSupportingNode(
+                Collections.singletonList(supportingNodeBuilder1)).build();
+        final Node data2 = new NodeBuilder(DATA).setSupportingNode(
+                Collections.singletonList(supportingNodeBuilder2)).build();
 
         mdsalUtilsAsync.put(LogicalDatastoreType.CONFIGURATION, TEST_IID, data1, operationDesc);
         assertEquals(data1, readDS());
 
-        final CheckedFuture<Void, TransactionCommitFailedException> future = mdsalUtilsAsync.put(LogicalDatastoreType.CONFIGURATION, TEST_IID, data2);
+        final CheckedFuture<Void, TransactionCommitFailedException> future = mdsalUtilsAsync.put(
+                LogicalDatastoreType.CONFIGURATION, TEST_IID, data2);
         Futures.addCallback(future, new FutureCallback<Void>() {
 
             @Override
@@ -114,25 +122,30 @@ public class MdsalUtilsAsyncTest extends AbstractDataBrokerTest {
             }
 
             @Override
-            public void onFailure(final Throwable t) {
-                fail(t.getMessage());
+            public void onFailure(final Throwable ex) {
+                fail(ex.getMessage());
             }
-        });
+        }, MoreExecutors.directExecutor());
     }
 
     @Test
     public void testMerge() {
         final String operationDesc = "testMerge";
-        final SupportingNode supportingNodeBuilder1 = new SupportingNodeBuilder().setKey(new SupportingNodeKey(new NodeId("id1"), TOPOLOGY_TEST)).build();
-        final SupportingNode supportingNodeBuilder2 = new SupportingNodeBuilder().setKey(new SupportingNodeKey(new NodeId("id2"), TOPOLOGY_TEST)).build();
+        final SupportingNode supportingNodeBuilder1 = new SupportingNodeBuilder().setKey(
+                new SupportingNodeKey(new NodeId("id1"), TOPOLOGY_TEST)).build();
+        final SupportingNode supportingNodeBuilder2 = new SupportingNodeBuilder().setKey(
+                new SupportingNodeKey(new NodeId("id2"), TOPOLOGY_TEST)).build();
 
-        final Node data1 = new NodeBuilder(data).setSupportingNode(Collections.singletonList(supportingNodeBuilder1)).build();
-        final Node data2 = new NodeBuilder(data).setSupportingNode(Collections.singletonList(supportingNodeBuilder2)).build();
+        final Node data1 = new NodeBuilder(DATA).setSupportingNode(
+                Collections.singletonList(supportingNodeBuilder1)).build();
+        final Node data2 = new NodeBuilder(DATA).setSupportingNode(
+                Collections.singletonList(supportingNodeBuilder2)).build();
 
         mdsalUtilsAsync.merge(LogicalDatastoreType.CONFIGURATION, TEST_IID, data1, operationDesc, true);
         assertEquals(data1, readDS());
 
-        final CheckedFuture<Void, TransactionCommitFailedException> future = mdsalUtilsAsync.merge(LogicalDatastoreType.CONFIGURATION, TEST_IID, data2, true);
+        final CheckedFuture<Void, TransactionCommitFailedException> future =
+                mdsalUtilsAsync.merge(LogicalDatastoreType.CONFIGURATION, TEST_IID, data2, true);
         Futures.addCallback(future, new FutureCallback<Void>() {
 
             @Override
@@ -141,26 +154,27 @@ public class MdsalUtilsAsyncTest extends AbstractDataBrokerTest {
             }
 
             @Override
-            public void onFailure(final Throwable t) {
-                fail(t.getMessage());
+            public void onFailure(final Throwable ex) {
+                fail(ex.getMessage());
             }
-        });
+        }, MoreExecutors.directExecutor());
     }
 
     @Test
     public void testRead() {
-        final CheckedFuture<Void, TransactionCommitFailedException> fut = mdsalUtilsAsync.put(LogicalDatastoreType.CONFIGURATION, TEST_IID, data);
+        final CheckedFuture<Void, TransactionCommitFailedException> fut =
+                mdsalUtilsAsync.put(LogicalDatastoreType.CONFIGURATION, TEST_IID, DATA);
 
         Futures.addCallback(fut, new FutureCallback<Void>() {
-
             @Override
             public void onSuccess(final Void result) {
-                final CheckedFuture<Optional<Node>, ReadFailedException> future = mdsalUtilsAsync.read(LogicalDatastoreType.CONFIGURATION, TEST_IID);
+                final CheckedFuture<Optional<Node>, ReadFailedException> future =
+                        mdsalUtilsAsync.read(LogicalDatastoreType.CONFIGURATION, TEST_IID);
                 Optional<Node> optNode;
                 try {
                     optNode = future.get();
                     if (optNode.isPresent()) {
-                        assertEquals(data, optNode.get());
+                        assertEquals(DATA, optNode.get());
                     } else {
                         fail("Couldn't read node");
                     }
@@ -170,15 +184,16 @@ public class MdsalUtilsAsyncTest extends AbstractDataBrokerTest {
             }
 
             @Override
-            public void onFailure(final Throwable t) {
-                fail(t.getMessage());
+            public void onFailure(final Throwable ex) {
+                fail(ex.getMessage());
             }
-        });
+        }, MoreExecutors.directExecutor());
     }
 
     private Node readDS() {
         try {
-            final Optional<Node> result = databroker.newReadOnlyTransaction().read(LogicalDatastoreType.CONFIGURATION, TEST_IID).get();
+            final Optional<Node> result = databroker.newReadOnlyTransaction().read(
+                    LogicalDatastoreType.CONFIGURATION, TEST_IID).get();
             if (result.isPresent()) {
                 return result.get();
             }
index fe852c3fe2977655f503879e57c5276b305ba94f..c88e25a9307624cead7262e463ff24b51217b8c8 100644 (file)
@@ -16,6 +16,8 @@ import static org.mockito.Mockito.times;
 import static org.mockito.Mockito.verify;
 import static org.mockito.Mockito.when;
 
+import com.google.common.base.Optional;
+import com.google.common.util.concurrent.CheckedFuture;
 import org.junit.Test;
 import org.junit.runner.RunWith;
 import org.mockito.InjectMocks;
@@ -30,12 +32,8 @@ import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFaile
 import org.opendaylight.yangtools.yang.binding.DataObject;
 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
 
-import com.google.common.base.Optional;
-import com.google.common.util.concurrent.CheckedFuture;
-
 /**
- * Unit test for class {@link MdsalUtils}
- *
+ * Unit test for class {@link MdsalUtils}.
  */
 @RunWith(MockitoJUnitRunner.class)
 @SuppressWarnings({ "unchecked", "rawtypes" })
@@ -50,7 +48,7 @@ public class MdsalUtilsTest {
         WriteTransaction writeTransaction = mock(WriteTransaction.class);
         when(databroker.newWriteOnlyTransaction()).thenReturn(writeTransaction);
         CheckedFuture<Void, TransactionCommitFailedException> future = mock(CheckedFuture.class);
-        when(writeTransaction.submit()).thenReturn(future );
+        when(writeTransaction.submit()).thenReturn(future);
 
         boolean result = mdsalUtils.delete(LogicalDatastoreType.CONFIGURATION, mock(InstanceIdentifier.class));
 
@@ -65,11 +63,13 @@ public class MdsalUtilsTest {
         WriteTransaction writeTransaction = mock(WriteTransaction.class);
         when(databroker.newWriteOnlyTransaction()).thenReturn(writeTransaction);
         CheckedFuture<Void, TransactionCommitFailedException> future = mock(CheckedFuture.class);
-        when(writeTransaction.submit()).thenReturn(future );
+        when(writeTransaction.submit()).thenReturn(future);
 
-        boolean result = mdsalUtils.merge(LogicalDatastoreType.CONFIGURATION, mock(InstanceIdentifier.class), mock(DataObject.class));
+        boolean result = mdsalUtils.merge(LogicalDatastoreType.CONFIGURATION,
+                mock(InstanceIdentifier.class), mock(DataObject.class));
 
-        verify(writeTransaction, times(1)).merge(any(LogicalDatastoreType.class), any(InstanceIdentifier.class), any(DataObject.class), anyBoolean());
+        verify(writeTransaction, times(1)).merge(any(LogicalDatastoreType.class),
+                any(InstanceIdentifier.class), any(DataObject.class), anyBoolean());
         verify(writeTransaction, times(1)).submit();
 
         assertTrue("Error, the merge transaction failed", result);
@@ -80,11 +80,13 @@ public class MdsalUtilsTest {
         WriteTransaction writeTransaction = mock(WriteTransaction.class);
         when(databroker.newWriteOnlyTransaction()).thenReturn(writeTransaction);
         CheckedFuture<Void, TransactionCommitFailedException> future = mock(CheckedFuture.class);
-        when(writeTransaction.submit()).thenReturn(future );
+        when(writeTransaction.submit()).thenReturn(future);
 
-        boolean result = mdsalUtils.put(LogicalDatastoreType.CONFIGURATION, mock(InstanceIdentifier.class), mock(DataObject.class));
+        boolean result = mdsalUtils.put(LogicalDatastoreType.CONFIGURATION,
+                mock(InstanceIdentifier.class), mock(DataObject.class));
 
-        verify(writeTransaction, times(1)).put(any(LogicalDatastoreType.class), any(InstanceIdentifier.class), any(DataObject.class), anyBoolean());
+        verify(writeTransaction, times(1)).put(any(LogicalDatastoreType.class),
+                any(InstanceIdentifier.class), any(DataObject.class), anyBoolean());
         verify(writeTransaction, times(1)).submit();
 
         assertTrue("Error, the put transaction failed", result);
@@ -98,7 +100,8 @@ public class MdsalUtilsTest {
         DataObject obj = mock(DataObject.class);
         Optional opt = Optional.of(obj);
         when(future.checkedGet()).thenReturn(opt);
-        when(readOnlyTransaction.read(any(LogicalDatastoreType.class), any(InstanceIdentifier.class))).thenReturn(future);
+        when(readOnlyTransaction.read(any(LogicalDatastoreType.class),
+                any(InstanceIdentifier.class))).thenReturn(future);
 
         DataObject result = mdsalUtils.read(LogicalDatastoreType.CONFIGURATION, mock(InstanceIdentifier.class));
 
index d747d2486d71b5d814db4d68c58123a1ec925cf2..72b56e2ea3eff525babdf8a815cde6b7bd2b74f8 100644 (file)
@@ -8,12 +8,16 @@
 
 package org.opendaylight.ovsdb.utils.ovsdb.it.utils;
 
+import static org.ops4j.pax.exam.CoreOptions.propagateSystemProperties;
+
+import com.esotericsoftware.yamlbeans.YamlException;
+import com.esotericsoftware.yamlbeans.YamlReader;
 import java.io.File;
 import java.io.FileNotFoundException;
 import java.io.FileReader;
 import java.io.FileWriter;
-import java.io.InputStreamReader;
 import java.io.IOException;
+import java.io.InputStreamReader;
 import java.io.Reader;
 import java.net.InetSocketAddress;
 import java.net.URL;
@@ -29,9 +33,6 @@ import java.util.List;
 import java.util.Map;
 import java.util.Properties;
 import java.util.concurrent.atomic.AtomicInteger;
-
-import com.esotericsoftware.yamlbeans.YamlException;
-import com.esotericsoftware.yamlbeans.YamlReader;
 import org.junit.Assert;
 import org.ops4j.pax.exam.Option;
 import org.osgi.framework.Bundle;
@@ -39,8 +40,6 @@ import org.osgi.framework.FrameworkUtil;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-import static org.ops4j.pax.exam.CoreOptions.propagateSystemProperties;
-
 /**
  * Run OVS(s) using docker-compose for use in integration tests.
  * For example,
@@ -66,19 +65,22 @@ import static org.ops4j.pax.exam.CoreOptions.propagateSystemProperties;
  * to accept OVSDB connections.
  * Any docker-compose file must have a port mapping.
  *
+ * <p>
  * The following explains how system properties are used to configure DockerOvs
  * <pre>
  *  private static String ENV_USAGE =
  *  "-Ddocker.run - explicitly configure whether or not DockerOvs should run docker-compose\n" +
  *  "-Dovsdbserver.ipaddress - specify IP address of ovsdb server - implies -Ddocker.run=false\n" +
  *  "-Dovsdbserver.port - specify the port of the ovsdb server - required with -Dovsdbserver.ipaddress\n" +
- *  "-Ddocker.compose.file - docker compose file in META-INF/docker-compose-files/. If not specified, default file is used\n" +
+ *  "-Ddocker.compose.file - docker compose file in META-INF/docker-compose-files/.
+ *      If not specified, default file is used\n" +
  *  "-Dovsdb.userspace.enabled - true when Ovs is running in user space (usually the case with docker)\n" +
  *  "-Dovsdb.controller.address - IP address of the controller (usually the docker0 interface with docker)\n" +
  *  "To auto-run Ovs and connect actively:\n" +
  *  " -Dovsdb.controller.address=x.x.x.x -Dovsdb.userspace.enabled=yes [-Ddocker.compose.file=ffff]\n" +
  *  "To auto-run Ovs and connect passively:\n" +
- *  " -Dovsdbserver.connection=passive -Dovsdb.controller.address=x.x.x.x -Dovsdb.userspace.enabled=yes [-Ddocker.compose.file=ffff]\n" +
+ *  " -Dovsdbserver.connection=passive -Dovsdb.controller.address=x.x.x.x
+ *    -Dovsdb.userspace.enabled=yes [-Ddocker.compose.file=ffff]\n" +
  *  "To actively connect to a running Ovs:\n" +
  *  " -Dovsdbserver.ipaddress=x.x.x.x -Dovsdbserver.port=6641 -Dovsdb.controller.address=y.y.y.y\n" +
  *  "To passively connect to a running Ovs:\n" +
@@ -91,21 +93,22 @@ import static org.ops4j.pax.exam.CoreOptions.propagateSystemProperties;
  * the system properties.
  */
 public class DockerOvs implements AutoCloseable {
-    private static String ENV_USAGE = "Usage:\n" +
-            "-Ddocker.run - explicitly configure whether or not DockerOvs should run docker-compose\n" +
-                    "-Dovsdbserver.ipaddress - specify IP address of ovsdb server - implies -Ddocker.run=false\n" +
-                    "-Dovsdbserver.port - specify the port of the ovsdb server - required with -Dovsdbserver.ipaddress\n" +
-                    "-Ddocker.compose.file - docker compose file in META-INF/docker-compose-files/. If not specified, default file is used\n" +
-                    "-Dovsdb.userspace.enabled - true when Ovs is running in user space (usually the case with docker)\n" +
-                    "-Dovsdb.controller.address - IP address of the controller (usually the docker0 interface with docker)\n" +
-                    "To auto-run Ovs and connect actively:\n" +
-                    " -Dovsdb.controller.address=x.x.x.x -Dovsdb.userspace.enabled=yes <-Ddocker.compose.file=ffff>\n" +
-                    "To auto-run Ovs and connect passively:\n" +
-                    " -Dovsdbserver.connection=passive -Dovsdb.controller.address=x.x.x.x -Dovsdb.userspace.enabled=yes <-Ddocker.compose.file=ffff>\n" +
-                    "To actively connect to a running Ovs:\n" +
-                    " -Dovsdbserver.ipaddress=x.x.x.x -Dovsdbserver.port=6641 -Dovsdb.controller.address=y.y.y.y\n" +
-                    "To passively connect to a running Ovs:\n" +
-                    " -Dovsdbserver.connection=passive -Ddocker.run=false\n";
+    private static String ENV_USAGE = "Usage:\n"
+        + "-Ddocker.run - explicitly configure whether or not DockerOvs should run docker-compose\n"
+        + "-Dovsdbserver.ipaddress - specify IP address of ovsdb server - implies -Ddocker.run=false\n"
+        + "-Dovsdbserver.port - specify the port of the ovsdb server - required with -Dovsdbserver.ipaddress\n"
+        + "-Ddocker.compose.file - docker compose file in META-INF/docker-compose-files/. "
+        + "If not specified, default file is used\n"
+        + "-Dovsdb.userspace.enabled - true when Ovs is running in user space (usually the case with docker)\n"
+        + "-Dovsdb.controller.address - IP address of the controller (usually the docker0 interface with docker)\n"
+        + "To auto-run Ovs and connect actively:\n"
+        + " -Dovsdb.controller.address=x.x.x.x -Dovsdb.userspace.enabled=yes <-Ddocker.compose.file=ffff>\n"
+        + "To auto-run Ovs and connect passively:\n"
+        + " -Dovsdbserver.connection=passive -Dovsdb.controller.address=x.x.x.x -Dovsdb.userspace.enabled=yes "
+        + "<-Ddocker.compose.file=ffff>\n"
+        + "To actively connect to a running Ovs:\n"
+        + " -Dovsdbserver.ipaddress=x.x.x.x -Dovsdbserver.port=6641 -Dovsdb.controller.address=y.y.y.y\n"
+        + "To passively connect to a running Ovs:\n" + " -Dovsdbserver.connection=passive -Ddocker.run=false\n";
 
     private static final Logger LOG = LoggerFactory.getLogger(DockerOvs.class);
     private static final String DEFAULT_DOCKER_FILE = "ovs-2.5.0-hwvtep.yml";
@@ -121,11 +124,11 @@ public class DockerOvs implements AutoCloseable {
     private String[] downCmd = {"sudo", "docker-compose", "-f", null, "stop"};
     private String[] execCmd = {"sudo", "docker-compose", "-f", null, "exec", null};
 
-    private String[] dockerPsCmdNoSudo = {"docker", "ps"};
-    private String[] dockerPsCmd = {"sudo", "docker", "ps"};
+    private final String[] dockerPsCmdNoSudo = {"docker", "ps"};
+    private final String[] dockerPsCmd = {"sudo", "docker", "ps"};
     private String[] netInspectCmd = {"sudo", "docker", "network", "inspect", "odl"};
     private String[] netCreateCmd = {"sudo", "docker", "network", "create",
-                                                            "--subnet=172.99.0.0/16", "--gateway=172.99.0.254", "odl"};
+                                     "--subnet=172.99.0.0/16", "--gateway=172.99.0.254", "odl"};
 
     private File tmpDockerComposeFile;
     boolean isRunning;
@@ -134,14 +137,14 @@ public class DockerOvs implements AutoCloseable {
     private String envDockerComposeFile;
     private String envDockerWaitForPing;
     private boolean runDocker;
-    private boolean runVenv;
     private boolean createOdlNetwork;
 
     class DockerComposeServiceInfo {
         public String name;
         public String port;
     }
-    private Map<String, DockerComposeServiceInfo> dockerComposeServices = new HashMap<>();
+
+    private final Map<String, DockerComposeServiceInfo> dockerComposeServices = new HashMap<>();
 
     /**
      * Get the array of system properties as pax exam Option objects for use in pax exam
@@ -203,17 +206,12 @@ public class DockerOvs implements AutoCloseable {
 
     private void setupEnvForDockerCompose(String venvWs) {
         String dockerCompose = venvWs + "/venv/bin/docker-compose";
-        String[] psCmdVenv = {"sudo", dockerCompose, "-f", null, "ps"};
-        String[] psCmdNoSudoVenv = {dockerCompose, "-f", null, "ps"};
-        String[] upCmdVenv = {"sudo", dockerCompose, "-f", null, "up", "-d", "--force-recreate"};
-        String[] downCmdVenv = {"sudo", dockerCompose, "-f", null, "stop"};
-        String[] execCmdVenv = {"sudo", dockerCompose, "-f", null, "exec", null};
-
-        psCmd = psCmdVenv;
-        psCmdNoSudo = psCmdNoSudoVenv;
-        upCmd = upCmdVenv;
-        downCmd = downCmdVenv;
-        execCmd = execCmdVenv;
+
+        psCmd = new String[]{"sudo", dockerCompose, "-f", null, "ps"};
+        psCmdNoSudo = new String[]{dockerCompose, "-f", null, "ps"};
+        upCmd = new String[]{"sudo", dockerCompose, "-f", null, "up", "-d", "--force-recreate"};
+        downCmd = new String[]{"sudo", dockerCompose, "-f", null, "stop"};
+        execCmd = new String[]{"sudo", dockerCompose, "-f", null, "exec", null};
     }
 
     /**
@@ -229,25 +227,25 @@ public class DockerOvs implements AutoCloseable {
         envDockerWaitForPing = env.getProperty(ItConstants.DOCKER_WAIT_FOR_PING_SECS, "10");
         createOdlNetwork = env.getProperty(ItConstants.CONTROLLER_IPADDRESS) == null;
         String envRunDocker = env.getProperty(ItConstants.DOCKER_RUN);
-        String connType = env.getProperty(ItConstants.CONNECTION_TYPE, ItConstants.CONNECTION_TYPE_ACTIVE);
         String dockerFile = env.getProperty(ItConstants.DOCKER_COMPOSE_FILE_NAME);
         String venvWs = env.getProperty(ItConstants.DOCKER_VENV_WS);
         envDockerComposeFile = DOCKER_FILE_PATH + (null == dockerFile ? DEFAULT_DOCKER_FILE : dockerFile);
 
         //Are we running docker? If we specified docker.run, that's the answer. Otherwise, if there is a server
         //address we assume docker is already running
-        runDocker = (envRunDocker != null) ? Boolean.parseBoolean(envRunDocker) : envServerAddress == null;
+        runDocker = envRunDocker != null ? Boolean.parseBoolean(envRunDocker) : envServerAddress == null;
 
         //Should we run in a virtual environment? Needed for jenkins and docker-compose
-        if ((venvWs != null) && (!venvWs.isEmpty())) {
+        if (venvWs != null && !venvWs.isEmpty()) {
             LOG.info("Setting up virtual environment for docker compose");
             setupEnvForDockerCompose(venvWs);
         }
 
-        if(runDocker) {
+        if (runDocker) {
             return;
         }
 
+        String connType = env.getProperty(ItConstants.CONNECTION_TYPE, ItConstants.CONNECTION_TYPE_ACTIVE);
         if (connType.equals(ItConstants.CONNECTION_TYPE_PASSIVE)) {
             return;
         }
@@ -314,7 +312,8 @@ public class DockerOvs implements AutoCloseable {
     }
 
     /**
-     * Are we using some other OVS, not a docker we spin up?
+     * Are we using some other OVS, not a docker we spin up?.
+     *
      * @return true if we are *not* running a docker image to test against
      */
     public boolean usingExternalDocker() {
@@ -367,6 +366,7 @@ public class DockerOvs implements AutoCloseable {
             return "ovs" + numOvs;
         }
     }
+
     public String[] getExecCmdPrefix(int numOvs) {
         String[] res = new String[execCmd.length];
         System.arraycopy(execCmd, 0, res, 0, execCmd.length);
@@ -468,20 +468,15 @@ public class DockerOvs implements AutoCloseable {
 
     /**
      * Shut everything down.
-     * @throws Exception but not really
      */
     @Override
-    public void close() throws Exception {
+    public void close() throws IOException, InterruptedException {
         if (isRunning) {
             ProcUtils.runProcess(10000, downCmd);
             isRunning = false;
         }
 
-        try {
-            tmpDockerComposeFile.delete();
-        } catch (Exception ignored) {
-            //No reason to fail the test, we're just being polite here.
-        }
+        tmpDockerComposeFile.delete();
     }
 
     /**
@@ -490,7 +485,7 @@ public class DockerOvs implements AutoCloseable {
      * checked to make sure the Open_Vswitch DB is present. Note that this thread will
      * run until it succeeds unless its interrupt() method is called.
      */
-    class OvsdbPing extends Thread {
+    private class OvsdbPing extends Thread {
 
         private final String host;
         private final int port;
@@ -503,7 +498,7 @@ public class DockerOvs implements AutoCloseable {
          * @param ovsNumber which OVS is this?
          * @param result an AtomicInteger that is incremented upon a successful "ping"
          */
-        public OvsdbPing(int ovsNumber, AtomicInteger result) {
+        OvsdbPing(int ovsNumber, AtomicInteger result) {
             this.host = getOvsdbAddress(ovsNumber);
             this.port = Integer.parseInt(getOvsdbPort(ovsNumber));
             this.result = result;
@@ -547,8 +542,8 @@ public class DockerOvs implements AutoCloseable {
                 LOG.warn("OvsdbPing interrupted", e);
                 //return true here because we're done, ne'er to return again.
                 return true;
-            } catch (Exception e) {
-                LOG.info("OvsdbPing exception while attempting connect {}", e.toString());
+            } catch (IOException e) {
+                LOG.info("OvsdbPing exception while attempting connect", e);
             }
             return false;
         }
@@ -574,13 +569,13 @@ public class DockerOvs implements AutoCloseable {
             pingers[0].start();
         } else {
             for (int i = 0; i < numOvs; i++) {
-                pingers[i] = new OvsdbPing(i+1, numRunningOvs);
+                pingers[i] = new OvsdbPing(i + 1, numRunningOvs);
                 pingers[i].start();
             }
         }
 
         long startTime = System.currentTimeMillis();
-        while ( (System.currentTimeMillis() - startTime) < waitFor) {
+        while (System.currentTimeMillis() - startTime < waitFor) {
             if (numRunningOvs.get() >= numOvs) {
                 LOG.info("DockerOvs.waitForOvsdbServers all OVS instances running");
                 break;
index fe4b24786951c942810756168d590aeb62fa1540..50813c6a9226a3a87865fe6678f8490663f21b22 100644 (file)
@@ -11,33 +11,29 @@ package org.opendaylight.ovsdb.utils.ovsdb.it.utils;
 /**
  * Constants for SouthboundIT.
  */
-public final class ItConstants {
-    private ItConstants() {
-        throw new AssertionError("This class should not be instantiated.");
-    }
-
-    public static final String ORG_OPS4J_PAX_LOGGING_CFG = "etc/org.ops4j.pax.logging.cfg";
-    public static final String CUSTOM_PROPERTIES = "etc/custom.properties";
-    public static final String SERVER_IPADDRESS = "ovsdbserver.ipaddress";
-    public static final String SERVER_PORT = "ovsdbserver.port";
-    public static final String CONTROLLER_IPADDRESS = "ovsdb.controller.address";
-    public static final String USERSPACE_ENABLED = "ovsdb.userspace.enabled";
-    public static final String SERVER_EXTRAS = "ovsdbserver.extras";
-    public static final String CONNECTION_TYPE = "ovsdbserver.connection";
-    public static final String CONNECTION_TYPE_ACTIVE = "active";
-    public static final String CONNECTION_TYPE_PASSIVE = "passive";
-    public static final int CONNECTION_INIT_TIMEOUT = 10000;
-    public static final String DEFAULT_SERVER_IPADDRESS = "127.0.0.1";
-    public static final String DEFAULT_SERVER_PORT = "6640";
-    public static final String DEFAULT_OPENFLOW_PORT = "6653";
-    public static final String DEFAULT_SERVER_EXTRAS = "false";
-    public static final String BRIDGE_NAME = "brtest";
-    public static final String PORT_NAME = "porttest";
-    public static final String INTEGRATION_BRIDGE_NAME = "br-int";
-    public static final String OPENFLOW_CONNECTION_PROTOCOL = "tcp";
-    public static final String NETVIRT_TOPOLOGY_ID = "netvirt:1";
-    public static final String DOCKER_COMPOSE_FILE_NAME="docker.compose.file";
-    public static final String DOCKER_RUN="docker.run";
-    public static final String DOCKER_VENV_WS="docker.vEnvWs";
-    public static final String DOCKER_WAIT_FOR_PING_SECS = "docker.ping.wait.secs";
+public interface ItConstants {
+    String ORG_OPS4J_PAX_LOGGING_CFG = "etc/org.ops4j.pax.logging.cfg";
+    String CUSTOM_PROPERTIES = "etc/custom.properties";
+    String SERVER_IPADDRESS = "ovsdbserver.ipaddress";
+    String SERVER_PORT = "ovsdbserver.port";
+    String CONTROLLER_IPADDRESS = "ovsdb.controller.address";
+    String USERSPACE_ENABLED = "ovsdb.userspace.enabled";
+    String SERVER_EXTRAS = "ovsdbserver.extras";
+    String CONNECTION_TYPE = "ovsdbserver.connection";
+    String CONNECTION_TYPE_ACTIVE = "active";
+    String CONNECTION_TYPE_PASSIVE = "passive";
+    int CONNECTION_INIT_TIMEOUT = 10000;
+    String DEFAULT_SERVER_IPADDRESS = "127.0.0.1";
+    String DEFAULT_SERVER_PORT = "6640";
+    String DEFAULT_OPENFLOW_PORT = "6653";
+    String DEFAULT_SERVER_EXTRAS = "false";
+    String BRIDGE_NAME = "brtest";
+    String PORT_NAME = "porttest";
+    String INTEGRATION_BRIDGE_NAME = "br-int";
+    String OPENFLOW_CONNECTION_PROTOCOL = "tcp";
+    String NETVIRT_TOPOLOGY_ID = "netvirt:1";
+    String DOCKER_COMPOSE_FILE_NAME = "docker.compose.file";
+    String DOCKER_RUN = "docker.run";
+    String DOCKER_VENV_WS = "docker.vEnvWs";
+    String DOCKER_WAIT_FOR_PING_SECS = "docker.ping.wait.secs";
 }
index 54fdedd0d32c4dca8703e4fc4a791ebecf5e7282..0950fe6da8a35c2739fadddaa7e2f772e9c95da7 100644 (file)
@@ -14,7 +14,6 @@ import static org.junit.Assert.assertNull;
 import static org.junit.Assert.assertTrue;
 
 import java.util.List;
-
 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
 import org.opendaylight.ovsdb.utils.mdsal.utils.NotifyingDataChangeListener;
 import org.opendaylight.ovsdb.utils.southbound.utils.SouthboundUtils;
@@ -32,16 +31,16 @@ public class NodeInfo {
     private static final Logger LOG = LoggerFactory.getLogger(NodeInfo.class);
     public static final String INTEGRATION_BRIDGE_NAME = "br-int";
 
-    private ConnectionInfo connectionInfo;
-    private InstanceIdentifier<Node> ovsdbIid;
-    InstanceIdentifier<Node> bridgeIid;
+    private final ConnectionInfo connectionInfo;
+    private final InstanceIdentifier<Node> ovsdbIid;
+    private final InstanceIdentifier<Node> bridgeIid;
     public long datapathId;
     public Node ovsdbNode;
     public Node bridgeNode;
-    NotifyingDataChangeListener ovsdbWaiter;
-    NotifyingDataChangeListener bridgeWaiter;
-    List<NotifyingDataChangeListener> waitList;
-    OvsdbItUtils itUtils;
+    private NotifyingDataChangeListener ovsdbWaiter;
+    private NotifyingDataChangeListener bridgeWaiter;
+    private final List<NotifyingDataChangeListener> waitList;
+    private final OvsdbItUtils itUtils;
 
     /**
      * Create a new NodeInfo object.
@@ -106,13 +105,11 @@ public class NodeInfo {
         bridgeWaiter.setMask(NotifyingDataChangeListener.BIT_DELETE);
         assertTrue(itUtils.southboundUtils.deleteBridge(connectionInfo, INTEGRATION_BRIDGE_NAME, 0));
         bridgeWaiter.waitForDeletion();
-        Node bridgeNode = itUtils.mdsalUtils.read(LogicalDatastoreType.OPERATIONAL, bridgeIid);
-        assertNull("Bridge should not be found", bridgeNode);
+        assertNull("Bridge should not be found", itUtils.mdsalUtils.read(LogicalDatastoreType.OPERATIONAL, bridgeIid));
         assertTrue(itUtils.southboundUtils.disconnectOvsdbNode(connectionInfo, 0));
         ovsdbWaiter.waitForDeletion();
-        Node ovsdbNode = itUtils.mdsalUtils.read(LogicalDatastoreType.OPERATIONAL, ovsdbIid);
-        assertNull("Ovsdb node should not be found", ovsdbNode);
+        assertNull("Ovsdb node should not be found",
+                itUtils.mdsalUtils.read(LogicalDatastoreType.OPERATIONAL, ovsdbIid));
         closeWaiters();
     }
-
 }
index d6d01eb111b344c5d925ca9bb23e80ca32da132c..1fa708f82e5513210dd080e2bdbca0f1ae1f18f1 100644 (file)
@@ -11,7 +11,6 @@ package org.opendaylight.ovsdb.utils.ovsdb.it.utils;
 import java.io.BufferedReader;
 import java.io.IOException;
 import java.io.InputStreamReader;
-
 import org.junit.Assert;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
@@ -19,9 +18,12 @@ import org.slf4j.LoggerFactory;
 /**
  * Run subprocesses and log or return their output.
  */
-public class ProcUtils {
+public final class ProcUtils {
     private static final Logger LOG = LoggerFactory.getLogger(ProcUtils.class);
 
+    private ProcUtils() {
+    }
+
      /**
      * Run a process and assert the exit code is 0.
      * @param waitFor How long to wait for the command to execute
@@ -97,7 +99,7 @@ public class ProcUtils {
                         logText != null ? logText : "", stderr.readLine());
             }
 
-            StringBuilder stdoutStringBuilder = (capturedStdout != null) ? capturedStdout : new StringBuilder();
+            StringBuilder stdoutStringBuilder = capturedStdout != null ? capturedStdout : new StringBuilder();
             int read;
             char[] buf = new char[1024];
             while (-1 != (read = stdout.read(buf))) {
@@ -131,7 +133,7 @@ public class ProcUtils {
                 exitValue = proc.exitValue();
                 break;
             } catch (IllegalThreadStateException e) {
-                if ((System.currentTimeMillis() - startTime) < waitFor) {
+                if (System.currentTimeMillis() - startTime < waitFor) {
                     Thread.sleep(200);
                 } else {
                     LOG.warn("ProcUtils.waitForExitValue: timed out while waiting for command to complete", e);
index 402a9949388897672dd8e5826a3dd5c87844570d..45e36bde4c2227370fc0c8b0284c4cd29b1bf4f0 100644 (file)
@@ -10,21 +10,24 @@ package org.opendaylight.ovsdb.utils.servicehelper;
 
 import java.util.HashMap;
 import java.util.Map;
-
 import org.osgi.framework.Bundle;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
 import org.osgi.framework.BundleContext;
 import org.osgi.framework.FrameworkUtil;
+import org.osgi.framework.InvalidSyntaxException;
 import org.osgi.framework.ServiceReference;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 
 /**
- * The class helps to register and retrieve OSGi service registry
+ * The class helps to register and retrieve OSGi service registry.
  */
 public final class ServiceHelper {
     private static final Logger LOG = LoggerFactory.getLogger(ServiceHelper.class);
     private static final Map<Class<?>, Object> OVERRIDES = new HashMap<>();
 
+    private ServiceHelper() {
+    }
+
     /**
      * Override a global instance. This should generally only be used for testing.
      *
@@ -70,7 +73,7 @@ public final class ServiceHelper {
     /**
      * Retrieve all the Instances of a Service, optionally
      * filtered via serviceFilter if non-null else all the results are
-     * returned if null
+     * returned if null.
      *
      * @param clazz The target class
      * @param bundle The caller
@@ -78,23 +81,23 @@ public final class ServiceHelper {
      */
     private static Object[] getGlobalInstances(Class<?> clazz, Object bundle,
                                               String serviceFilter) {
-        Object instances[] = null;
+        Object[] instances = null;
         try {
             Bundle ourBundle = FrameworkUtil.getBundle(bundle.getClass());
             if (ourBundle != null) {
-                BundleContext bCtx = ourBundle.getBundleContext();
+                BundleContext bundleContext = ourBundle.getBundleContext();
 
-                ServiceReference<?>[] services = bCtx.getServiceReferences(clazz
+                ServiceReference<?>[] services = bundleContext.getServiceReferences(clazz
                         .getName(), serviceFilter);
 
                 if (services != null) {
                     instances = new Object[services.length];
                     for (int i = 0; i < services.length; i++) {
-                        instances[i] = bCtx.getService(services[i]);
+                        instances[i] = bundleContext.getService(services[i]);
                     }
                 }
             }
-        } catch (Exception e) {
+        } catch (IllegalStateException | InvalidSyntaxException e) {
             LOG.error("Error retrieving global instances of {} from caller {} with filter {}",
                     clazz, bundle, serviceFilter, e);
         }
index 95286b54ae278b522beaa9e1bfeb249ed4deb11e..3a0cebb4bb16c528a512c153323ff23ca8f081c3 100644 (file)
@@ -13,7 +13,6 @@ import static org.mockito.Matchers.any;
 
 import org.junit.Test;
 import org.junit.runner.RunWith;
-import org.osgi.framework.Bundle;
 import org.osgi.framework.FrameworkUtil;
 import org.powermock.api.mockito.PowerMockito;
 import org.powermock.core.classloader.annotations.PrepareForTest;
@@ -31,9 +30,7 @@ public class ServiceHelperTest {
      * Test method for
      * {@link ServiceHelper#getGlobalInstance(Class, Object)}
      */
-    public void getGlobalInstanceTest () {
-        Bundle bundle = new MockBundle();
-
+    public void getGlobalInstanceTest() {
         PowerMockito.mockStatic(FrameworkUtil.class);
 
         PowerMockito.when(FrameworkUtil.getBundle(any(Class.class)))
@@ -42,7 +39,7 @@ public class ServiceHelperTest {
         assertNull("Service should be null", object);
 
         PowerMockito.when(FrameworkUtil.getBundle(any(Class.class)))
-                .thenReturn(bundle);
+                .thenReturn(new MockBundle());
         object = ServiceHelper.getGlobalInstance(Test.class, this);
         assertNotNull("Service should not be null", object);
     }
index 9923ce79709d038ee782fc9ab2099ebb1c045f89..4d2c3b7edd02cadbf4d022856a8d5d002fe53208 100644 (file)
@@ -8,11 +8,13 @@
 
 package org.opendaylight.ovsdb.utils.southbound.utils;
 
+import com.google.common.collect.ImmutableBiMap;
 import java.math.BigInteger;
 import java.net.Inet4Address;
 import java.net.Inet6Address;
 import java.net.InetAddress;
 import java.net.NetworkInterface;
+import java.net.SocketException;
 import java.net.UnknownHostException;
 import java.security.InvalidParameterException;
 import java.util.ArrayList;
@@ -21,7 +23,6 @@ import java.util.Enumeration;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
-
 import java.util.regex.Matcher;
 import java.util.regex.Pattern;
 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
@@ -106,8 +107,6 @@ import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-import com.google.common.collect.ImmutableBiMap;
-
 public class SouthboundUtils {
     private static final Logger LOG = LoggerFactory.getLogger(SouthboundUtils.class);
     private static final int OVSDB_UPDATE_TIMEOUT = 1000;
@@ -199,11 +198,6 @@ public class SouthboundUtils {
         return createInstanceIdentifier(createManagedNodeId(ovsdbNodeKey.getNodeId(), bridgeName));
     }
 
-    public static NodeId createManagedNodeId(NodeId ovsdbNodeId, String bridgeName) {
-        return new NodeId(ovsdbNodeId.getValue()
-                + "/" + BRIDGE_URI_PREFIX + "/" + bridgeName);
-    }
-
     public static InstanceIdentifier<Node> createInstanceIdentifier(ConnectionInfo key) {
         return createInstanceIdentifier(key.getRemoteIp(), key.getRemotePort());
     }
@@ -217,7 +211,7 @@ public class SouthboundUtils {
         return path;
     }
 
-    public static InstanceIdentifier<Node> createInstanceIdentifier(ConnectionInfo key,OvsdbBridgeName bridgeName) {
+    public static InstanceIdentifier<Node> createInstanceIdentifier(ConnectionInfo key, OvsdbBridgeName bridgeName) {
         return createInstanceIdentifier(createManagedNodeId(key, bridgeName));
     }
 
@@ -225,7 +219,7 @@ public class SouthboundUtils {
         return createInstanceIdentifier(key, new OvsdbBridgeName(bridgeName));
     }
 
-    public InstanceIdentifier<TerminationPoint> createTerminationPointInstanceIdentifier(Node node, String portName){
+    public InstanceIdentifier<TerminationPoint> createTerminationPointInstanceIdentifier(Node node, String portName) {
 
         InstanceIdentifier<TerminationPoint> terminationPointPath = InstanceIdentifier
                 .create(NetworkTopology.class)
@@ -241,6 +235,11 @@ public class SouthboundUtils {
         return new NodeKey(createNodeId(ip, port));
     }
 
+    public static NodeId createManagedNodeId(NodeId ovsdbNodeId, String bridgeName) {
+        return new NodeId(ovsdbNodeId.getValue()
+                + "/" + BRIDGE_URI_PREFIX + "/" + bridgeName);
+    }
+
     public static NodeId createManagedNodeId(ConnectionInfo key, OvsdbBridgeName bridgeName) {
         return createManagedNodeId(key.getRemoteIp(), key.getRemotePort(), bridgeName);
     }
@@ -255,15 +254,6 @@ public class SouthboundUtils {
         return nodeKey.getNodeId();
     }
 
-    public ConnectionInfo getConnectionInfo(Node ovsdbNode) {
-        ConnectionInfo connectionInfo = null;
-        OvsdbNodeAugmentation ovsdbNodeAugmentation = extractOvsdbNode(ovsdbNode);
-        if (ovsdbNodeAugmentation != null) {
-            connectionInfo = ovsdbNodeAugmentation.getConnectionInfo();
-        }
-        return connectionInfo;
-    }
-
     public OvsdbNodeAugmentation extractOvsdbNode(Node node) {
         return node.getAugmentation(OvsdbNodeAugmentation.class);
     }
@@ -287,6 +277,15 @@ public class SouthboundUtils {
         return new IpAddress(ipv6);
     }
 
+    public ConnectionInfo getConnectionInfo(Node ovsdbNode) {
+        ConnectionInfo connectionInfo = null;
+        OvsdbNodeAugmentation ovsdbNodeAugmentation = extractOvsdbNode(ovsdbNode);
+        if (ovsdbNodeAugmentation != null) {
+            connectionInfo = ovsdbNodeAugmentation.getConnectionInfo();
+        }
+        return connectionInfo;
+    }
+
     public static ConnectionInfo getConnectionInfo(final String addressStr, final String portStr) {
         InetAddress inetAddress = null;
         try {
@@ -404,8 +403,8 @@ public class SouthboundUtils {
     }
 
     /**
-     * extract the <code>LogicalDataStoreType.OPERATIONAL</code> type data store contents for the particular bridge
-     * identified by <code>bridgeName</code>
+     * Extract the <code>LogicalDataStoreType.OPERATIONAL</code> type data store contents for the particular bridge
+     * identified by <code>bridgeName</code>.
      *
      * @param connectionInfo address for the node
      * @param bridgeName name of the bridge
@@ -475,7 +474,7 @@ public class SouthboundUtils {
             InstanceIdentifier<Node> ovsdbNodeIid =
                     (InstanceIdentifier<Node>) bridgeAugmentation.getManagedBy().getValue();
             ovsdbNode = mdsalUtils.read(LogicalDatastoreType.OPERATIONAL, ovsdbNodeIid);
-        }else{
+        } else {
             LOG.debug("readOvsdbNode: Provided node is not a bridge node : {}",bridgeNode);
         }
         return ovsdbNode;
@@ -589,69 +588,6 @@ public class SouthboundUtils {
         return result;
     }
 
-    /**
-     * Set the controllers of an existing bridge node
-     * @param ovsdbNode where the bridge is
-     * @param bridgeName Name of the bridge
-     * @param controllers controller strings
-     * @return success if the write to md-sal was successful
-     */
-    public boolean setBridgeController(Node ovsdbNode, String bridgeName, List<String> controllers) {
-        return setBridgeController(ovsdbNode, bridgeName, controllers, null, null);
-    }
-    /**
-     * Set the controllers of an existing bridge node
-     * @param ovsdbNode where the bridge is
-     * @param bridgeName Name of the bridge
-     * @param controllers controller strings
-     * @param maxBackoff Max backoff in milliseconds
-     * @param inactivityProbe inactivity probe in milliseconds
-     * @return success if the write to md-sal was successful
-     */
-    public boolean setBridgeController(Node ovsdbNode, String bridgeName, List<String> controllers,
-            Long maxBackoff, Long inactivityProbe) {
-        LOG.debug("setBridgeController: ovsdbNode: {}, bridgeNode: {}, controller(s): {}",
-                ovsdbNode, bridgeName, controllers);
-
-        InstanceIdentifier<Node> bridgeNodeIid = createInstanceIdentifier(ovsdbNode.getKey(), bridgeName);
-        Node bridgeNode = mdsalUtils.read(LogicalDatastoreType.CONFIGURATION, bridgeNodeIid);
-        if (bridgeNode == null) {
-            LOG.info("setBridgeController could not find bridge in configuration {}", bridgeNodeIid);
-            return false;
-        }
-
-        OvsdbBridgeAugmentation bridgeAug = extractBridgeAugmentation(bridgeNode);
-
-        //Only add controller entries that do not already exist on this bridge
-        List<ControllerEntry> existingControllerEntries = bridgeAug.getControllerEntry();
-        List<ControllerEntry> newControllerEntries = new ArrayList<>();
-        if(existingControllerEntries != null) {
-            NEW_ENTRY_LOOP:
-            for (ControllerEntry newEntry : createControllerEntries(controllers, maxBackoff, inactivityProbe)) {
-                for (ControllerEntry existingEntry : existingControllerEntries) {
-                    if (newEntry.getTarget().equals(existingEntry.getTarget())) {
-                        continue NEW_ENTRY_LOOP;
-                    }
-                }
-                newControllerEntries.add(newEntry);
-            }
-        } else {
-            newControllerEntries = createControllerEntries(controllers,maxBackoff, inactivityProbe);
-        }
-
-        if(newControllerEntries.isEmpty()) {
-            return true;
-        }
-
-        NodeBuilder nodeBuilder = new NodeBuilder(bridgeNode);
-        OvsdbBridgeAugmentationBuilder augBuilder = new OvsdbBridgeAugmentationBuilder(bridgeAug);
-
-        augBuilder.setControllerEntry(newControllerEntries);
-        nodeBuilder.addAugmentation(OvsdbBridgeAugmentation.class, augBuilder.build());
-        InstanceIdentifier<Node> bridgeIid = createInstanceIdentifier(ovsdbNode.getKey(), bridgeName);
-        return mdsalUtils.merge(LogicalDatastoreType.CONFIGURATION, bridgeIid, nodeBuilder.build());
-    }
-
     public boolean addBridge(Node ovsdbNode, String bridgeName, List<String> controllersStr,
             final Class<? extends DatapathTypeBase> dpType, String mac) {
         return addBridge(ovsdbNode, bridgeName, controllersStr, dpType, mac, null, null);
@@ -672,9 +608,9 @@ public class SouthboundUtils {
     }
 
     public boolean addBridge(Node ovsdbNode, String bridgeName, List<String> controllersStr,
-                             final Class<? extends DatapathTypeBase> dpType,
-                             List<BridgeOtherConfigs> otherConfigs,
-                             Long maxBackoff, Long inactivityProbe) {
+            final Class<? extends DatapathTypeBase> dpType,
+            List<BridgeOtherConfigs> otherConfigs,
+            Long maxBackoff, Long inactivityProbe) {
         boolean result;
 
         LOG.info("addBridge: node: {}, bridgeName: {}, controller(s): {}", ovsdbNode, bridgeName, controllersStr);
@@ -689,7 +625,7 @@ public class SouthboundUtils {
                     controllersStr, maxBackoff, inactivityProbe));
             ovsdbBridgeAugmentationBuilder.setBridgeName(new OvsdbBridgeName(bridgeName));
             ovsdbBridgeAugmentationBuilder.setProtocolEntry(createMdsalProtocols());
-            ovsdbBridgeAugmentationBuilder.setFailMode( OVSDB_FAIL_MODE_MAP.inverse().get("secure"));
+            ovsdbBridgeAugmentationBuilder.setFailMode(OVSDB_FAIL_MODE_MAP.inverse().get("secure"));
             // TODO: Currently netvirt relies on this function to set disabled-in-band=true. However,
             // TODO (cont): a better design would be to have netvirt pass that in. That way this function
             // TODO (cont): can take a null otherConfigs to erase other_configs.
@@ -719,6 +655,71 @@ public class SouthboundUtils {
         return result;
     }
 
+    /**
+     * Set the controllers of an existing bridge node.
+     *
+     * @param ovsdbNode where the bridge is
+     * @param bridgeName Name of the bridge
+     * @param controllers controller strings
+     * @return success if the write to md-sal was successful
+     */
+    public boolean setBridgeController(Node ovsdbNode, String bridgeName, List<String> controllers) {
+        return setBridgeController(ovsdbNode, bridgeName, controllers, null, null);
+    }
+
+    /**
+     * Set the controllers of an existing bridge node.
+     *
+     * @param ovsdbNode where the bridge is
+     * @param bridgeName Name of the bridge
+     * @param controllers controller strings
+     * @param maxBackoff Max backoff in milliseconds
+     * @param inactivityProbe inactivity probe in milliseconds
+     * @return success if the write to md-sal was successful
+     */
+    public boolean setBridgeController(Node ovsdbNode, String bridgeName, List<String> controllers,
+            Long maxBackoff, Long inactivityProbe) {
+        LOG.debug("setBridgeController: ovsdbNode: {}, bridgeNode: {}, controller(s): {}",
+                ovsdbNode, bridgeName, controllers);
+
+        InstanceIdentifier<Node> bridgeNodeIid = createInstanceIdentifier(ovsdbNode.getKey(), bridgeName);
+        Node bridgeNode = mdsalUtils.read(LogicalDatastoreType.CONFIGURATION, bridgeNodeIid);
+        if (bridgeNode == null) {
+            LOG.info("setBridgeController could not find bridge in configuration {}", bridgeNodeIid);
+            return false;
+        }
+
+        OvsdbBridgeAugmentation bridgeAug = extractBridgeAugmentation(bridgeNode);
+
+        //Only add controller entries that do not already exist on this bridge
+        List<ControllerEntry> existingControllerEntries = bridgeAug.getControllerEntry();
+        List<ControllerEntry> newControllerEntries = new ArrayList<>();
+        if (existingControllerEntries != null) {
+            NEW_ENTRY_LOOP:
+            for (ControllerEntry newEntry : createControllerEntries(controllers, maxBackoff, inactivityProbe)) {
+                for (ControllerEntry existingEntry : existingControllerEntries) {
+                    if (newEntry.getTarget().equals(existingEntry.getTarget())) {
+                        continue NEW_ENTRY_LOOP;
+                    }
+                }
+                newControllerEntries.add(newEntry);
+            }
+        } else {
+            newControllerEntries = createControllerEntries(controllers,maxBackoff, inactivityProbe);
+        }
+
+        if (newControllerEntries.isEmpty()) {
+            return true;
+        }
+
+        NodeBuilder nodeBuilder = new NodeBuilder(bridgeNode);
+        OvsdbBridgeAugmentationBuilder augBuilder = new OvsdbBridgeAugmentationBuilder(bridgeAug);
+
+        augBuilder.setControllerEntry(newControllerEntries);
+        nodeBuilder.addAugmentation(OvsdbBridgeAugmentation.class, augBuilder.build());
+        InstanceIdentifier<Node> bridgeIid = createInstanceIdentifier(ovsdbNode.getKey(), bridgeName);
+        return mdsalUtils.merge(LogicalDatastoreType.CONFIGURATION, bridgeIid, nodeBuilder.build());
+    }
 
     private void setManagedBy(final OvsdbBridgeAugmentationBuilder ovsdbBridgeAugmentationBuilder,
                               final ConnectionInfo connectionInfo) {
@@ -735,7 +736,6 @@ public class SouthboundUtils {
     public boolean addTerminationPoint(
             Node bridgeNode, String portName, String type, Map<String, String> options, Map<String, String> externalIds,
             Long ofPort) {
-        InstanceIdentifier<TerminationPoint> tpIid = createTerminationPointInstanceIdentifier(bridgeNode, portName);
         OvsdbTerminationPointAugmentationBuilder tpAugmentationBuilder = new OvsdbTerminationPointAugmentationBuilder();
 
         tpAugmentationBuilder.setName(portName);
@@ -769,6 +769,7 @@ public class SouthboundUtils {
         }
 
         TerminationPointBuilder tpBuilder = new TerminationPointBuilder();
+        InstanceIdentifier<TerminationPoint> tpIid = createTerminationPointInstanceIdentifier(bridgeNode, portName);
         tpBuilder.setKey(InstanceIdentifier.keyOf(tpIid));
         tpBuilder.addAugmentation(OvsdbTerminationPointAugmentation.class, tpAugmentationBuilder.build());
         /* TODO SB_MIGRATION should this be merge or mdsalUtils.put */
@@ -781,8 +782,6 @@ public class SouthboundUtils {
 
     public Boolean addTerminationPoint(Node bridgeNode, String bridgeName, String portName,
                                        String type, Map<String, String> options) {
-        InstanceIdentifier<TerminationPoint> tpIid = createTerminationPointInstanceIdentifier(
-                bridgeNode, portName);
         OvsdbTerminationPointAugmentationBuilder tpAugmentationBuilder = new OvsdbTerminationPointAugmentationBuilder();
 
         tpAugmentationBuilder.setName(portName);
@@ -801,6 +800,7 @@ public class SouthboundUtils {
         tpAugmentationBuilder.setOptions(optionsList);
 
         TerminationPointBuilder tpBuilder = new TerminationPointBuilder();
+        InstanceIdentifier<TerminationPoint> tpIid = createTerminationPointInstanceIdentifier(bridgeNode, portName);
         tpBuilder.setKey(InstanceIdentifier.keyOf(tpIid));
         tpBuilder.addAugmentation(OvsdbTerminationPointAugmentation.class, tpAugmentationBuilder.build());
         /* TODO SB_MIGRATION should this be merge or mdsalUtils.put */
@@ -948,8 +948,9 @@ public class SouthboundUtils {
 
     private String getLocalControllerHostIpAddress() {
         String ipaddress = null;
-        try{
-            for (Enumeration<NetworkInterface> ifaces = NetworkInterface.getNetworkInterfaces(); ifaces.hasMoreElements();){
+        try {
+            for (Enumeration<NetworkInterface> ifaces = NetworkInterface.getNetworkInterfaces();
+                    ifaces.hasMoreElements();) {
                 NetworkInterface iface = ifaces.nextElement();
 
                 for (Enumeration<InetAddress> inetAddrs = iface.getInetAddresses(); inetAddrs.hasMoreElements();) {
@@ -960,7 +961,7 @@ public class SouthboundUtils {
                     }
                 }
             }
-        }catch (Exception e){
+        } catch (SocketException e) {
             LOG.warn("Exception while fetching local host ip address ", e);
         }
         return ipaddress;
@@ -1086,15 +1087,15 @@ public class SouthboundUtils {
         return null;
     }
 
-    public List<OvsdbTerminationPointAugmentation> extractTerminationPointAugmentations( Node node ) {
+    public List<OvsdbTerminationPointAugmentation> extractTerminationPointAugmentations(Node node) {
         List<OvsdbTerminationPointAugmentation> tpAugmentations = new ArrayList<>();
         if (node == null) {
             LOG.error("extractTerminationPointAugmentations: Node value is null");
             return Collections.emptyList();
         }
         List<TerminationPoint> terminationPoints = node.getTerminationPoint();
-        if(terminationPoints != null && !terminationPoints.isEmpty()){
-            for(TerminationPoint tp : terminationPoints){
+        if (terminationPoints != null && !terminationPoints.isEmpty()) {
+            for (TerminationPoint tp : terminationPoints) {
                 OvsdbTerminationPointAugmentation ovsdbTerminationPointAugmentation =
                         tp.getAugmentation(OvsdbTerminationPointAugmentation.class);
                 if (ovsdbTerminationPointAugmentation != null) {
@@ -1108,18 +1109,14 @@ public class SouthboundUtils {
     /**
      * Extract the <code>OvsdbTerminationPointAugmentation</code> for the particular <code>node</code> identified by
      * <code>portName</code>.
-     *
-     * @param node
-     * @param portName
-     * @return
      */
     public OvsdbTerminationPointAugmentation getTerminationPointOfBridge(Node node, String portName) {
         OvsdbTerminationPointAugmentation tpAugmentation = extractTerminationPointAugmentation(node,portName);
-        if(tpAugmentation == null){
+        if (tpAugmentation == null) {
             List<OvsdbTerminationPointAugmentation> tpAugmentations = readTerminationPointAugmentations(node);
-            if(tpAugmentations != null){
-                for(OvsdbTerminationPointAugmentation ovsdbTpAugmentation : tpAugmentations){
-                    if(ovsdbTpAugmentation.getName().equals(portName)){
+            if (tpAugmentations != null) {
+                for (OvsdbTerminationPointAugmentation ovsdbTpAugmentation : tpAugmentations) {
+                    if (ovsdbTpAugmentation.getName().equals(portName)) {
                         return ovsdbTpAugmentation;
                     }
                 }
@@ -1129,10 +1126,7 @@ public class SouthboundUtils {
     }
 
     /**
-     * read the list of <code>OvsdbTerminationPointAugmentation</code> for the particular <code>node</code>.
-     *
-     * @param node
-     * @return
+     * Read the list of <code>OvsdbTerminationPointAugmentation</code> for the particular <code>node</code>.
      */
     public List<OvsdbTerminationPointAugmentation> readTerminationPointAugmentations(Node node) {
         if (node == null) {
@@ -1242,40 +1236,46 @@ public class SouthboundUtils {
         final Matcher dbVersionMatcher = PATTERN.matcher(dbVersion);
         final Matcher minVersionMatcher = PATTERN.matcher(minVersion);
         LOG.debug("dbVersion {}, minVersion {}", dbVersion, minVersion);
-        if (!dbVersionMatcher.find()){
+        if (!dbVersionMatcher.find()) {
             LOG.error("Invalid DB version format {}", dbVersion);
             return false;
         }
-        if (!minVersionMatcher.find()){
+        if (!minVersionMatcher.find()) {
             LOG.error("Invalid Min DB version format {}", minVersion);
             return false;
         }
 
         if (dbVersion != null && !dbVersion.isEmpty() && minVersion != null
                 && !minVersion.isEmpty()) {
-            if (Integer.valueOf(dbVersionMatcher.group(1)).equals(Integer.valueOf(minVersionMatcher.group(1))) &&
-                   Integer.valueOf(dbVersionMatcher.group(2)).equals(Integer.valueOf(minVersionMatcher.group(2))) &&
-                   Integer.valueOf(dbVersionMatcher.group(3)).equals(Integer.valueOf(minVersionMatcher.group(3)))) {
+            if (Integer.valueOf(dbVersionMatcher.group(1)).equals(Integer.valueOf(minVersionMatcher.group(1)))
+                   && Integer.valueOf(dbVersionMatcher.group(2)).equals(Integer.valueOf(minVersionMatcher.group(2)))
+                   && Integer.valueOf(dbVersionMatcher.group(3)).equals(Integer.valueOf(minVersionMatcher.group(3)))) {
                 return true;
             }
 
-            if (Integer.valueOf(dbVersionMatcher.group(1)).intValue() > Integer.valueOf(minVersionMatcher.group(1)).intValue()) {
+            if (Integer.valueOf(dbVersionMatcher.group(1)).intValue()
+                    > Integer.valueOf(minVersionMatcher.group(1)).intValue()) {
                 return true;
             }
 
-            if (Integer.valueOf(dbVersionMatcher.group(1)).intValue() < Integer.valueOf(minVersionMatcher.group(1)).intValue()) {
+            if (Integer.valueOf(dbVersionMatcher.group(1)).intValue()
+                    < Integer.valueOf(minVersionMatcher.group(1)).intValue()) {
                 return false;
             }
 
             // major version is equal
-            if (Integer.valueOf(dbVersionMatcher.group(2)).intValue() > Integer.valueOf(minVersionMatcher.group(2)).intValue()) {
+            if (Integer.valueOf(dbVersionMatcher.group(2)).intValue()
+                    > Integer.valueOf(minVersionMatcher.group(2)).intValue()) {
                 return true;
             }
-            if (Integer.valueOf(dbVersionMatcher.group(2)).intValue() < Integer.valueOf(minVersionMatcher.group(2)).intValue()) {
+
+            if (Integer.valueOf(dbVersionMatcher.group(2)).intValue()
+                    < Integer.valueOf(minVersionMatcher.group(2)).intValue()) {
                 return false;
             }
 
-           if (Integer.valueOf(dbVersionMatcher.group(3)).intValue() > Integer.valueOf(minVersionMatcher.group(3)).intValue()) {
+            if (Integer.valueOf(dbVersionMatcher.group(3)).intValue()
+                   > Integer.valueOf(minVersionMatcher.group(3)).intValue()) {
                 return true;
             }
         }
index d48a92a740ebd8a7d62df90b9ce17b31d6b210f9..1e72e0bb0d1881027374db6ea81e5832ff4cb6f6 100644 (file)
@@ -9,6 +9,7 @@
 package org.opendaylight.ovsdb.utils.southbound.utils;
 
 import static org.junit.Assert.assertTrue;
+
 import org.junit.Test;
 
 public class SouthboundUtilsTest {