Fix findbugs violations in md-sal - part 2
[controller.git] / opendaylight / md-sal / samples / clustering-test-app / provider / src / main / java / org / opendaylight / controller / clustering / it / provider / CarProvider.java
index 63041aba0ed86282c1fb75251f0dad4f417472fa..857a61b18cb896e23e00dde7fca6798322f1ce3c 100644 (file)
@@ -12,6 +12,7 @@ import com.google.common.collect.Sets;
 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 java.util.Collection;
 import java.util.concurrent.Future;
 import java.util.concurrent.TimeUnit;
@@ -20,7 +21,6 @@ import java.util.concurrent.atomic.AtomicBoolean;
 import java.util.concurrent.atomic.AtomicLong;
 import java.util.concurrent.atomic.AtomicReference;
 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.controller.md.sal.binding.api.DataChangeListener;
 import org.opendaylight.controller.md.sal.binding.api.DataTreeIdentifier;
 import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
 import org.opendaylight.controller.md.sal.common.api.clustering.CandidateAlreadyRegisteredException;
@@ -28,7 +28,6 @@ import org.opendaylight.controller.md.sal.common.api.clustering.Entity;
 import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipChange;
 import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipListener;
 import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipService;
-import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker;
 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
 import org.opendaylight.controller.md.sal.dom.api.DOMDataBroker;
