Fixes for LibraryIT timing out 34/37034/1
authorSam Hague <shague@redhat.com>
Sat, 2 Apr 2016 21:46:59 +0000 (17:46 -0400)
committerSam Hague <shague@redhat.com>
Sat, 2 Apr 2016 21:46:59 +0000 (17:46 -0400)
Something recently changed in the karaf builds such that
it is causing the five core karaf bundles to only go to
an installed state. The LibraryIT tests will not run unless
they see all bundles active, so the installed state bundles
cause the test to timeout.

Reworked the tests to not use the bundle states and to use what all
the other tests in OBSDB use which is to wait until the config is up.
Added these methods to the abstract test class so that it could be
shared across the five differetn library IT sets.

Also cleaned up a bunchof System.Out.println's and Assert's.

Change-Id: Iddd31eede1de1c5f3cde88bb1c3f7c96a5489051
Signed-off-by: Sam Hague <shague@redhat.com>
library/it/src/test/java/org/opendaylight/ovsdb/integrationtest/ovsdbclient/OvsdbClientTestIT.java
library/it/src/test/java/org/opendaylight/ovsdb/integrationtest/ovsdbclient/OvsdbClientTestTypedIT.java
library/it/src/test/java/org/opendaylight/ovsdb/integrationtest/schema/hardwarevtep/HardwareVTEPIT.java
library/it/src/test/java/org/opendaylight/ovsdb/integrationtest/schema/openvswitch/OpenVSwitchIT.java
library/it/src/test/java/org/opendaylight/ovsdb/lib/it/LibraryIT.java
library/it/src/test/java/org/opendaylight/ovsdb/lib/it/LibraryIntegrationTestBase.java
library/it/src/test/java/org/opendaylight/ovsdb/lib/it/LibraryIntegrationTestUtils.java

index f0cbe5a84f27fcc63e04bd7c39fac4c94e07a62a..13cd93eab4ab0477c64f6ba49704b2eb5dd145db 100644 (file)
@@ -9,6 +9,12 @@
  */
 package org.opendaylight.ovsdb.integrationtest.ovsdbclient;
 
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
 import static org.opendaylight.ovsdb.lib.operations.Operations.op;
 
 import com.google.common.collect.ImmutableMap;
@@ -20,9 +26,7 @@ import java.util.List;
 import java.util.Map;
 import java.util.Set;
 import java.util.concurrent.ExecutionException;
-import java.util.concurrent.TimeoutException;
 import org.junit.After;
-import org.junit.Assert;
 import org.junit.Before;
 import org.junit.Test;
 import org.junit.runner.RunWith;
@@ -48,15 +52,17 @@ import org.opendaylight.ovsdb.lib.schema.TableSchema;
 import org.ops4j.pax.exam.junit.PaxExam;
 import org.ops4j.pax.exam.spi.reactors.ExamReactorStrategy;
 import org.ops4j.pax.exam.spi.reactors.PerSuite;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 
 @RunWith(PaxExam.class)
 @ExamReactorStrategy(PerSuite.class)
 public class OvsdbClientTestIT extends LibraryIntegrationTestBase {
-
+    private static final Logger LOG = LoggerFactory.getLogger(OvsdbClientTestIT.class);
     OvsdbClient ovs;
     DatabaseSchema dbSchema = null;
-    static String testBridgeName = "br-test";
-    static UUID testBridgeUuid = null;
+    private static final String TEST_BRIDGE_NAME = "br-test";
+    private static UUID testBridgeUuid = null;
 
     /**
      * Test general OVSDB transactions (viz., insert, select, update,
@@ -65,7 +71,7 @@ public class OvsdbClientTestIT extends LibraryIntegrationTestBase {
      */
     @Test
     public void testTransact() throws IOException, InterruptedException, ExecutionException {
-        Assert.assertNotNull(dbSchema);
+        assertNotNull(dbSchema);
         TableSchema<GenericTableSchema> bridge = dbSchema.table("Bridge", GenericTableSchema.class);
         ColumnSchema<GenericTableSchema, String> name = bridge.column("name", String.class);
 
@@ -81,7 +87,7 @@ public class OvsdbClientTestIT extends LibraryIntegrationTestBase {
      */
     @Test
     public void testMonitorRequest() throws ExecutionException, InterruptedException, IOException {
-        Assert.assertNotNull(dbSchema);
+        assertNotNull(dbSchema);
         // Create Test Bridge before testing the Monitor operation
         createBridgeTransaction();
         sendBridgeMonitorRequest(true); // Test monitor request with Column filters
@@ -89,7 +95,7 @@ public class OvsdbClientTestIT extends LibraryIntegrationTestBase {
     }
 
     public void sendBridgeMonitorRequest(boolean filter) throws ExecutionException, InterruptedException, IOException {
-        Assert.assertNotNull(dbSchema);
+        assertNotNull(dbSchema);
         GenericTableSchema bridge = dbSchema.table("Bridge", GenericTableSchema.class);
 
         List<MonitorRequest> monitorRequests = Lists.newArrayList();
@@ -112,64 +118,64 @@ public class OvsdbClientTestIT extends LibraryIntegrationTestBase {
             @Override
             public void update(TableUpdates result, DatabaseSchema dbSchema) {
                 results.add(result);
-                System.out.println("result = " + result);
+                LOG.info("result = {}", result);
             }
 
             @Override
             public void exception(Throwable t) {
                 results.add(t);
-                System.out.println("t = " + t);
+                LOG.warn("t = ", t);
             }
         });
         if (updates != null) {
             results.add(updates);
         }
         for (int i = 0; i < 3 ; i++) { //wait 3 seconds to get a result
-            System.out.println("waiting on monitor response for Bridge Table...");
+            LOG.info("waiting on monitor response for Bridge Table...");
             if (!results.isEmpty()) {
                 break;
             }
             Thread.sleep(1000);
         }
 
-        Assert.assertTrue(!results.isEmpty());
+        assertTrue(!results.isEmpty());
         Object result = results.get(0);
-        Assert.assertTrue(result instanceof TableUpdates);
+        assertTrue(result instanceof TableUpdates);
         updates = (TableUpdates) result;
         TableUpdate<GenericTableSchema> update = updates.getUpdate(bridge);
-        Assert.assertTrue(update.getRows().size() > 0);
+        assertTrue(update.getRows().size() > 0);
         for (UUID uuid : update.getRows().keySet()) {
             Row<GenericTableSchema> aNew = update.getNew(uuid);
-            if (!aNew.getColumn(name).getData().equals(testBridgeName)) {
+            if (!aNew.getColumn(name).getData().equals(TEST_BRIDGE_NAME)) {
                 continue;
             }
             if (filter) {
-                Assert.assertEquals(builder.getColumns().size(), aNew.getColumns().size());
+                assertEquals(builder.getColumns().size(), aNew.getColumns().size());
             } else {
                 // As per RFC7047, Section 4.1.5 : If "columns" is omitted, all columns in the table, except for "_uuid", are monitored.
-                Assert.assertEquals(bridge.getColumns().size() - 1, aNew.getColumns().size());
+                assertEquals(bridge.getColumns().size() - 1, aNew.getColumns().size());
             }
             for (Column<GenericTableSchema, ?> column: aNew.getColumns()) {
                 if (column.getSchema().equals(flood_vlans)) {
                     // Test for the 5 flood_vlans inserted in Bridge br-test in createBridgeTransaction
                     Set<Integer> data = column.getData(flood_vlans);
-                    Assert.assertNotNull(data);
-                    Assert.assertTrue(!data.isEmpty());
-                    Assert.assertEquals(5, data.size());
+                    assertNotNull(data);
+                    assertTrue(!data.isEmpty());
+                    assertEquals(5, data.size());
                 } else if (column.getSchema().equals(externalIds)) {
                     // Test for the {"key", "value"} external_ids inserted in Bridge br-test in createBridgeTransaction
                     Map<String, String> data = column.getData(externalIds);
-                    Assert.assertNotNull(data);
-                    Assert.assertNotNull(data.get("key"));
-                    Assert.assertEquals("value", data.get("key"));
+                    assertNotNull(data);
+                    assertNotNull(data.get("key"));
+                    assertEquals("value", data.get("key"));
                     // Test for {"key2", "value2"} external_ids mutation-inserted in Bridge br-test in createBridgeTransaction
-                    Assert.assertNotNull(data.get("key2"));
-                    Assert.assertEquals("value2", data.get("key2"));
+                    assertNotNull(data.get("key2"));
+                    assertEquals("value2", data.get("key2"));
                 }
             }
             return;
         }
-        Assert.fail("Bridge being monitored :"+testBridgeName+" Not found");
+        fail("Bridge being monitored :"+ TEST_BRIDGE_NAME +" Not found");
     }
 
     /*
@@ -177,7 +183,7 @@ public class OvsdbClientTestIT extends LibraryIntegrationTestBase {
      * parsing challenges on the Row object returned by the Select operation.
      */
     private UUID selectOpenVSwitchTableUuid() throws ExecutionException, InterruptedException {
-        Assert.assertNotNull(dbSchema);
+        assertNotNull(dbSchema);
         GenericTableSchema ovsTable = dbSchema.table("Open_vSwitch", GenericTableSchema.class);
 
         List<MonitorRequest> monitorRequests = Lists.newArrayList();
@@ -189,7 +195,7 @@ public class OvsdbClientTestIT extends LibraryIntegrationTestBase {
                       .execute()
                       .get();
 
-        Assert.assertTrue(!results.isEmpty());
+        assertTrue(!results.isEmpty());
         OperationResult result = results.get(0);
         List<Row<GenericTableSchema>> rows = result.getRows();
         Row<GenericTableSchema> ovsTableRow = rows.get(0);
@@ -197,7 +203,7 @@ public class OvsdbClientTestIT extends LibraryIntegrationTestBase {
     }
 
     private void createBridgeTransaction() throws IOException, InterruptedException, ExecutionException {
-        Assert.assertNotNull(dbSchema);
+        assertNotNull(dbSchema);
         TableSchema<GenericTableSchema> bridge = dbSchema.table("Bridge", GenericTableSchema.class);
         GenericTableSchema ovsTable = dbSchema.table("Open_vSwitch", GenericTableSchema.class);
 
@@ -218,26 +224,26 @@ public class OvsdbClientTestIT extends LibraryIntegrationTestBase {
                   */
                 .add(op.insert(bridge)
                         .withId(namedUuid)
-                        .value(name, testBridgeName)
+                        .value(name, TEST_BRIDGE_NAME)
                         .value(flood_vlans, Sets.newHashSet(100, 101, 4001))
                         .value(externalIds, ImmutableMap.of("key","value")))
                 .add(op.comment("Inserting Bridge br-int"))
                 .add(op.update(bridge)
                         .set(fail_mode, "secure")
-                        .where(name.opEqual(testBridgeName))
+                        .where(name.opEqual(TEST_BRIDGE_NAME))
                         .build())
                 .add(op.select(bridge)
                         .column(name)
                         .column(_uuid)
-                        .where(name.opEqual(testBridgeName))
+                        .where(name.opEqual(TEST_BRIDGE_NAME))
                         .build())
                 .add(op.mutate(bridge)
                         .addMutation(flood_vlans, Mutator.INSERT, Sets.newHashSet(200,400))
-                        .where(name.opEqual(testBridgeName))
+                        .where(name.opEqual(TEST_BRIDGE_NAME))
                         .build())
                 .add(op.mutate(bridge)
                         .addMutation(externalIds, Mutator.INSERT, ImmutableMap.of("key2","value2"))
-                        .where(name.opEqual(testBridgeName))
+                        .where(name.opEqual(TEST_BRIDGE_NAME))
                         .build())
                 .add(op.mutate(ovsTable)
                         .addMutation(bridges, Mutator.INSERT, Sets.newHashSet(new UUID(namedUuid)))
@@ -247,18 +253,18 @@ public class OvsdbClientTestIT extends LibraryIntegrationTestBase {
 
         ListenableFuture<List<OperationResult>> results = transactionBuilder.execute();
         List<OperationResult> operationResults = results.get();
-        Assert.assertFalse(operationResults.isEmpty());
+        assertFalse(operationResults.isEmpty());
         // Check if Results matches the number of operations in transaction
-        Assert.assertEquals(transactionBuilder.getOperations().size(), operationResults.size());
-        System.out.println("Insert & Update operation results = " + operationResults);
+        assertEquals(transactionBuilder.getOperations().size(), operationResults.size());
+        LOG.info("Insert & Update operation results = {}", operationResults);
         for (OperationResult result : operationResults) {
-            Assert.assertNull(result.getError());
+            assertNull(result.getError());
         }
         testBridgeUuid = operationResults.get(insertOperationIndex).getUuid();
     }
 
     private void assertTransaction() throws InterruptedException, ExecutionException {
-        Assert.assertNotNull(dbSchema);
+        assertNotNull(dbSchema);
         TableSchema<GenericTableSchema> bridge = dbSchema.table("Bridge", GenericTableSchema.class);
         ColumnSchema<GenericTableSchema, String> name = bridge.column("name", String.class);
 
@@ -268,20 +274,20 @@ public class OvsdbClientTestIT extends LibraryIntegrationTestBase {
          */
         ListenableFuture<List<OperationResult>> results = ovs.transactBuilder(dbSchema)
                 .add(op.delete(bridge)
-                        .where(name.opEqual(testBridgeName))
+                        .where(name.opEqual(TEST_BRIDGE_NAME))
                         .build())
                 .add(op.assertion("Assert12345")) // Failing intentionally
                 .execute();
 
         List<OperationResult> operationResults = results.get();
-        Assert.assertFalse(operationResults.isEmpty());
+        assertFalse(operationResults.isEmpty());
         /* Testing for an Assertion Error */
-        Assert.assertFalse(operationResults.get(1).getError() == null);
-        System.out.println("Assert operation results = " + operationResults);
+        assertFalse(operationResults.get(1).getError() == null);
+        LOG.info("Assert operation results = {}", operationResults);
     }
 
     private void abortTransaction() throws InterruptedException, ExecutionException {
-        Assert.assertNotNull(dbSchema);
+        assertNotNull(dbSchema);
         TableSchema<GenericTableSchema> bridge = dbSchema.table("Bridge", GenericTableSchema.class);
         ColumnSchema<GenericTableSchema, String> name = bridge.column("name", String.class);
 
@@ -291,43 +297,47 @@ public class OvsdbClientTestIT extends LibraryIntegrationTestBase {
          */
         ListenableFuture<List<OperationResult>> results = ovs.transactBuilder(dbSchema)
                 .add(op.delete(bridge)
-                        .where(name.opEqual(testBridgeName))
+                        .where(name.opEqual(TEST_BRIDGE_NAME))
                         .build())
                 .add(op.abort())
                 .execute();
 
         List<OperationResult> operationResults = results.get();
-        Assert.assertFalse(operationResults.isEmpty());
+        assertFalse(operationResults.isEmpty());
         /* Testing for Abort Error */
-        Assert.assertFalse(operationResults.get(1).getError() == null);
-        System.out.println("Abort operation results = " + operationResults);
+        assertFalse(operationResults.get(1).getError() == null);
+        LOG.info("Abort operation results = {}", operationResults);
     }
 
     public void testGetDBs() throws ExecutionException, InterruptedException {
         ListenableFuture<List<String>> databases = ovs.getDatabases();
         List<String> dbNames = databases.get();
-        Assert.assertNotNull(dbNames);
+        assertNotNull(dbNames);
         boolean hasOpenVswitchSchema = false;
         for(String dbName : dbNames) {
-           if (dbName.equals(LibraryIntegrationTestUtils.OPEN_VSWITCH_SCHEMA)) {
+           if (dbName.equals(LibraryIntegrationTestUtils.OPEN_VSWITCH)) {
                 hasOpenVswitchSchema = true;
                 break;
            }
         }
-        Assert.assertTrue(LibraryIntegrationTestUtils.OPEN_VSWITCH_SCHEMA
+        assertTrue(LibraryIntegrationTestUtils.OPEN_VSWITCH
                 + " schema is not supported by the switch", hasOpenVswitchSchema);
     }
 
     @Before
-    public  void setUp() throws IOException, ExecutionException, InterruptedException, TimeoutException {
+    public void setup() throws Exception {
+        schema = LibraryIntegrationTestUtils.OPEN_VSWITCH;
+        super.setup2();
+
         if (ovs != null) {
             return;
         }
 
         ovs = LibraryIntegrationTestUtils.getTestConnection(this);
-        System.out.println("Connection Info :" + ovs.getConnectionInfo().toString());
+        assertNotNull("Failed to get connection to ovsdb node", ovs);
+        LOG.info("Connection Info: {}", ovs.getConnectionInfo().toString());
         testGetDBs();
-        dbSchema = ovs.getSchema(LibraryIntegrationTestUtils.OPEN_VSWITCH_SCHEMA).get();
+        dbSchema = ovs.getSchema(LibraryIntegrationTestUtils.OPEN_VSWITCH).get();
     }
 
     @After
@@ -344,7 +354,7 @@ public class OvsdbClientTestIT extends LibraryIntegrationTestBase {
 
         ListenableFuture<List<OperationResult>> results = ovs.transactBuilder(dbSchema)
                 .add(op.delete(bridge)
-                        .where(name.opEqual(testBridgeName))
+                        .where(name.opEqual(TEST_BRIDGE_NAME))
                         .build())
                 .add(op.mutate(ovsTable)
                         .addMutation(bridges, Mutator.DELETE, Sets.newHashSet(testBridgeUuid))
@@ -354,7 +364,7 @@ public class OvsdbClientTestIT extends LibraryIntegrationTestBase {
                 .execute();
 
         List<OperationResult> operationResults = results.get();
-        System.out.println("Delete operation results = " + operationResults);
+        LOG.info("Delete operation results = {}", operationResults);
         ovs.disconnect();
     }
 }
index 15f64fbbdf620f31ee0be0554172845ea53774de..6db208c9be8ae9dc3f74e129bc589495bbbb2b55 100644 (file)
 
 package org.opendaylight.ovsdb.integrationtest.ovsdbclient;
 
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
 import static org.opendaylight.ovsdb.lib.operations.Operations.op;
 
 import com.google.common.collect.ImmutableMap;
@@ -20,9 +24,7 @@ import java.lang.reflect.InvocationTargetException;
 import java.util.List;
 import java.util.Set;
 import java.util.concurrent.ExecutionException;
-import java.util.concurrent.TimeoutException;
 import org.junit.After;
-import org.junit.Assert;
 import org.junit.Before;
 import org.junit.Test;
 import org.junit.runner.RunWith;
@@ -40,15 +42,17 @@ import org.opendaylight.ovsdb.lib.schema.TableSchema;
 import org.ops4j.pax.exam.junit.PaxExam;
 import org.ops4j.pax.exam.spi.reactors.ExamReactorStrategy;
 import org.ops4j.pax.exam.spi.reactors.PerSuite;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 
 @RunWith(PaxExam.class)
 @ExamReactorStrategy(PerSuite.class)
 public class OvsdbClientTestTypedIT extends LibraryIntegrationTestBase {
-
+    private static final Logger LOG = LoggerFactory.getLogger(OvsdbClientTestTypedIT.class);
     OvsdbClient ovs;
     DatabaseSchema dbSchema = null;
-    static String testBridgeName = "br_test";
-    static UUID testBridgeUuid = null;
+    private static final String TEST_BRIDGE_NAME = "br_test";
+    private static UUID testBridgeUuid = null;
 
     /**
      * Test creation of statically typed bridge table as defined in
@@ -59,7 +63,7 @@ public class OvsdbClientTestTypedIT extends LibraryIntegrationTestBase {
     @Test
     public void testTypedBridgeCreate() throws IOException, InterruptedException, ExecutionException, NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
         TestBridge rBridge = ovs.createTypedRowWrapper(TestBridge.class);
-        rBridge.setName(testBridgeName);
+        rBridge.setName(TEST_BRIDGE_NAME);
         rBridge.setStatus(ImmutableMap.of("key","value"));
         rBridge.setFloodVlans(Sets.newHashSet(34));
 
@@ -77,36 +81,41 @@ public class OvsdbClientTestTypedIT extends LibraryIntegrationTestBase {
 
         ListenableFuture<List<OperationResult>> results = transactionBuilder.execute();
         List<OperationResult> operationResults = results.get();
-        Assert.assertFalse(operationResults.isEmpty());
+        assertFalse(operationResults.isEmpty());
         // Check if Results matches the number of operations in transaction
-        Assert.assertEquals(transactionBuilder.getOperations().size(), operationResults.size());
-        System.out.println("Insert & Update operation results = " + operationResults);
+        assertEquals(transactionBuilder.getOperations().size(), operationResults.size());
+        LOG.info("Insert & Update operation results = {}", operationResults);
         testBridgeUuid = operationResults.get(insertOperationIndex).getUuid();
     }
 
     public void testGetDBs() throws ExecutionException, InterruptedException {
         ListenableFuture<List<String>> databases = ovs.getDatabases();
         List<String> dbNames = databases.get();
-        Assert.assertNotNull(dbNames);
+        assertNotNull(dbNames);
         boolean hasOpenVswitchSchema = false;
         for(String dbName : dbNames) {
-           if (dbName.equals(LibraryIntegrationTestUtils.OPEN_VSWITCH_SCHEMA)) {
+           if (dbName.equals(LibraryIntegrationTestUtils.OPEN_VSWITCH)) {
                 hasOpenVswitchSchema = true;
                 break;
            }
         }
-        Assert.assertTrue(LibraryIntegrationTestUtils.OPEN_VSWITCH_SCHEMA
+        assertTrue(LibraryIntegrationTestUtils.OPEN_VSWITCH
                 + " schema is not supported by the switch", hasOpenVswitchSchema);
     }
 
     @Before
-    public  void setUp() throws IOException, ExecutionException, InterruptedException, TimeoutException {
+    public void setup() throws Exception {
+        schema = LibraryIntegrationTestUtils.OPEN_VSWITCH;
+        super.setup2();
+
         if (ovs != null) {
             return;
         }
         ovs = LibraryIntegrationTestUtils.getTestConnection(this);
+        assertNotNull("Failed to get connection to ovsdb node", ovs);
+        LOG.info("Connection Info: {}", ovs.getConnectionInfo().toString());
         testGetDBs();
-        dbSchema = ovs.getSchema(LibraryIntegrationTestUtils.OPEN_VSWITCH_SCHEMA).get();
+        dbSchema = ovs.getSchema(LibraryIntegrationTestUtils.OPEN_VSWITCH).get();
     }
 
     @After
@@ -118,7 +127,7 @@ public class OvsdbClientTestTypedIT extends LibraryIntegrationTestBase {
 
         ListenableFuture<List<OperationResult>> results = ovs.transactBuilder(dbSchema)
                 .add(op.delete(bridge)
-                        .where(name.opEqual(testBridgeName))
+                        .where(name.opEqual(TEST_BRIDGE_NAME))
                         .build())
                 .add(op.mutate(ovsTable)
                         .addMutation(bridges, Mutator.DELETE, Sets.newHashSet(testBridgeUuid)))
@@ -126,7 +135,7 @@ public class OvsdbClientTestTypedIT extends LibraryIntegrationTestBase {
                 .execute();
 
         List<OperationResult> operationResults = results.get();
-        System.out.println("Delete operation results = " + operationResults);
+        LOG.info("Delete operation results = {}", operationResults);
         ovs.disconnect();
     }
 }
index 067fcdb4bdabda78dd9d30dd34b129a9bd772f92..910471a1128ae1f4257f1b6d26ef52b783d46909 100644 (file)
@@ -11,51 +11,30 @@ package org.opendaylight.ovsdb.integrationtest.schema.hardwarevtep;
 
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
 import static org.junit.Assume.assumeTrue;
 import static org.opendaylight.ovsdb.lib.operations.Operations.op;
 
-import com.google.common.collect.Lists;
 import com.google.common.collect.Sets;
-import com.google.common.util.concurrent.ListenableFuture;
-import java.io.IOException;
-import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
-import java.util.Set;
 import java.util.concurrent.ExecutionException;
-import javax.inject.Inject;
 import org.junit.Assert;
 import org.junit.Before;
 import org.junit.Test;
 import org.junit.runner.RunWith;
-import org.opendaylight.ovsdb.lib.MonitorCallBack;
 import org.opendaylight.ovsdb.lib.OvsdbClient;
 import org.opendaylight.ovsdb.lib.it.LibraryIntegrationTestBase;
 import org.opendaylight.ovsdb.lib.it.LibraryIntegrationTestUtils;
-import org.opendaylight.ovsdb.lib.message.MonitorRequest;
-import org.opendaylight.ovsdb.lib.message.MonitorRequestBuilder;
-import org.opendaylight.ovsdb.lib.message.MonitorSelect;
-import org.opendaylight.ovsdb.lib.message.TableUpdate;
-import org.opendaylight.ovsdb.lib.message.TableUpdates;
 import org.opendaylight.ovsdb.lib.notation.Mutator;
 import org.opendaylight.ovsdb.lib.notation.Row;
 import org.opendaylight.ovsdb.lib.notation.UUID;
 import org.opendaylight.ovsdb.lib.operations.OperationResult;
 import org.opendaylight.ovsdb.lib.operations.TransactionBuilder;
-import org.opendaylight.ovsdb.lib.schema.DatabaseSchema;
-import org.opendaylight.ovsdb.lib.schema.GenericTableSchema;
-import org.opendaylight.ovsdb.lib.schema.TableSchema;
-import org.opendaylight.ovsdb.lib.schema.typed.TypedBaseTable;
 import org.opendaylight.ovsdb.schema.hardwarevtep.Global;
 import org.opendaylight.ovsdb.schema.hardwarevtep.Manager;
-import org.opendaylight.ovsdb.schema.openvswitch.OpenVSwitch;
 import org.ops4j.pax.exam.junit.PaxExam;
 import org.ops4j.pax.exam.spi.reactors.ExamReactorStrategy;
 import org.ops4j.pax.exam.spi.reactors.PerSuite;
-import org.osgi.framework.BundleContext;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -63,75 +42,12 @@ import org.slf4j.LoggerFactory;
 @ExamReactorStrategy(PerSuite.class)
 public class HardwareVTEPIT  extends LibraryIntegrationTestBase {
     private static final Logger LOG = LoggerFactory.getLogger(HardwareVTEPIT.class);
-    private static boolean monitorReady = false;
-    private static boolean schemaSupported = false;
-    private static final String ASSERT_TRANS_ERROR = "Transaction should not have errors";
-    private static final String ASSERT_TRANS_RESULT_EMPTY = "Transaction should not be empty";
-    private static final String ASSERT_TRANS_OPERATION_COUNT = "Transaction should match number of operations";
-    private static final String ASSERT_TRANS_UUID = "Transaction UUID should not be null";
     private UUID testManagerUuid = null;
 
-    private static Map<String, Map<UUID, Row>> tableCache = new HashMap<>();
-    private static Map<String, Map<UUID, Row>> getTableCache () {
-        return tableCache;
-    }
-
-    private static OvsdbClient ovsdbClient;
-    private OvsdbClient getClient () {
-        return ovsdbClient;
-    }
-
-    private static DatabaseSchema dbSchema;
-    private DatabaseSchema getDbSchema () {
-        return dbSchema;
-    }
-
-    @Inject
-    private BundleContext bc;
-
     @Before
-    public void set() throws Exception {
+    public void setup() throws Exception {
+        schema = LibraryIntegrationTestUtils.HARDWARE_VTEP;
         super.setup();
-        assumeTrue(LibraryIntegrationTestUtils.HARDWARE_VTEP + " is required.", checkSchema(LibraryIntegrationTestUtils.HARDWARE_VTEP));
-        assertTrue("Failed to monitor tables", monitorTables());
-        LOG.info("{} schema version = {}", LibraryIntegrationTestUtils.OPEN_VSWITCH_SCHEMA,
-                getClient().getDatabaseSchema(LibraryIntegrationTestUtils.OPEN_VSWITCH_SCHEMA).getVersion());
-    }
-
-    public boolean checkSchema (String schema) {
-        if (schemaSupported) {
-            LOG.info("Schema ({}) is supported", schema);
-            return true;
-        }
-        try {
-            ovsdbClient = LibraryIntegrationTestUtils.getTestConnection(this);
-            assertNotNull("Invalid Client. Check connection params", ovsdbClient);
-            //Thread.sleep(3000); // Wait for a few seconds to get the Schema exchange done
-            if (isSchemaSupported(ovsdbClient, schema)) {
-                dbSchema = ovsdbClient.getSchema(schema).get();
-                assertNotNull(dbSchema);
-                LOG.info("{} schema in {} with tables: {}",
-                        schema, ovsdbClient.getConnectionInfo(), dbSchema.getTables());
-                schemaSupported = true;
-                return true;
-            }
-        } catch (Exception e) {
-            fail("Exception : "+e.getMessage());
-        }
-
-        LOG.info("Schema ({}) is not supported", schema);
-        return false;
-    }
-
-    public UUID getOpenVSwitchTableUuid (OvsdbClient ovs, Map<String, Map<UUID, Row>> tableCache) {
-        OpenVSwitch openVSwitch = getClient().getTypedRowWrapper(OpenVSwitch.class, null);
-        Map<UUID, Row> ovsTable = tableCache.get(openVSwitch.getSchema().getName());
-        if (ovsTable != null) {
-            if (ovsTable.keySet().size() >= 1) {
-                return (UUID)ovsTable.keySet().toArray()[0];
-            }
-        }
-        return null;
     }
 
     public UUID getGlobalTableUuid(OvsdbClient ovs, Map<String, Map<UUID, Row>> tableCache) {
@@ -145,118 +61,11 @@ public class HardwareVTEPIT  extends LibraryIntegrationTestBase {
         return null;
     }
 
-    public boolean isSchemaSupported (OvsdbClient client, String schema) throws ExecutionException, InterruptedException {
-        ListenableFuture<List<String>> databases = client.getDatabases();
-        List<String> dbNames = databases.get();
-        assertNotNull(dbNames);
-        return dbNames.contains(schema);
-    }
-
-    /**
-     * As per RFC 7047, section 4.1.5, if a Monitor request is sent without any columns, the update response will not include
-     * the _uuid column.
-     * ----------------------------------------------------------------------------------------------------------------------------------
-     * Each <monitor-request> specifies one or more columns and the manner in which the columns (or the entire table) are to be monitored.
-     * The "columns" member specifies the columns whose values are monitored. It MUST NOT contain duplicates.
-     * If "columns" is omitted, all columns in the table, except for "_uuid", are monitored.
-     * ----------------------------------------------------------------------------------------------------------------------------------
-     * In order to overcome this limitation, this method
-     *
-     * @return MonitorRequest that includes all the Bridge Columns including _uuid
-     */
-    public <T extends TypedBaseTable<GenericTableSchema>> MonitorRequest getAllColumnsMonitorRequest (Class <T> klazz) {
-        TypedBaseTable<GenericTableSchema> table = getClient().createTypedRowWrapper(klazz);
-        GenericTableSchema tableSchema = table.getSchema();
-        Set<String> columns = tableSchema.getColumns();
-        MonitorRequestBuilder<GenericTableSchema> bridgeBuilder = MonitorRequestBuilder.builder(table.getSchema());
-        for (String column : columns) {
-            bridgeBuilder.addColumn(column);
-        }
-        return bridgeBuilder.with(new MonitorSelect(true, true, true, true)).build();
-    }
-
-    public <T extends TableSchema<T>> MonitorRequest getAllColumnsMonitorRequest (T tableSchema) {
-        Set<String> columns = tableSchema.getColumns();
-        MonitorRequestBuilder<T> monitorBuilder = MonitorRequestBuilder.builder(tableSchema);
-        for (String column : columns) {
-            monitorBuilder.addColumn(column);
-        }
-        return monitorBuilder.with(new MonitorSelect(true, true, true, true)).build();
-    }
-
-    public boolean monitorTables () throws ExecutionException, InterruptedException, IOException {
-        if (monitorReady) {
-            LOG.info("Monitoring is already initialized.");
-            return monitorReady;
-        }
-
-        assertNotNull(getDbSchema());
-
-        List<MonitorRequest> monitorRequests = Lists.newArrayList();
-        Set<String> tables = getDbSchema().getTables();
-        assertNotNull("ovsdb tables should not be null", tables);
-
-        for (String tableName : tables) {
-            GenericTableSchema tableSchema = getDbSchema().table(tableName, GenericTableSchema.class);
-            monitorRequests.add(this.getAllColumnsMonitorRequest(tableSchema));
-        }
-        TableUpdates updates = getClient().monitor(getDbSchema(), monitorRequests, new UpdateMonitor());
-        assertNotNull(updates);
-        this.updateTableCache(updates);
-
-        monitorReady = true;
-        LOG.info("Monitoring is initialized.");
-        return monitorReady;
-    }
-
-    private void updateTableCache (TableUpdates updates) {
-        for (String tableName : updates.getUpdates().keySet()) {
-            Map<UUID, Row> tUpdate = getTableCache().get(tableName);
-            TableUpdate update = updates.getUpdates().get(tableName);
-            for (UUID uuid : (Set<UUID>)update.getRows().keySet()) {
-                if (update.getNew(uuid) != null) {
-                    if (tUpdate == null) {
-                        tUpdate = new HashMap<>();
-                        getTableCache().put(tableName, tUpdate);
-                    }
-                    tUpdate.put(uuid, update.getNew(uuid));
-                } else {
-                    tUpdate.remove(uuid);
-                }
-            }
-        }
-    }
-
-    private class UpdateMonitor implements MonitorCallBack {
-        @Override
-        public void update(TableUpdates result, DatabaseSchema dbSchema) {
-            updateTableCache(result);
-        }
-
-        @Override
-        public void exception(Throwable t) {
-            LOG.error("Exception t = " + t);
-        }
-    }
-
-    public List<OperationResult> executeTransaction (TransactionBuilder transactionBuilder, String text)
-            throws ExecutionException, InterruptedException {
-        ListenableFuture<List<OperationResult>> results = transactionBuilder.execute();
-        List<OperationResult> operationResults = results.get();
-        LOG.info("{}: {}", text, operationResults);
-        org.junit.Assert.assertFalse(ASSERT_TRANS_RESULT_EMPTY, operationResults.isEmpty());
-        assertEquals(ASSERT_TRANS_OPERATION_COUNT, transactionBuilder.getOperations().size(), operationResults.size());
-        for (OperationResult result : operationResults) {
-            assertNull(ASSERT_TRANS_ERROR, result.getError());
-        }
-        //Thread.sleep(500); // Wait for a few seconds to ensure the cache updates
-        return operationResults;
-    }
-
     /**
      * Create a new manager string in addition to whatever is already there
      * Will modify the Global table to include the UUID to the new Manager row
      */
+    @SuppressWarnings("unchecked")
     public void managerInsert () throws ExecutionException, InterruptedException {
         //Ensure test only proceeds if HW VTEP is supported
         assumeTrue(isSchemaSupported(getClient(), LibraryIntegrationTestUtils.HARDWARE_VTEP));
index cad4a5e129d9304e1e84ddf1a2ff105e605b65bc..29e0186bcd4a6fccb09c823daeab477a45ea472a 100644 (file)
@@ -16,36 +16,24 @@ import static org.junit.Assert.assertNotSame;
 import static org.junit.Assert.assertNull;
 import static org.junit.Assert.assertSame;
 import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
 import static org.junit.Assume.assumeTrue;
 import static org.opendaylight.ovsdb.lib.operations.Operations.op;
 
 import com.google.common.collect.ImmutableMap;
 import com.google.common.collect.ImmutableSet;
-import com.google.common.collect.Lists;
 import com.google.common.collect.Maps;
 import com.google.common.collect.Sets;
-import com.google.common.util.concurrent.ListenableFuture;
-import java.io.IOException;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
-import java.util.Set;
 import java.util.concurrent.ExecutionException;
-import javax.inject.Inject;
 import org.junit.Before;
 import org.junit.Test;
 import org.junit.runner.RunWith;
-import org.opendaylight.ovsdb.lib.MonitorCallBack;
 import org.opendaylight.ovsdb.lib.OvsdbClient;
 import org.opendaylight.ovsdb.lib.error.SchemaVersionMismatchException;
 import org.opendaylight.ovsdb.lib.it.LibraryIntegrationTestBase;
 import org.opendaylight.ovsdb.lib.it.LibraryIntegrationTestUtils;
-import org.opendaylight.ovsdb.lib.message.MonitorRequest;
-import org.opendaylight.ovsdb.lib.message.MonitorRequestBuilder;
-import org.opendaylight.ovsdb.lib.message.MonitorSelect;
-import org.opendaylight.ovsdb.lib.message.TableUpdate;
-import org.opendaylight.ovsdb.lib.message.TableUpdates;
 import org.opendaylight.ovsdb.lib.notation.Mutator;
 import org.opendaylight.ovsdb.lib.notation.Row;
 import org.opendaylight.ovsdb.lib.notation.UUID;
@@ -53,9 +41,6 @@ import org.opendaylight.ovsdb.lib.notation.Version;
 import org.opendaylight.ovsdb.lib.operations.OperationResult;
 import org.opendaylight.ovsdb.lib.operations.TransactionBuilder;
 import org.opendaylight.ovsdb.lib.schema.DatabaseSchema;
-import org.opendaylight.ovsdb.lib.schema.GenericTableSchema;
-import org.opendaylight.ovsdb.lib.schema.TableSchema;
-import org.opendaylight.ovsdb.lib.schema.typed.TypedBaseTable;
 import org.opendaylight.ovsdb.schema.openvswitch.AutoAttach;
 import org.opendaylight.ovsdb.schema.openvswitch.Bridge;
 import org.opendaylight.ovsdb.schema.openvswitch.Controller;
@@ -75,8 +60,6 @@ import org.opendaylight.ovsdb.schema.openvswitch.SSL;
 import org.ops4j.pax.exam.junit.PaxExam;
 import org.ops4j.pax.exam.spi.reactors.ExamReactorStrategy;
 import org.ops4j.pax.exam.spi.reactors.PerSuite;
-import org.osgi.framework.Bundle;
-import org.osgi.framework.BundleContext;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -84,15 +67,8 @@ import org.slf4j.LoggerFactory;
 @ExamReactorStrategy(PerSuite.class)
 public class OpenVSwitchIT extends LibraryIntegrationTestBase {
     private static final Logger LOG = LoggerFactory.getLogger(OpenVSwitchIT.class);
-    private static boolean monitorReady = false;
-    private static boolean schemaSupported = false;
     private static final String TEST_BRIDGE_NAME = "br_test";
     private static final String TEST_MANAGER_UUID_STR = "managerUuidName";
-    private static final String ASSERT_TRANS_ERROR = "Transaction should not have errors";
-    private static final String ASSERT_TRANS_RESULT_EMPTY = "Transaction should not be empty";
-    private static final String ASSERT_TRANS_OPERATION_COUNT = "Transaction should match number of operations";
-    private static final String ASSERT_TRANS_UUID = "Transaction UUID should not be null";
-    private Version schemaVersion;
     private UUID testBridgeUuid = null;
     private UUID testController1Uuid = null;
     private UUID testController2Uuid = null;
@@ -117,74 +93,10 @@ public class OpenVSwitchIT extends LibraryIntegrationTestBase {
     private Version ipfixCacheFromVersion = Version.fromString("7.3.0");
     private Version autoAttachFromVersion = Version.fromString("7.11.2");
 
-    private static Map<String, Map<UUID, Row>> tableCache = new HashMap<>();
-    private static Map<String, Map<UUID, Row>> getTableCache () {
-        return tableCache;
-    }
-
-    private static OvsdbClient ovsdbClient;
-    private OvsdbClient getClient () {
-        return ovsdbClient;
-    }
-
-    private static DatabaseSchema dbSchema;
-    private DatabaseSchema getDbSchema () {
-        return dbSchema;
-    }
-
-    @Inject
-    private BundleContext bc;
-
     @Before
-    public void areWeReady() throws InterruptedException, IOException, ExecutionException {
-        assertNotNull(bc);
-        boolean debugit = false;
-        Bundle b[] = bc.getBundles();
-        for (Bundle element : b) {
-            int state = element.getState();
-            if (state != Bundle.ACTIVE && state != Bundle.RESOLVED) {
-                LOG.info("Bundle: {} state: {}", element.getSymbolicName(),
-                        LibraryIntegrationTestUtils.bundleStateToString(state));
-                debugit = true;
-            }
-        }
-        if (debugit) {
-            LOG.debug("Do some debugging because some bundle is unresolved");
-            Thread.sleep(600000);
-        }
-
-        // Assert if true, if false we are good to go!
-        assertFalse(debugit);
-
-        assertTrue(LibraryIntegrationTestUtils.OPEN_VSWITCH_SCHEMA + " is required.", checkSchema(LibraryIntegrationTestUtils.OPEN_VSWITCH_SCHEMA));
-        assertTrue("Failed to monitor tables", monitorTables());
-        schemaVersion = getClient().getDatabaseSchema(LibraryIntegrationTestUtils.OPEN_VSWITCH_SCHEMA).getVersion();
-        LOG.info("{} schema version = {}", LibraryIntegrationTestUtils.OPEN_VSWITCH_SCHEMA, schemaVersion);
-    }
-
-    public boolean checkSchema (String schema) {
-        if (schemaSupported) {
-            LOG.info("Schema ({}) is supported", schema);
-            return true;
-        }
-        try {
-            ovsdbClient = LibraryIntegrationTestUtils.getTestConnection(this);
-            assertNotNull("Invalid Client. Check connection params", ovsdbClient);
-            //Thread.sleep(3000); // Wait for a few seconds to get the Schema exchange done
-            if (isSchemaSupported(ovsdbClient, schema)) {
-                dbSchema = ovsdbClient.getSchema(schema).get();
-                assertNotNull(dbSchema);
-                LOG.info("{} schema in {} with tables: {}",
-                        schema, ovsdbClient.getConnectionInfo(), dbSchema.getTables());
-                schemaSupported = true;
-                return true;
-            }
-        } catch (Exception e) {
-            fail("Exception : "+e.getMessage());
-        }
-
-        LOG.info("Schema ({}) is not supported", schema);
-        return false;
+    public void setup() throws Exception {
+        schema = LibraryIntegrationTestUtils.OPEN_VSWITCH;
+        super.setup();
     }
 
     public UUID getOpenVSwitchTableUuid (OvsdbClient ovs, Map<String, Map<UUID, Row>> tableCache) {
@@ -198,114 +110,6 @@ public class OpenVSwitchIT extends LibraryIntegrationTestBase {
         return null;
     }
 
-    public boolean isSchemaSupported (OvsdbClient client, String schema) throws ExecutionException, InterruptedException {
-        ListenableFuture<List<String>> databases = client.getDatabases();
-        List<String> dbNames = databases.get();
-        assertNotNull(dbNames);
-        return dbNames.contains(schema);
-    }
-
-    /**
-     * As per RFC 7047, section 4.1.5, if a Monitor request is sent without any columns, the update response will not include
-     * the _uuid column.
-     * ----------------------------------------------------------------------------------------------------------------------------------
-     * Each <monitor-request> specifies one or more columns and the manner in which the columns (or the entire table) are to be monitored.
-     * The "columns" member specifies the columns whose values are monitored. It MUST NOT contain duplicates.
-     * If "columns" is omitted, all columns in the table, except for "_uuid", are monitored.
-     * ----------------------------------------------------------------------------------------------------------------------------------
-     * In order to overcome this limitation, this method
-     *
-     * @return MonitorRequest that includes all the Bridge Columns including _uuid
-     */
-    public <T extends TypedBaseTable<GenericTableSchema>> MonitorRequest getAllColumnsMonitorRequest (Class <T> klazz) {
-        TypedBaseTable<GenericTableSchema> table = getClient().createTypedRowWrapper(klazz);
-        GenericTableSchema tableSchema = table.getSchema();
-        Set<String> columns = tableSchema.getColumns();
-        MonitorRequestBuilder<GenericTableSchema> bridgeBuilder = MonitorRequestBuilder.builder(table.getSchema());
-        for (String column : columns) {
-            bridgeBuilder.addColumn(column);
-        }
-        return bridgeBuilder.with(new MonitorSelect(true, true, true, true)).build();
-    }
-
-    public <T extends TableSchema<T>> MonitorRequest getAllColumnsMonitorRequest (T tableSchema) {
-        Set<String> columns = tableSchema.getColumns();
-        MonitorRequestBuilder<T> monitorBuilder = MonitorRequestBuilder.builder(tableSchema);
-        for (String column : columns) {
-            monitorBuilder.addColumn(column);
-        }
-        return monitorBuilder.with(new MonitorSelect(true, true, true, true)).build();
-    }
-
-    public boolean monitorTables () throws ExecutionException, InterruptedException, IOException {
-        if (monitorReady) {
-            LOG.info("Monitoring is already initialized.");
-            return monitorReady;
-        }
-
-        assertNotNull(getDbSchema());
-
-        List<MonitorRequest> monitorRequests = Lists.newArrayList();
-        Set<String> tables = getDbSchema().getTables();
-        assertNotNull("ovsdb tables should not be null", tables);
-
-        for (String tableName : tables) {
-            GenericTableSchema tableSchema = getDbSchema().table(tableName, GenericTableSchema.class);
-            monitorRequests.add(this.getAllColumnsMonitorRequest(tableSchema));
-        }
-        TableUpdates updates = getClient().monitor(getDbSchema(), monitorRequests, new UpdateMonitor());
-        assertNotNull(updates);
-        this.updateTableCache(updates);
-
-        monitorReady = true;
-        LOG.info("Monitoring is initialized.");
-        return monitorReady;
-    }
-
-    private void updateTableCache (TableUpdates updates) {
-        for (String tableName : updates.getUpdates().keySet()) {
-            Map<UUID, Row> tUpdate = getTableCache().get(tableName);
-            TableUpdate update = updates.getUpdates().get(tableName);
-            for (UUID uuid : (Set<UUID>)update.getRows().keySet()) {
-                if (update.getNew(uuid) != null) {
-                    if (tUpdate == null) {
-                        tUpdate = new HashMap<>();
-                        getTableCache().put(tableName, tUpdate);
-                    }
-                    tUpdate.put(uuid, update.getNew(uuid));
-                } else {
-                    tUpdate.remove(uuid);
-                }
-            }
-        }
-    }
-
-    private class UpdateMonitor implements MonitorCallBack {
-        @Override
-        public void update(TableUpdates result, DatabaseSchema dbSchema) {
-            updateTableCache(result);
-        }
-
-        @Override
-        public void exception(Throwable t) {
-            LOG.error("Exception t = " + t);
-        }
-    }
-
-    public List<OperationResult> executeTransaction (TransactionBuilder transactionBuilder, String text)
-            throws ExecutionException, InterruptedException {
-        ListenableFuture<List<OperationResult>> results = transactionBuilder.execute();
-        List<OperationResult> operationResults = results.get();
-        LOG.info("{}: {}", text, operationResults);
-        org.junit.Assert.assertFalse(ASSERT_TRANS_RESULT_EMPTY, operationResults.isEmpty());
-        assertEquals(ASSERT_TRANS_OPERATION_COUNT, transactionBuilder.getOperations().size(), operationResults.size());
-        for (OperationResult result : operationResults) {
-            assertNull(ASSERT_TRANS_ERROR, result.getError());
-        }
-        //Thread.sleep(500); // Wait for a few seconds to ensure the cache updates
-        return operationResults;
-    }
-
     public UUID bridgeInsert () throws ExecutionException, InterruptedException {
         Bridge bridge = getClient().createTypedRowWrapper(Bridge.class);
         bridge.setName(TEST_BRIDGE_NAME);
@@ -358,6 +162,7 @@ public class OpenVSwitchIT extends LibraryIntegrationTestBase {
     }
 
     @Test
+    @SuppressWarnings("unchecked")
     public void testBridge () throws ExecutionException, InterruptedException {
         testBridgeUuid = bridgeInsert();
 
@@ -370,6 +175,7 @@ public class OpenVSwitchIT extends LibraryIntegrationTestBase {
         bridgeDelete(testBridgeUuid);
     }
 
+    @SuppressWarnings("unchecked")
     private void controllerInsert () throws ExecutionException, InterruptedException {
         String controllerUuidStr = "controller";
         Controller controller1 = getClient().createTypedRowWrapper(Controller.class);
@@ -436,7 +242,7 @@ public class OpenVSwitchIT extends LibraryIntegrationTestBase {
     private void controllerDelete () throws ExecutionException, InterruptedException {
         Controller controller = getClient().getTypedRowWrapper(Controller.class, null);
         Bridge bridge = getClient().getTypedRowWrapper(Bridge.class, null);
-        DatabaseSchema dbSchema = getClient().getSchema(LibraryIntegrationTestUtils.OPEN_VSWITCH_SCHEMA).get();
+        DatabaseSchema dbSchema = getClient().getSchema(LibraryIntegrationTestUtils.OPEN_VSWITCH).get();
 
         TransactionBuilder transactionBuilder = getClient().transactBuilder(dbSchema)
                 .add(op.delete(controller.getSchema())
@@ -481,6 +287,7 @@ public class OpenVSwitchIT extends LibraryIntegrationTestBase {
         getClient().createTypedRowWrapper(FlowSampleCollectorSet.class);
     }
 
+    @SuppressWarnings("unchecked")
     public void flowSampleCollectorSetInsert () throws ExecutionException, InterruptedException {
         // Don't run this test if the table is not supported
         assumeTrue(schemaVersion.compareTo(flowSampleCollectorSetFromVersion) >= 0);
@@ -545,6 +352,7 @@ public class OpenVSwitchIT extends LibraryIntegrationTestBase {
         getClient().createTypedRowWrapper(FlowTable.class);
     }
 
+    @SuppressWarnings("unchecked")
     public void flowTableInsert () throws ExecutionException, InterruptedException {
         // Don't run this test if the table is not supported
         assumeTrue(schemaVersion.compareTo(flowTableFromVersion) >= 0);
@@ -631,6 +439,7 @@ public class OpenVSwitchIT extends LibraryIntegrationTestBase {
         getClient().createTypedRowWrapper(IPFIX.class);
     }
 
+    @SuppressWarnings("unchecked")
     public void ipfixInsert () throws ExecutionException, InterruptedException {
         // Don't run this test if the table is not supported
         assumeTrue(schemaVersion.compareTo(ipfixFromVersion) >= 0);
@@ -710,6 +519,7 @@ public class OpenVSwitchIT extends LibraryIntegrationTestBase {
         bridgeDelete(testBridgeUuid);
     }
 
+    @SuppressWarnings("unchecked")
     public void managerInsert() throws ExecutionException, InterruptedException {
         ImmutableMap<String, String> externalIds = ImmutableMap.of("slaveof", "themaster");
         UUID openVSwitchRowUuid = getOpenVSwitchTableUuid(getClient(), getTableCache());
@@ -770,6 +580,7 @@ public class OpenVSwitchIT extends LibraryIntegrationTestBase {
         managerDelete();
     }
 
+    @SuppressWarnings("unchecked")
     public void mirrorInsert () throws ExecutionException, InterruptedException {
         String mirrorUuidStr = "testMirror";
         String mirrorName = "my_name_is_mirror";
@@ -811,7 +622,7 @@ public class OpenVSwitchIT extends LibraryIntegrationTestBase {
     private void mirrorDelete () throws ExecutionException, InterruptedException {
         Mirror mirror = getClient().getTypedRowWrapper(Mirror.class, null);
         Bridge bridge = getClient().getTypedRowWrapper(Bridge.class, null);
-        DatabaseSchema dbSchema = getClient().getSchema(LibraryIntegrationTestUtils.OPEN_VSWITCH_SCHEMA).get();
+        DatabaseSchema dbSchema = getClient().getSchema(LibraryIntegrationTestUtils.OPEN_VSWITCH).get();
 
         TransactionBuilder transactionBuilder = getClient().transactBuilder(dbSchema)
                 .add(op.delete(mirror.getSchema())
@@ -835,6 +646,7 @@ public class OpenVSwitchIT extends LibraryIntegrationTestBase {
         bridgeDelete(testBridgeUuid);
     }
 
+    @SuppressWarnings("unchecked")
     public void netFlowInsert () throws ExecutionException, InterruptedException {
         String netFlowUuidStr = "testNetFlow";
         String netFlowTargets = "172.16.20.200:6343";
@@ -878,7 +690,7 @@ public class OpenVSwitchIT extends LibraryIntegrationTestBase {
     private void netFlowDelete () throws ExecutionException, InterruptedException {
         NetFlow netFlow = getClient().getTypedRowWrapper(NetFlow.class, null);
         Bridge bridge = getClient().getTypedRowWrapper(Bridge.class, null);
-        DatabaseSchema dbSchema = getClient().getSchema(LibraryIntegrationTestUtils.OPEN_VSWITCH_SCHEMA).get();
+        DatabaseSchema dbSchema = getClient().getSchema(LibraryIntegrationTestUtils.OPEN_VSWITCH).get();
 
         TransactionBuilder transactionBuilder = getClient().transactBuilder(dbSchema)
                 .add(op.delete(netFlow.getSchema())
@@ -902,6 +714,7 @@ public class OpenVSwitchIT extends LibraryIntegrationTestBase {
         bridgeDelete(testBridgeUuid);
     }
 
+    @SuppressWarnings("unchecked")
     public void portAndInterfaceInsert () throws ExecutionException, InterruptedException {
         String portUuidStr = "testPort";
         String intfUuidStr = "testIntf";
@@ -975,7 +788,7 @@ public class OpenVSwitchIT extends LibraryIntegrationTestBase {
         Port port = getClient().getTypedRowWrapper(Port.class, null);
         Interface intf = getClient().getTypedRowWrapper(Interface.class, null);
         Bridge bridge = getClient().getTypedRowWrapper(Bridge.class, null);
-        DatabaseSchema dbSchema = getClient().getSchema(LibraryIntegrationTestUtils.OPEN_VSWITCH_SCHEMA).get();
+        DatabaseSchema dbSchema = getClient().getSchema(LibraryIntegrationTestUtils.OPEN_VSWITCH).get();
 
         TransactionBuilder transactionBuilder = getClient().transactBuilder(dbSchema)
                 .add(op.delete(port.getSchema())
@@ -1003,6 +816,7 @@ public class OpenVSwitchIT extends LibraryIntegrationTestBase {
         bridgeDelete(testBridgeUuid);
     }
 
+    @SuppressWarnings("unchecked")
     public void autoAttachInsert() throws ExecutionException, InterruptedException {
         String autoattachUuid = "testAutoattachUuid";
         String systemName = "testSystemName";
@@ -1046,7 +860,7 @@ public class OpenVSwitchIT extends LibraryIntegrationTestBase {
     public void autoAttachDelete() throws ExecutionException, InterruptedException {
         AutoAttach autoattach = getClient().getTypedRowWrapper(AutoAttach.class, null);
         Bridge bridge = getClient().getTypedRowWrapper(Bridge.class, null);
-        DatabaseSchema dbSchema = getClient().getSchema(LibraryIntegrationTestUtils.OPEN_VSWITCH_SCHEMA).get();
+        DatabaseSchema dbSchema = getClient().getSchema(LibraryIntegrationTestUtils.OPEN_VSWITCH).get();
         TransactionBuilder transactionBuilder = getClient().transactBuilder(dbSchema)
                 .add(op.delete(autoattach.getSchema())
                         .where(autoattach.getUuidColumn().getSchema().opEqual(testAutoattachUuid))
@@ -1075,6 +889,7 @@ public class OpenVSwitchIT extends LibraryIntegrationTestBase {
         bridgeDelete(testBridgeUuid);
     }
 
+    @SuppressWarnings("unchecked")
     public void qosInsert() throws ExecutionException, InterruptedException {
         String portUuidStr = "testQosPortUuid";
         String intfUuidStr = "testQosIntfUuid";
@@ -1159,7 +974,7 @@ public class OpenVSwitchIT extends LibraryIntegrationTestBase {
         Interface intf = getClient().getTypedRowWrapper(Interface.class, null);
         Qos qos = getClient().getTypedRowWrapper(Qos.class, null);
         Bridge bridge = getClient().getTypedRowWrapper(Bridge.class, null);
-        DatabaseSchema dbSchema = getClient().getSchema(LibraryIntegrationTestUtils.OPEN_VSWITCH_SCHEMA).get();
+        DatabaseSchema dbSchema = getClient().getSchema(LibraryIntegrationTestUtils.OPEN_VSWITCH).get();
 
         TransactionBuilder transactionBuilder = getClient().transactBuilder(dbSchema)
                 .add(op.delete(port.getSchema())
@@ -1195,6 +1010,7 @@ public class OpenVSwitchIT extends LibraryIntegrationTestBase {
         bridgeDelete(testBridgeUuid);
     }
 
+    @SuppressWarnings("unchecked")
     public void queueInsert() throws InterruptedException, ExecutionException {
         /**
          * This is an arbitrary String that is a placeholder for
@@ -1249,7 +1065,7 @@ public class OpenVSwitchIT extends LibraryIntegrationTestBase {
     private void queueDelete () throws ExecutionException, InterruptedException {
         Queue queue = getClient().getTypedRowWrapper(Queue.class, null);
         Qos qos = getClient().getTypedRowWrapper(Qos.class, null);
-        DatabaseSchema dbSchema = getClient().getSchema(LibraryIntegrationTestUtils.OPEN_VSWITCH_SCHEMA).get();
+        DatabaseSchema dbSchema = getClient().getSchema(LibraryIntegrationTestUtils.OPEN_VSWITCH).get();
 
         TransactionBuilder transactionBuilder = getClient().transactBuilder(dbSchema)
                 .add(op.delete(queue.getSchema())
@@ -1275,6 +1091,7 @@ public class OpenVSwitchIT extends LibraryIntegrationTestBase {
         bridgeDelete(testBridgeUuid);
     }
 
+    @SuppressWarnings("unchecked")
     public void sFlowInsert () throws ExecutionException, InterruptedException {
         String sFlowUuidStr = "testSFlow";
         String sFlowTarget = "172.16.20.200:6343";
@@ -1323,7 +1140,7 @@ public class OpenVSwitchIT extends LibraryIntegrationTestBase {
     private void sFlowDelete () throws ExecutionException, InterruptedException {
         SFlow sFlow = getClient().getTypedRowWrapper(SFlow.class, null);
         Bridge bridge = getClient().getTypedRowWrapper(Bridge.class, null);
-        DatabaseSchema dbSchema = getClient().getSchema(LibraryIntegrationTestUtils.OPEN_VSWITCH_SCHEMA).get();
+        DatabaseSchema dbSchema = getClient().getSchema(LibraryIntegrationTestUtils.OPEN_VSWITCH).get();
 
         TransactionBuilder transactionBuilder = getClient().transactBuilder(dbSchema)
                 .add(op.delete(sFlow.getSchema())
@@ -1347,6 +1164,7 @@ public class OpenVSwitchIT extends LibraryIntegrationTestBase {
         bridgeDelete(testBridgeUuid);
     }
 
+    @SuppressWarnings("unchecked")
     public void sslInsert () throws ExecutionException, InterruptedException {
 
         String sslUuidStr = "sslUuidName";
index 6325114e9cfab1f391b34fcc040a9b78b7f69024..e5f94a837c4e2a5a2e5c8bc5fce7829033a3f616 100644 (file)
@@ -11,7 +11,6 @@ import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertFalse;
 import static org.junit.Assert.assertNotNull;
 import static org.junit.Assert.assertNull;
-import static org.junit.Assert.fail;
 import static org.opendaylight.ovsdb.lib.operations.Operations.op;
 
 import java.io.IOException;
@@ -19,13 +18,10 @@ import java.lang.reflect.InvocationTargetException;
 import java.util.List;
 import java.util.concurrent.ExecutionException;
 
-import javax.inject.Inject;
-
 import org.junit.After;
 import org.junit.Before;
 import org.junit.Test;
 import org.junit.runner.RunWith;
-import org.opendaylight.ovsdb.lib.OvsdbClient;
 import org.opendaylight.ovsdb.lib.notation.Mutator;
 import org.opendaylight.ovsdb.lib.notation.UUID;
 import org.opendaylight.ovsdb.lib.operations.OperationResult;
@@ -36,8 +32,6 @@ import org.opendaylight.ovsdb.schema.openvswitch.OpenVSwitch;
 import org.ops4j.pax.exam.junit.PaxExam;
 import org.ops4j.pax.exam.spi.reactors.ExamReactorStrategy;
 import org.ops4j.pax.exam.spi.reactors.PerSuite;
-import org.osgi.framework.Bundle;
-import org.osgi.framework.BundleContext;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -49,61 +43,31 @@ import com.google.common.util.concurrent.ListenableFuture;
 @ExamReactorStrategy(PerSuite.class)
 public class LibraryIT extends LibraryIntegrationTestBase {
     private static final Logger LOG = LoggerFactory.getLogger(LibraryIT.class);
-
-    @Inject
-    private BundleContext bc;
-    private OvsdbClient client = null;
+    private static final String TEST_BRIDGE_NAME = "br_test";
+    private static UUID testBridgeUuid = null;
 
     @Before
-    public void areWeReady() throws InterruptedException {
-        assertNotNull(bc);
-        boolean debugit = false;
-        Bundle b[] = bc.getBundles();
-        for (Bundle element : b) {
-            int state = element.getState();
-            if (state != Bundle.ACTIVE && state != Bundle.RESOLVED) {
-                LOG.info("Bundle: {} state: {}", element.getSymbolicName(),
-                        LibraryIntegrationTestUtils.bundleStateToString(state));
-                debugit = true;
-            }
-        }
-        if (debugit) {
-            LOG.debug("Do some debugging because some bundle is unresolved");
-            Thread.sleep(600000);
-        }
-
-        // Assert if true, if false we are good to go!
-        assertFalse(debugit);
-        try {
-            client = LibraryIntegrationTestUtils.getTestConnection(this);
-        } catch (Exception e) {
-            fail("Exception : "+e.getMessage());
-        }
-    }
-
-    public boolean isSchemaSupported(String schema) throws ExecutionException, InterruptedException {
-        ListenableFuture<List<String>> databases = client.getDatabases();
-        List<String> dbNames = databases.get();
-        assertNotNull(dbNames);
-        return dbNames.contains(schema);
+    public void setup() throws Exception {
+        schema = LibraryIntegrationTestUtils.OPEN_VSWITCH;
+        super.setup();
     }
 
-    static String testBridgeName = "br_test";
-    static UUID testBridgeUuid = null;
-    private void createTypedBridge(DatabaseSchema dbSchema) throws IOException, InterruptedException, ExecutionException, NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
-        Bridge bridge = client.createTypedRowWrapper(Bridge.class);
-        bridge.setName(testBridgeName);
+    private void createTypedBridge(DatabaseSchema dbSchema) throws IOException, InterruptedException,
+            ExecutionException, NoSuchMethodException, IllegalAccessException, IllegalArgumentException,
+            InvocationTargetException {
+        Bridge bridge = ovsdbClient.createTypedRowWrapper(Bridge.class);
+        bridge.setName(TEST_BRIDGE_NAME);
         bridge.setStatus(ImmutableMap.of("key", "value"));
         bridge.setFloodVlans(Sets.newHashSet(34L));
 
-        OpenVSwitch openVSwitch = client.createTypedRowWrapper(OpenVSwitch.class);
-        openVSwitch.setBridges(Sets.newHashSet(new UUID(testBridgeName)));
+        OpenVSwitch openVSwitch = ovsdbClient.createTypedRowWrapper(OpenVSwitch.class);
+        openVSwitch.setBridges(Sets.newHashSet(new UUID(TEST_BRIDGE_NAME)));
 
         int insertOperationIndex = 0;
 
-        TransactionBuilder transactionBuilder = client.transactBuilder(dbSchema)
+        TransactionBuilder transactionBuilder = ovsdbClient.transactBuilder(dbSchema)
                 .add(op.insert(bridge.getSchema())
-                        .withId(testBridgeName)
+                        .withId(TEST_BRIDGE_NAME)
                         .value(bridge.getNameColumn()))
                 .add(op.update(bridge.getSchema())
                         .set(bridge.getStatusColumn())
@@ -119,7 +83,7 @@ public class LibraryIT extends LibraryIntegrationTestBase {
         assertFalse(operationResults.isEmpty());
         // Check if Results matches the number of operations in transaction
         assertEquals(transactionBuilder.getOperations().size(), operationResults.size());
-        System.out.println("Insert & Update operation results = " + operationResults);
+        LOG.info("Insert & Update operation results = {}", operationResults);
         for (OperationResult result : operationResults) {
             assertNull(result.getError());
         }
@@ -129,41 +93,42 @@ public class LibraryIT extends LibraryIntegrationTestBase {
 
     @Test
     public void tableTest() throws Exception {
-        assertNotNull("Invalid Client. Check connection params", client);
+        assertNotNull("Invalid Client. Check connection params", ovsdbClient);
         Thread.sleep(3000); // Wait for a few seconds to get the Schema exchange done
-        if (isSchemaSupported(LibraryIntegrationTestUtils.OPEN_VSWITCH_SCHEMA)) {
-            DatabaseSchema dbSchema = client.getSchema(LibraryIntegrationTestUtils.OPEN_VSWITCH_SCHEMA).get();
+        if (isSchemaSupported(LibraryIntegrationTestUtils.OPEN_VSWITCH)) {
+            DatabaseSchema dbSchema = ovsdbClient.getSchema(LibraryIntegrationTestUtils.OPEN_VSWITCH).get();
             assertNotNull(dbSchema);
-            System.out.println(LibraryIntegrationTestUtils.OPEN_VSWITCH_SCHEMA + " schema in "+ client.getConnectionInfo() +
-                    " with Tables : " + dbSchema.getTables());
+            LOG.info("{} schema in {} with Tables: {}", LibraryIntegrationTestUtils.OPEN_VSWITCH,
+                    ovsdbClient.getConnectionInfo(), dbSchema.getTables());
 
             // A simple Typed Test to make sure a Typed wrapper bundle can coexist in an OSGi environment
             createTypedBridge(dbSchema);
         }
 
         if (isSchemaSupported(LibraryIntegrationTestUtils.HARDWARE_VTEP)) {
-            DatabaseSchema dbSchema = client.getSchema(LibraryIntegrationTestUtils.HARDWARE_VTEP).get();
+            DatabaseSchema dbSchema = ovsdbClient.getSchema(LibraryIntegrationTestUtils.HARDWARE_VTEP).get();
             assertNotNull(dbSchema);
-            System.out.println(LibraryIntegrationTestUtils.HARDWARE_VTEP + " schema in "+ client.getConnectionInfo() +
-                    " with Tables : " + dbSchema.getTables());
+            LOG.info("{} schema in {} with Tables: {}", LibraryIntegrationTestUtils.HARDWARE_VTEP,
+                    ovsdbClient.getConnectionInfo(), dbSchema.getTables());
         }
     }
 
     @After
     public void tearDown() throws InterruptedException, ExecutionException {
-        Bridge bridge = client.getTypedRowWrapper(Bridge.class, null);
-        OpenVSwitch openVSwitch = client.getTypedRowWrapper(OpenVSwitch.class, null);
-        DatabaseSchema dbSchema = client.getSchema(LibraryIntegrationTestUtils.OPEN_VSWITCH_SCHEMA).get();
-        ListenableFuture<List<OperationResult>> results = client.transactBuilder(dbSchema)
+        Bridge bridge = ovsdbClient.getTypedRowWrapper(Bridge.class, null);
+        OpenVSwitch openVSwitch = ovsdbClient.getTypedRowWrapper(OpenVSwitch.class, null);
+        DatabaseSchema dbSchema = ovsdbClient.getSchema(LibraryIntegrationTestUtils.OPEN_VSWITCH).get();
+        ListenableFuture<List<OperationResult>> results = ovsdbClient.transactBuilder(dbSchema)
                 .add(op.delete(bridge.getSchema())
-                        .where(bridge.getNameColumn().getSchema().opEqual(testBridgeName))
+                        .where(bridge.getNameColumn().getSchema().opEqual(TEST_BRIDGE_NAME))
                         .build())
                 .add(op.mutate(openVSwitch.getSchema())
-                        .addMutation(openVSwitch.getBridgesColumn().getSchema(), Mutator.DELETE, Sets.newHashSet(testBridgeUuid)))
+                        .addMutation(openVSwitch.getBridgesColumn().getSchema(),
+                                Mutator.DELETE, Sets.newHashSet(testBridgeUuid)))
                 .add(op.commit(true))
                 .execute();
 
         List<OperationResult> operationResults = results.get();
-        System.out.println("Delete operation results = " + operationResults);
+        LOG.info("Delete operation results = {}", operationResults);
     }
 }
index 8718eea18d532f01e54f092481422a5e92da5b0f..bc801a56b6f5ebe2d9d35f853e3447812395c157 100644 (file)
@@ -8,6 +8,12 @@
 
 package org.opendaylight.ovsdb.lib.it;
 
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+import static org.junit.Assume.assumeTrue;
 import static org.ops4j.pax.exam.CoreOptions.composite;
 import static org.ops4j.pax.exam.CoreOptions.maven;
 import static org.ops4j.pax.exam.CoreOptions.propagateSystemProperties;
@@ -15,16 +21,78 @@ import static org.ops4j.pax.exam.CoreOptions.vmOption;
 import static org.ops4j.pax.exam.karaf.options.KarafDistributionOption.editConfigurationFilePut;
 import static org.ops4j.pax.exam.karaf.options.KarafDistributionOption.keepRuntimeFolder;
 
+import com.google.common.collect.Lists;
+import com.google.common.util.concurrent.ListenableFuture;
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.atomic.AtomicBoolean;
 import org.opendaylight.controller.mdsal.it.base.AbstractMdsalTestBase;
+import org.opendaylight.controller.sal.binding.api.BindingAwareBroker;
+import org.opendaylight.ovsdb.lib.MonitorCallBack;
+import org.opendaylight.ovsdb.lib.OvsdbClient;
+import org.opendaylight.ovsdb.lib.message.MonitorRequest;
+import org.opendaylight.ovsdb.lib.message.MonitorRequestBuilder;
+import org.opendaylight.ovsdb.lib.message.MonitorSelect;
+import org.opendaylight.ovsdb.lib.message.TableUpdate;
+import org.opendaylight.ovsdb.lib.message.TableUpdates;
+import org.opendaylight.ovsdb.lib.notation.Row;
+import org.opendaylight.ovsdb.lib.notation.UUID;
+import org.opendaylight.ovsdb.lib.notation.Version;
+import org.opendaylight.ovsdb.lib.operations.OperationResult;
+import org.opendaylight.ovsdb.lib.operations.TransactionBuilder;
+import org.opendaylight.ovsdb.lib.schema.DatabaseSchema;
+import org.opendaylight.ovsdb.lib.schema.GenericTableSchema;
+import org.opendaylight.ovsdb.lib.schema.TableSchema;
+import org.opendaylight.ovsdb.lib.schema.typed.TypedBaseTable;
 import org.ops4j.pax.exam.Configuration;
 import org.ops4j.pax.exam.Option;
 import org.ops4j.pax.exam.karaf.options.LogLevelOption;
 import org.ops4j.pax.exam.options.MavenUrlReference;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 
 /**
  * Base class for library IT.
  */
 public abstract class LibraryIntegrationTestBase extends AbstractMdsalTestBase {
+    private static final Logger LOG = LoggerFactory.getLogger(LibraryIntegrationTestBase.class);
+    protected static final String ASSERT_TRANS_ERROR = "Transaction should not have errors";
+    protected static final String ASSERT_TRANS_RESULT_EMPTY = "Transaction should not be empty";
+    protected static final String ASSERT_TRANS_OPERATION_COUNT = "Transaction should match number of operations";
+    protected static final String ASSERT_TRANS_UUID = "Transaction UUID should not be null";
+    protected static Version schemaVersion;
+    private static boolean schemaSupported = false;
+    protected static OvsdbClient ovsdbClient;
+    private static Map<String, Map<UUID, Row>> tableCache = new HashMap<>();
+    private static boolean monitorReady = false;
+    public String schema;
+
+    protected static Map<String, Map<UUID, Row>> getTableCache() {
+        return tableCache;
+    }
+
+    protected OvsdbClient getClient () {
+        return ovsdbClient;
+    }
+
+    protected static DatabaseSchema dbSchema;
+    protected DatabaseSchema getDbSchema () {
+        return dbSchema;
+    }
+
+    private static AtomicBoolean setup = new AtomicBoolean(false);
+    protected static boolean getSetup() {
+        return setup.get();
+    }
+
+    protected static void setSetup(boolean setup) {
+        LibraryIntegrationTestBase.setup.set(setup);
+    }
+
     @Override
     public String getModuleName() {
         return "library";
@@ -88,4 +156,209 @@ public abstract class LibraryIntegrationTestBase extends AbstractMdsalTestBase {
         option = composite(option, super.getLoggingOption());
         return option;
     }
+
+    protected BindingAwareBroker.ProviderContext getProviderContext() {
+        BindingAwareBroker.ProviderContext providerContext = null;
+        for (int i=0; i < 60; i++) {
+            LOG.info("Looking for ProviderContext, try {}", i);
+            providerContext = getSession();
+            if (providerContext != null) {
+                break;
+            } else {
+                try {
+                    Thread.sleep(1000);
+                } catch (InterruptedException e) {
+                    LOG.warn("Interrupted while waiting for provider context", e);
+                }
+            }
+        }
+        assertNotNull("providercontext should not be null", providerContext);
+        /* One more second to let the provider finish initialization */
+        try {
+            Thread.sleep(1000);
+        } catch (InterruptedException e) {
+            LOG.warn("Interrupted while waiting for other provider", e);
+        }
+        return providerContext;
+    }
+
+    public boolean checkSchema (String schema) {
+        if (schemaSupported) {
+            LOG.info("Schema ({}) is supported", schema);
+            return true;
+        }
+        try {
+            ovsdbClient = LibraryIntegrationTestUtils.getTestConnection(this);
+            assertNotNull("Invalid Client. Check connection params", ovsdbClient);
+            if (isSchemaSupported(ovsdbClient, schema)) {
+                dbSchema = ovsdbClient.getSchema(schema).get();
+                assertNotNull(dbSchema);
+                LOG.info("{} schema in {} with tables: {}",
+                        schema, ovsdbClient.getConnectionInfo(), dbSchema.getTables());
+                schemaSupported = true;
+                return true;
+            }
+        } catch (Exception e) {
+            fail("Exception: " + e);
+        }
+
+        LOG.info("Schema ({}) is not supported", schema);
+        return false;
+    }
+
+    public boolean isSchemaSupported (String schema) throws ExecutionException,
+            InterruptedException {
+        return isSchemaSupported(ovsdbClient, schema);
+    }
+
+    public boolean isSchemaSupported (OvsdbClient client, String schema) throws ExecutionException, InterruptedException {
+        ListenableFuture<List<String>> databases = client.getDatabases();
+        List<String> dbNames = databases.get();
+        assertNotNull(dbNames);
+        return dbNames.contains(schema);
+    }
+
+    /**
+     * As per RFC 7047, section 4.1.5, if a Monitor request is sent without any columns, the update response will not include
+     * the _uuid column.
+     * ----------------------------------------------------------------------------------------------------------------------------------
+     * Each <monitor-request> specifies one or more columns and the manner in which the columns (or the entire table) are to be monitored.
+     * The "columns" member specifies the columns whose values are monitored. It MUST NOT contain duplicates.
+     * If "columns" is omitted, all columns in the table, except for "_uuid", are monitored.
+     * ----------------------------------------------------------------------------------------------------------------------------------
+     * In order to overcome this limitation, this method
+     *
+     * @return MonitorRequest that includes all the Bridge Columns including _uuid
+     */
+    public <T extends TypedBaseTable<GenericTableSchema>> MonitorRequest getAllColumnsMonitorRequest (Class <T> klazz) {
+        TypedBaseTable<GenericTableSchema> table = getClient().createTypedRowWrapper(klazz);
+        GenericTableSchema tableSchema = table.getSchema();
+        Set<String> columns = tableSchema.getColumns();
+        MonitorRequestBuilder<GenericTableSchema> bridgeBuilder = MonitorRequestBuilder.builder(table.getSchema());
+        for (String column : columns) {
+            bridgeBuilder.addColumn(column);
+        }
+        return bridgeBuilder.with(new MonitorSelect(true, true, true, true)).build();
+    }
+
+    public <T extends TableSchema<T>> MonitorRequest getAllColumnsMonitorRequest (T tableSchema) {
+        Set<String> columns = tableSchema.getColumns();
+        MonitorRequestBuilder<T> monitorBuilder = MonitorRequestBuilder.builder(tableSchema);
+        for (String column : columns) {
+            monitorBuilder.addColumn(column);
+        }
+        return monitorBuilder.with(new MonitorSelect(true, true, true, true)).build();
+    }
+
+    public boolean monitorTables () throws ExecutionException, InterruptedException, IOException {
+        if (monitorReady) {
+            LOG.info("Monitoring is already initialized.");
+            return monitorReady;
+        }
+
+        assertNotNull(getDbSchema());
+
+        List<MonitorRequest> monitorRequests = Lists.newArrayList();
+        Set<String> tables = getDbSchema().getTables();
+        assertNotNull("ovsdb tables should not be null", tables);
+
+        for (String tableName : tables) {
+            GenericTableSchema tableSchema = getDbSchema().table(tableName, GenericTableSchema.class);
+            monitorRequests.add(this.getAllColumnsMonitorRequest(tableSchema));
+        }
+        TableUpdates updates = getClient().monitor(getDbSchema(), monitorRequests, new UpdateMonitor());
+        assertNotNull(updates);
+        this.updateTableCache(updates);
+
+        monitorReady = true;
+        LOG.info("Monitoring is initialized.");
+        return monitorReady;
+    }
+
+    @SuppressWarnings("unchecked")
+    protected void updateTableCache(TableUpdates updates) {
+        for (String tableName : updates.getUpdates().keySet()) {
+            Map<UUID, Row> tUpdate = getTableCache().get(tableName);
+            TableUpdate update = updates.getUpdates().get(tableName);
+            for (UUID uuid : (Set<UUID>)update.getRows().keySet()) {
+                if (update.getNew(uuid) != null) {
+                    if (tUpdate == null) {
+                        tUpdate = new HashMap<>();
+                        getTableCache().put(tableName, tUpdate);
+                    }
+                    tUpdate.put(uuid, update.getNew(uuid));
+                } else {
+                    tUpdate.remove(uuid);
+                }
+            }
+        }
+    }
+
+    public List<OperationResult> executeTransaction (TransactionBuilder transactionBuilder, String text)
+            throws ExecutionException, InterruptedException {
+        ListenableFuture<List<OperationResult>> results = transactionBuilder.execute();
+        List<OperationResult> operationResults = results.get();
+        LOG.info("{}: {}", text, operationResults);
+        org.junit.Assert.assertFalse(ASSERT_TRANS_RESULT_EMPTY, operationResults.isEmpty());
+        assertEquals(ASSERT_TRANS_OPERATION_COUNT, transactionBuilder.getOperations().size(), operationResults.size());
+        for (OperationResult result : operationResults) {
+            assertNull(ASSERT_TRANS_ERROR, result.getError());
+        }
+        //Thread.sleep(500); // Wait for a few seconds to ensure the cache updates
+        return operationResults;
+    }
+
+    public void setup() throws Exception {
+        if (getSetup()) {
+            LOG.info("Skipping setUp, already initialized");
+            return;
+        }
+
+        try {
+            super.setup();
+        } catch (Exception e) {
+            LOG.warn("Failed to setup test", e);
+            fail("Failed to setup test: " + e);
+        }
+
+        assertNotNull("ProviderContext was not found", getProviderContext());
+        if (schema.equals(LibraryIntegrationTestUtils.OPEN_VSWITCH)) {
+            assertTrue(schema + " is required.", checkSchema(schema));
+        } else {
+            assumeTrue(schema + " is required.", checkSchema(schema));
+        }
+        schemaVersion = getClient().getDatabaseSchema(schema).getVersion();
+        LOG.info("{} schema version = {}", schema, schemaVersion);
+        assertTrue("Failed to monitor tables", monitorTables());
+        setSetup(true);
+    }
+
+    public void setup2() throws Exception {
+        if (getSetup()) {
+            LOG.info("Skipping setUp, already initialized");
+            return;
+        }
+
+        try {
+            super.setup();
+        } catch (Exception e) {
+            LOG.warn("Failed to setup test", e);
+            fail("Failed to setup test: " + e);
+        }
+
+        assertNotNull("ProviderContext was not found", getProviderContext());
+        setSetup(true);
+    }
+
+    private class UpdateMonitor implements MonitorCallBack {
+        @Override
+        public void update(TableUpdates result, DatabaseSchema dbSchema) {
+            updateTableCache(result);
+        }
+
+        @Override
+        public void exception(Throwable t) {
+            LOG.error("Exception t = " + t);
+        }
+    }
 }
index e326f9c1cde43a5807f03b82fdc401733e19b097..e1b9e799c32064e6ef5c84d273222e1a21d14a12 100644 (file)
@@ -25,16 +25,18 @@ import org.opendaylight.ovsdb.lib.OvsdbClient;
 import org.opendaylight.ovsdb.lib.OvsdbConnection;
 import org.opendaylight.ovsdb.lib.OvsdbConnectionListener;
 import org.opendaylight.ovsdb.utils.servicehelper.ServiceHelper;
-import org.osgi.framework.Bundle;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 
 /**
  * Utilities for OVSDB integration tests.
  */
 public final class LibraryIntegrationTestUtils {
+    private static final Logger LOG = LoggerFactory.getLogger(LibraryIntegrationTestUtils.class);
     public static final String SERVER_IPADDRESS = "ovsdbserver.ipaddress";
     public static final String SERVER_PORT = "ovsdbserver.port";
     public static final String CONNECTION_TYPE = "ovsdbserver.connection";
-    public final static String OPEN_VSWITCH_SCHEMA = "Open_vSwitch";
+    public final static String OPEN_VSWITCH = "Open_vSwitch";
     public final static String HARDWARE_VTEP = "hardware_vtep";
     private static final String CONNECTION_TYPE_ACTIVE = "active";
     private static final String CONNECTION_TYPE_PASSIVE = "passive";
@@ -47,7 +49,8 @@ public final class LibraryIntegrationTestUtils {
         // Nothing to do
     }
 
-    public static OvsdbClient getTestConnection(BindingAwareProvider provider) throws IOException, InterruptedException, ExecutionException, TimeoutException {
+    public static OvsdbClient getTestConnection(BindingAwareProvider provider) throws IOException,
+            InterruptedException, ExecutionException, TimeoutException {
         Properties props = System.getProperties();
         String addressStr = props.getProperty(SERVER_IPADDRESS);
         String portStr = props.getProperty(SERVER_PORT, DEFAULT_SERVER_PORT);
@@ -63,8 +66,7 @@ public final class LibraryIntegrationTestUtils {
             try {
                 address = InetAddress.getByName(addressStr);
             } catch (Exception e) {
-                System.out.println("Unable to resolve " + addressStr);
-                e.printStackTrace();
+                LOG.warn("Unable to resolve {}", addressStr, e);
                 return null;
             }
 
@@ -72,40 +74,27 @@ public final class LibraryIntegrationTestUtils {
             try {
                 port = Integer.parseInt(portStr);
             } catch (NumberFormatException e) {
-                System.out.println("Invalid port number : " + portStr);
-                e.printStackTrace();
+                LOG.warn("Invalid port number: {}", portStr, e);
                 return null;
             }
 
-            OvsdbConnection connection = (OvsdbConnection) ServiceHelper.getGlobalInstance(OvsdbConnection.class, provider);
+            OvsdbConnection connection =
+                    (OvsdbConnection) ServiceHelper.getGlobalInstance(OvsdbConnection.class, provider);
             return connection.connect(address, port);
         } else if (connectionType.equalsIgnoreCase(CONNECTION_TYPE_PASSIVE)) {
             ExecutorService executor = Executors.newFixedThreadPool(1);
             Future<OvsdbClient> passiveConnection = executor.submit(new PassiveListener());
             return passiveConnection.get(60, TimeUnit.SECONDS);
         }
-        throw new IllegalArgumentException("Connection parameter (" + CONNECTION_TYPE + ") must be either active or passive");
-    }
-
-    public static String bundleStateToString(int state) {
-        switch (state) {
-            case Bundle.ACTIVE:
-                return "ACTIVE";
-            case Bundle.INSTALLED:
-                return "INSTALLED";
-            case Bundle.RESOLVED:
-                return "RESOLVED";
-            case Bundle.UNINSTALLED:
-                return "UNINSTALLED";
-            default:
-                return "Not CONVERTED";
-        }
+        throw new IllegalArgumentException("Connection parameter (" + CONNECTION_TYPE
+                + ") must be either active or passive");
     }
 
     private static String usage() {
-        return "Integration Test needs a valid connection configuration as follows :\n" +
-                "active connection : mvn -Pintegrationtest -Dovsdbserver.ipaddress=x.x.x.x -Dovsdbserver.port=yyyy verify\n"+
-                "passive connection : mvn -Pintegrationtest -Dovsdbserver.connection=passive verify\n";
+        return "Integration Test needs a valid connection configuration as follows :\n"
+                + "active connection : mvn -Pintegrationtest -Dovsdbserver.ipaddress=x.x.x.x "
+                + " -Dovsdbserver.port=yyyy verify\n"
+                + "passive connection : mvn -Pintegrationtest -Dovsdbserver.connection=passive verify\n";
     }
 
     private static class PassiveListener implements Callable<OvsdbClient>, OvsdbConnectionListener {
@@ -133,5 +122,4 @@ public final class LibraryIntegrationTestUtils {
             this.client = null;
         }
     }
-
 }