@@ -55,15 +54,17 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
 /**
+ * Implementation of CarService.
+ *
  * @author Thomas Pantelis
  */
 public class CarProvider implements CarService {
-    private static final Logger log = LoggerFactory.getLogger(PurchaseCarProvider.class);
+    private static final Logger LOG_PURCHASE_CAR = LoggerFactory.getLogger(PurchaseCarProvider.class);
 
-    private static final Logger LOG = LoggerFactory.getLogger(CarProvider.class);
+    private static final Logger LOG_CAR_PROVIDER = LoggerFactory.getLogger(CarProvider.class);
 
     private static final String ENTITY_TYPE = "cars";
-    private static final InstanceIdentifier CARS_IID = InstanceIdentifier.builder(Cars.class).build();
+    private static final InstanceIdentifier<Cars> CARS_IID = InstanceIdentifier.builder(Cars.class).build();
     private static final DataTreeIdentifier<Cars> CARS_DTID = new DataTreeIdentifier<>(
             LogicalDatastoreType.CONFIGURATION, CARS_IID);
 
@@ -76,7 +77,7 @@ public class CarProvider implements CarService {
     private final CarEntityOwnershipListener ownershipListener = new CarEntityOwnershipListener();
     private final AtomicBoolean registeredListener = new AtomicBoolean();
 
-    private final Collection<ListenerRegistration<DataChangeListener>> carsDclRegistrations =
+    private final Collection<ListenerRegistration<?>> carsDclRegistrations =
             Sets.newConcurrentHashSet();
     private final Collection<ListenerRegistration<CarDataTreeChangeListener>> carsDtclRegistrations =
             Sets.newConcurrentHashSet();
@@ -86,8 +87,8 @@ public class CarProvider implements CarService {
     private final AtomicReference<DOMDataTreeCommitCohortRegistration<CarEntryDataTreeCommitCohort>> commitCohortReg =
             new AtomicReference<>();
 
-    public CarProvider(DataBroker dataProvider, EntityOwnershipService ownershipService,
-            DOMDataBroker domDataBroker) {
+    public CarProvider(final DataBroker dataProvider, final EntityOwnershipService ownershipService,
+            final DOMDataBroker domDataBroker) {
         this.dataProvider = dataProvider;
         this.ownershipService = ownershipService;
         this.domDataBroker = domDataBroker;
@@ -95,42 +96,43 @@ public class CarProvider implements CarService {
 
     public void close() {
         stopThread();
-        unregisterCommitCohort();
+        closeCommitCohortRegistration();
     }
 
     private void stopThread() {
-        if(testThread != null) {
+        if (testThread != null) {
             stopThread = true;
             testThread.interrupt();
             try {
                 testThread.join();
-            } catch (InterruptedException e) {}
+            } catch (InterruptedException e) {
+                // don't care
+            }
             testThread = null;
         }
     }
 
     @Override
-    public Future<RpcResult<Void>> stressTest(StressTestInput input) {
+    public Future<RpcResult<Void>> stressTest(final StressTestInput input) {
         final int inputRate;
         final long inputCount;
 
         // If rate is not provided, or given as zero, then just return.
         if (input.getRate() == null || input.getRate() == 0) {
-            log.info("Exiting stress test as no rate is given.");
+            LOG_PURCHASE_CAR.info("Exiting stress test as no rate is given.");
             return Futures.immediateFuture(RpcResultBuilder.<Void>failed()
                     .withError(ErrorType.PROTOCOL, "invalid rate")
                     .build());
-        } else {
-            inputRate = input.getRate();
         }
 
+        inputRate = input.getRate();
         if (input.getCount() != null) {
             inputCount = input.getCount();
         } else {
             inputCount = 0;
         }
 
-        log.info("Stress test starting : rate: {} count: {}", inputRate, inputCount);
+        LOG_PURCHASE_CAR.info("Stress test starting : rate: {} count: {}", inputRate, inputCount);
 
         stopThread();
         // clear counters
@@ -143,7 +145,7 @@ public class CarProvider implements CarService {
         try {
             tx.submit().checkedGet(5, TimeUnit.SECONDS);
         } catch (TransactionCommitFailedException | TimeoutException e) {
-            log.error("Put Cars failed",e);
+            LOG_PURCHASE_CAR.error("Put Cars failed",e);
             return Futures.immediateFuture(RpcResultBuilder.<Void>success().build());
         }
 
@@ -153,10 +155,10 @@ public class CarProvider implements CarService {
         testThread = new Thread(() -> {
             sw.start();
             AtomicLong count = new AtomicLong();
-            while(!stopThread) {
+            while (!stopThread) {
                 long id = count.incrementAndGet();
                 WriteTransaction tx1 = dataProvider.newWriteOnlyTransaction();
-                CarEntry car = new CarEntryBuilder().setId(new CarId("car"+id)).build();
+                CarEntry car = new CarEntryBuilder().setId(new CarId("car" + id)).build();
                 tx1.put(LogicalDatastoreType.CONFIGURATION,
                         InstanceIdentifier.<Cars>builder(Cars.class).child(CarEntry.class, car.getKey()).build(),
                         car);
@@ -170,20 +172,20 @@ public class CarProvider implements CarService {
                     }
 
                     @Override
-                    public void onFailure(final Throwable t) {
+                    public void onFailure(final Throwable ex) {
                         // Transaction failed
                         failureCounter.getAndIncrement();
-                        LOG.error("Put Cars failed", t);
+                        LOG_CAR_PROVIDER.error("Put Cars failed", ex);
                     }
-                });
+                }, MoreExecutors.directExecutor());
                 try {
                     TimeUnit.NANOSECONDS.sleep(sleep);
                 } catch (InterruptedException e) {
                     break;
                 }
 
-                if(count.get() % 1000 == 0) {
-                    log.info("Cars created {}, time: {}",count.get(),sw.elapsed(TimeUnit.SECONDS));
+                if (count.get() % 1000 == 0) {
+                    LOG_PURCHASE_CAR.info("Cars created {}, time: {}",count.get(),sw.elapsed(TimeUnit.SECONDS));
                 }
 
                 // Check if a count is specified in input and we have created that many cars.
@@ -192,7 +194,7 @@ public class CarProvider implements CarService {
                 }
             }
 
-            log.info("Stress test thread stopping after creating {} cars.", count.get());
+            LOG_PURCHASE_CAR.info("Stress test thread stopping after creating {} cars.", count.get());
         });
         testThread.start();
 
@@ -207,9 +209,9 @@ public class CarProvider implements CarService {
                 .setSuccessCount(succcessCounter.longValue())
                 .setFailureCount(failureCounter.longValue());
 
-        StopStressTestOutput result = stopStressTestOutput.build();
-        log.info("Executed Stop Stress test; No. of cars created {}; " +
-                "No. of cars failed {}; ", succcessCounter, failureCounter);
+        final StopStressTestOutput result = stopStressTestOutput.build();
+        LOG_PURCHASE_CAR.info("Executed Stop Stress test; No. of cars created {}; "
+                "No. of cars failed {}; ", succcessCounter, failureCounter);
         // clear counters
         succcessCounter.set(0);
         failureCounter.set(0);
@@ -218,8 +220,8 @@ public class CarProvider implements CarService {
 
 
     @Override
-    public Future<RpcResult<Void>> registerOwnership(RegisterOwnershipInput input) {
-        if(registeredListener.compareAndSet(false, true)) {
+    public Future<RpcResult<Void>> registerOwnership(final RegisterOwnershipInput input) {
+        if (registeredListener.compareAndSet(false, true)) {
             ownershipService.registerListener(ENTITY_TYPE, ownershipListener);
         }
 
@@ -235,62 +237,30 @@ public class CarProvider implements CarService {
     }
 
     @Override
-    public Future<RpcResult<Void>> unregisterOwnership(UnregisterOwnershipInput input) {
+    public Future<RpcResult<Void>> unregisterOwnership(final UnregisterOwnershipInput input) {
         return RpcResultBuilder.<Void>success().buildFuture();
     }
 
     private static class CarEntityOwnershipListener implements EntityOwnershipListener {
         @Override
-        public void ownershipChanged(EntityOwnershipChange ownershipChange) {
-            LOG.info("ownershipChanged: {}", ownershipChange);
+        public void ownershipChanged(final EntityOwnershipChange ownershipChange) {
+            LOG_CAR_PROVIDER.info("ownershipChanged: {}", ownershipChange);
         }
     }
 
-    @Override
-    public Future<RpcResult<java.lang.Void>> registerLoggingDcl() {
-        LOG.info("Registering a new CarDataChangeListener");
-        final ListenerRegistration carsDclRegistration = dataProvider.registerDataChangeListener(
-                LogicalDatastoreType.CONFIGURATION, CARS_IID, new CarDataChangeListener(),
-                AsyncDataBroker.DataChangeScope.SUBTREE);
-
-        if (carsDclRegistration != null) {
-            carsDclRegistrations.add(carsDclRegistration);
-            return RpcResultBuilder.<Void>success().buildFuture();
-        }
-        return RpcResultBuilder.<Void>failed().buildFuture();
-    }
-
     @Override
     public Future<RpcResult<java.lang.Void>> registerLoggingDtcl() {
-        LOG.info("Registering a new CarDataTreeChangeListener");
+        LOG_CAR_PROVIDER.info("Registering a new CarDataTreeChangeListener");
         final ListenerRegistration<CarDataTreeChangeListener> carsDtclRegistration =
                 dataProvider.registerDataTreeChangeListener(CARS_DTID, new CarDataTreeChangeListener());
 
-        if (carsDtclRegistration != null) {
-            carsDtclRegistrations.add(carsDtclRegistration);
-            return RpcResultBuilder.<Void>success().buildFuture();
-        }
-        return RpcResultBuilder.<Void>failed().buildFuture();
-    }
-
-    @Override
-    public Future<RpcResult<java.lang.Void>> unregisterLoggingDcls() {
-        LOG.info("Unregistering the CarDataChangeListener(s)");
-        synchronized (carsDclRegistrations) {
-            int numListeners = 0;
-            for (ListenerRegistration<DataChangeListener> carsDclRegistration : carsDclRegistrations) {
-                carsDclRegistration.close();
-                numListeners++;
-            }
-            carsDclRegistrations.clear();
-            LOG.info("Unregistered {} CarDataChangeListener(s)", numListeners);
-        }
+        carsDtclRegistrations.add(carsDtclRegistration);
         return RpcResultBuilder.<Void>success().buildFuture();
     }
 
     @Override
     public Future<RpcResult<java.lang.Void>> unregisterLoggingDtcls() {
-        LOG.info("Unregistering the CarDataTreeChangeListener(s)");
+        LOG_CAR_PROVIDER.info("Unregistering the CarDataTreeChangeListener(s)");
         synchronized (carsDtclRegistrations) {
             int numListeners = 0;
             for (ListenerRegistration<CarDataTreeChangeListener> carsDtclRegistration : carsDtclRegistrations) {
@@ -298,7 +268,7 @@ public class CarProvider implements CarService {
                 numListeners++;
             }
             carsDtclRegistrations.clear();
-            LOG.info("Unregistered {} CaraDataTreeChangeListener(s)", numListeners);
+            LOG_CAR_PROVIDER.info("Unregistered {} CaraDataTreeChangeListener(s)", numListeners);
         }
         return RpcResultBuilder.<Void>success().buildFuture();
     }
@@ -306,18 +276,17 @@ public class CarProvider implements CarService {
     @Override
     @SuppressWarnings("checkstyle:IllegalCatch")
     public Future<RpcResult<Void>> unregisterCommitCohort() {
+        closeCommitCohortRegistration();
+
+        return RpcResultBuilder.<Void>success().buildFuture();
+    }
+
+    private void closeCommitCohortRegistration() {
         final DOMDataTreeCommitCohortRegistration<CarEntryDataTreeCommitCohort> reg = commitCohortReg.getAndSet(null);
         if (reg != null) {
-            try {
-                reg.close();
-                LOG.info("Unregistered commit cohort");
-            } catch (Exception e) {
-                return RpcResultBuilder.<Void>failed().withError(ErrorType.APPLICATION,
-                        "Error closing commit cohort registration", e).buildFuture();
-            }
+            reg.close();
+            LOG_CAR_PROVIDER.info("Unregistered commit cohort");
         }
-
-        return RpcResultBuilder.<Void>success().buildFuture();
     }
 
     @Override
@@ -348,7 +317,7 @@ public class CarProvider implements CarService {
                     org.opendaylight.mdsal.common.api.LogicalDatastoreType.CONFIGURATION,
                         carEntryPath), new CarEntryDataTreeCommitCohort()));
 
-        LOG.info("Registered commit cohort");
+        LOG_CAR_PROVIDER.info("Registered commit cohort");
 
         return RpcResultBuilder.<Void>success().buildFuture();
     }