Use OSGi DS for MessageIntelligenceAgencyImpl 07/111807/5
authorRobert Varga <robert.varga@pantheon.tech>
Tue, 21 May 2024 17:13:51 +0000 (19:13 +0200)
committerRobert Varga <robert.varga@pantheon.tech>
Wed, 22 May 2024 09:26:52 +0000 (11:26 +0200)
Rather than using static field in OpenFlowPluginProviderImpl, make
MessageIntelligenceAgencyImpl a proper singleton component and inject it
where neeeded.

JIRA: OPNFLWPLUG-1130
Change-Id: I1265c558fdbd4093283b356e2b469a0ed6723e68
Signed-off-by: Robert Varga <robert.varga@pantheon.tech>
openflowplugin-impl/src/main/java/org/opendaylight/openflowplugin/impl/OpenFlowPluginProviderImpl.java
openflowplugin-impl/src/main/java/org/opendaylight/openflowplugin/impl/karaf/ClearStatsCommandProvider.java
openflowplugin-impl/src/main/java/org/opendaylight/openflowplugin/impl/karaf/ShowStatsCommandProvider.java
openflowplugin-impl/src/main/java/org/opendaylight/openflowplugin/impl/statistics/ofpspecific/MessageIntelligenceAgencyImpl.java
openflowplugin-impl/src/main/java/org/opendaylight/openflowplugin/impl/statistics/ofpspecific/MessageIntelligenceAgencyMXBean.java
openflowplugin-impl/src/main/resources/OSGI-INF/blueprint/openflowplugin-impl.xml
openflowplugin-impl/src/test/java/org/opendaylight/openflowplugin/impl/OpenFlowPluginProviderImplTest.java
openflowplugin-impl/src/test/java/org/opendaylight/openflowplugin/impl/karaf/ClearStatsCommandProviderTest.java
openflowplugin-impl/src/test/java/org/opendaylight/openflowplugin/impl/karaf/ShowStatsCommandProviderTest.java

index 7f3fdd663dd062fab7c87e74f0d64b033c681f92..bc59a99103fc24f0de4c540df1c0f42e91412272 100644 (file)
@@ -15,7 +15,6 @@ import com.google.common.util.concurrent.MoreExecutors;
 import com.google.common.util.concurrent.SettableFuture;
 import io.netty.util.HashedWheelTimer;
 import io.netty.util.Timer;
-import java.lang.management.ManagementFactory;
 import java.util.Collection;
 import java.util.List;
 import java.util.Map;
@@ -30,13 +29,6 @@ import javax.annotation.PostConstruct;
 import javax.annotation.PreDestroy;
 import javax.inject.Inject;
 import javax.inject.Singleton;
-import javax.management.InstanceAlreadyExistsException;
-import javax.management.InstanceNotFoundException;
-import javax.management.MBeanRegistrationException;
-import javax.management.MBeanServer;
-import javax.management.MalformedObjectNameException;
-import javax.management.NotCompliantMBeanException;
-import javax.management.ObjectName;
 import org.opendaylight.infrautils.diagstatus.ServiceState;
 import org.opendaylight.infrautils.ready.SystemReadyListener;
 import org.opendaylight.infrautils.ready.SystemReadyMonitor;
@@ -72,8 +64,6 @@ import org.opendaylight.openflowplugin.impl.protocol.serialization.SerializerInj
 import org.opendaylight.openflowplugin.impl.role.RoleManagerImpl;
 import org.opendaylight.openflowplugin.impl.rpc.RpcManagerImpl;
 import org.opendaylight.openflowplugin.impl.statistics.StatisticsManagerImpl;
-import org.opendaylight.openflowplugin.impl.statistics.ofpspecific.MessageIntelligenceAgencyImpl;
-import org.opendaylight.openflowplugin.impl.statistics.ofpspecific.MessageIntelligenceAgencyMXBean;
 import org.opendaylight.openflowplugin.impl.util.ThreadPoolLoggingExecutor;
 import org.opendaylight.openflowplugin.impl.util.TranslatorLibraryUtil;
 import org.opendaylight.openflowplugin.openflow.md.core.extension.ExtensionConverterManagerImpl;
@@ -98,12 +88,8 @@ public class OpenFlowPluginProviderImpl implements
     private static final long TICK_DURATION = 10;
     private static final String POOL_NAME = "ofppool";
 
-    private static final MessageIntelligenceAgency MESSAGE_INTELLIGENCE_AGENCY = new MessageIntelligenceAgencyImpl();
-    private static final String MESSAGE_INTELLIGENCE_AGENCY_MX_BEAN_NAME = String
-            .format("%s:type=%s",
-                    MessageIntelligenceAgencyMXBean.class.getPackage().getName(),
-                    MessageIntelligenceAgencyMXBean.class.getSimpleName());
-
+    // TODO: Split this out into a separate component, which requires proper timer cancellation from all users. But is
+    //       that worth the complications?
     private final HashedWheelTimer hashedWheelTimer =
             new HashedWheelTimer(TICK_DURATION, TimeUnit.MILLISECONDS, TICKS_PER_WHEEL);
     private final NotificationPublishService notificationPublishService;
@@ -124,15 +110,12 @@ public class OpenFlowPluginProviderImpl implements
     private ConnectionManager connectionManager;
     private ExecutorService executorService;
     private ContextChainHolderImpl contextChainHolder;
+    private final MessageIntelligenceAgency messageIntelligenceAgency;
     private final DiagStatusProvider diagStatusProvider;
     private final SystemReadyMonitor systemReadyMonitor;
     private final SettableFuture<Void> fullyStarted = SettableFuture.create();
     private static final String OPENFLOW_SERVICE_NAME = "OPENFLOW";
 
-    public static MessageIntelligenceAgency getMessageIntelligenceAgency() {
-        return MESSAGE_INTELLIGENCE_AGENCY;
-    }
-
     @Inject
     public OpenFlowPluginProviderImpl(final ConfigurationService configurationService,
                                final List<SwitchConnectionProvider> switchConnectionProviders,
@@ -142,6 +125,7 @@ public class OpenFlowPluginProviderImpl implements
                                final ClusterSingletonServiceProvider singletonServiceProvider,
                                final EntityOwnershipService entityOwnershipService,
                                final MastershipChangeServiceManager mastershipChangeServiceManager,
+                               final MessageIntelligenceAgency messageIntelligenceAgency,
                                final DiagStatusProvider diagStatusProvider,
                                final SystemReadyMonitor systemReadyMonitor) {
         this.switchConnectionProviders = switchConnectionProviders;
@@ -155,6 +139,7 @@ public class OpenFlowPluginProviderImpl implements
         deviceInitializerProvider = DeviceInitializerProviderFactory.createDefaultProvider();
         config = new OpenFlowProviderConfigImpl(configurationService);
         this.mastershipChangeServiceManager = mastershipChangeServiceManager;
+        this.messageIntelligenceAgency = messageIntelligenceAgency;
         this.diagStatusProvider = diagStatusProvider;
         this.systemReadyMonitor = systemReadyMonitor;
     }
@@ -227,8 +212,6 @@ public class OpenFlowPluginProviderImpl implements
     @Override
     @PostConstruct
     public void initialize() {
-        registerMXBean(MESSAGE_INTELLIGENCE_AGENCY, MESSAGE_INTELLIGENCE_AGENCY_MX_BEAN_NAME);
-
         // TODO: copied from OpenFlowPluginProvider (Helium) misusesing the old way of distributing extension converters
         // TODO: rewrite later!
         OFSessionUtil.getSessionManager().setExtensionConverterProvider(extensionConverterManager);
@@ -245,7 +228,7 @@ public class OpenFlowPluginProviderImpl implements
         deviceManager = new DeviceManagerImpl(
                 config,
                 dataBroker,
-                getMessageIntelligenceAgency(),
+                messageIntelligenceAgency,
                 notificationPublishService,
                 hashedWheelTimer,
                 convertorManager,
@@ -325,7 +308,6 @@ public class OpenFlowPluginProviderImpl implements
         gracefulShutdown(roleManager);
         gracefulShutdown(executorService);
         gracefulShutdown(hashedWheelTimer);
-        unregisterMXBean(MESSAGE_INTELLIGENCE_AGENCY_MX_BEAN_NAME);
         diagStatusProvider.reportStatus(ServiceState.UNREGISTERED);
         try {
             if (connectionManager != null) {
@@ -368,28 +350,5 @@ public class OpenFlowPluginProviderImpl implements
         }
     }
 
-    private static void registerMXBean(final Object bean, final String beanName) {
-        final MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
-
-        try {
-            mbs.registerMBean(bean, new ObjectName(beanName));
-        } catch (MalformedObjectNameException
-                | NotCompliantMBeanException
-                | MBeanRegistrationException
-                | InstanceAlreadyExistsException e) {
-            LOG.warn("Error registering MBean {}", beanName, e);
-        }
-    }
-
-    private static void unregisterMXBean(final String beanName) {
-        final MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
 
-        try {
-            mbs.unregisterMBean(new ObjectName(beanName));
-        } catch (InstanceNotFoundException
-                | MBeanRegistrationException
-                | MalformedObjectNameException e) {
-            LOG.warn("Error unregistering MBean {}", beanName, e);
-        }
-    }
 }
index 5dcc22613acbec67a55d1d9a114308fcdb8cd122..86aa56274b61583873496d49270b39223c88cac9 100644 (file)
@@ -9,18 +9,18 @@
 package org.opendaylight.openflowplugin.impl.karaf;
 
 import java.io.PrintStream;
+import org.apache.karaf.shell.api.action.lifecycle.Reference;
 import org.apache.karaf.shell.commands.Command;
 import org.apache.karaf.shell.console.OsgiCommandSupport;
 import org.opendaylight.openflowplugin.api.openflow.statistics.ofpspecific.MessageIntelligenceAgency;
-import org.opendaylight.openflowplugin.impl.OpenFlowPluginProviderImpl;
 
 @Command(scope = "ofp", name = "clearStats", description = "Clear openflow statistics.")
 public class ClearStatsCommandProvider extends OsgiCommandSupport {
+    @Reference
+    MessageIntelligenceAgency messageIntelligenceAgency;
 
     @Override
     protected Object doExecute() {
-        final MessageIntelligenceAgency messageIntelligenceAgency =
-                OpenFlowPluginProviderImpl.getMessageIntelligenceAgency();
         messageIntelligenceAgency.resetStatistics();
         PrintStream out = session.getConsole();
         out.print("Openflow plugin statistics cleaned.\n");
index 3d8307e6cb81cb6e83ea5118520575f0fc837412..4042b4cea297d849bd9928ee0b0da706d976882a 100644 (file)
@@ -10,19 +10,19 @@ package org.opendaylight.openflowplugin.impl.karaf;
 
 import java.io.PrintStream;
 import java.util.List;
+import org.apache.karaf.shell.api.action.lifecycle.Reference;
 import org.apache.karaf.shell.commands.Command;
 import org.apache.karaf.shell.console.OsgiCommandSupport;
 import org.opendaylight.openflowplugin.api.openflow.statistics.ofpspecific.MessageIntelligenceAgency;
-import org.opendaylight.openflowplugin.impl.OpenFlowPluginProviderImpl;
 
 @Command(scope = "ofp", name = "showStats", description = "Show openflow statistics.")
 public class ShowStatsCommandProvider extends OsgiCommandSupport {
+    @Reference
+    MessageIntelligenceAgency messageIntelligenceAgency;
 
     @Override
     protected Object doExecute() {
         PrintStream out = session.getConsole();
-        final MessageIntelligenceAgency messageIntelligenceAgency =
-                OpenFlowPluginProviderImpl.getMessageIntelligenceAgency();
         final List<String> statistics = messageIntelligenceAgency.provideIntelligence();
         final StringBuilder result = new StringBuilder();
         for (String line : statistics) {
index 866882251dd027a2d736b9ad7cd8fc1f18e3439b..732240f3d26b38f6fafd26bd0216b56da81974b5 100644 (file)
@@ -9,14 +9,25 @@ package org.opendaylight.openflowplugin.impl.statistics.ofpspecific;
 
 import static java.util.Objects.requireNonNull;
 
+import java.lang.management.ManagementFactory;
 import java.util.ArrayList;
 import java.util.List;
 import java.util.Map;
-import java.util.Map.Entry;
 import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.ConcurrentMap;
 import java.util.concurrent.atomic.AtomicLongFieldUpdater;
+import javax.annotation.PreDestroy;
+import javax.inject.Inject;
+import javax.inject.Singleton;
+import javax.management.InstanceAlreadyExistsException;
+import javax.management.InstanceNotFoundException;
+import javax.management.MBeanRegistrationException;
+import javax.management.MalformedObjectNameException;
+import javax.management.NotCompliantMBeanException;
+import javax.management.ObjectName;
 import org.opendaylight.openflowplugin.api.openflow.statistics.ofpspecific.MessageIntelligenceAgency;
+import org.osgi.service.component.annotations.Activate;
+import org.osgi.service.component.annotations.Component;
+import org.osgi.service.component.annotations.Deactivate;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -25,9 +36,23 @@ import org.slf4j.LoggerFactory;
  * {@link org.opendaylight.openflowplugin.api.openflow.statistics.ofpspecific.MessageIntelligenceAgency}.
  * Class counts message of {@link StatisticsGroup} type and provides info as debug log.
  */
-public class MessageIntelligenceAgencyImpl implements MessageIntelligenceAgency, MessageIntelligenceAgencyMXBean {
+@Singleton
+@Component(immediate = true, service = MessageIntelligenceAgency.class)
+public final class MessageIntelligenceAgencyImpl implements MessageIntelligenceAgency, AutoCloseable {
     private static final Logger LOG = LoggerFactory.getLogger(MessageIntelligenceAgencyImpl.class);
 
+    private static final ObjectName MXBEAN_OBJECT_NAME;
+
+    static {
+        try {
+            MXBEAN_OBJECT_NAME = new ObjectName("%s:type=%s".formatted(
+                    MessageIntelligenceAgencyMXBean.class.getPackage().getName(),
+                    MessageIntelligenceAgencyMXBean.class.getSimpleName()));
+        } catch (MalformedObjectNameException e) {
+            throw new ExceptionInInitializerError(e);
+        }
+    }
+
     private static final class MessageCounters {
         private static final AtomicLongFieldUpdater<MessageCounters> UPDATER =
                 AtomicLongFieldUpdater.newUpdater(MessageCounters.class, "current");
@@ -50,8 +75,38 @@ public class MessageIntelligenceAgencyImpl implements MessageIntelligenceAgency,
         }
     }
 
-    private ConcurrentMap<StatisticsGroup, ConcurrentMap<Class<?>, MessageCounters>> inputStats =
-            new ConcurrentHashMap<>();
+    private final Map<StatisticsGroup, Map<Class<?>, MessageCounters>> inputStats = new ConcurrentHashMap<>();
+
+    private boolean runUnreg;
+
+    @Inject
+    @Activate
+    public MessageIntelligenceAgencyImpl() {
+        try {
+            ManagementFactory.getPlatformMBeanServer()
+                .registerMBean((MessageIntelligenceAgencyMXBean) this::provideIntelligence, MXBEAN_OBJECT_NAME);
+            runUnreg = true;
+            LOG.info("Registered MBean {}", MXBEAN_OBJECT_NAME);
+        } catch (NotCompliantMBeanException | MBeanRegistrationException | InstanceAlreadyExistsException e) {
+            LOG.warn("Error registering MBean {}", MXBEAN_OBJECT_NAME, e);
+            runUnreg = false;
+        }
+    }
+
+    @PreDestroy
+    @Deactivate
+    @Override
+    public void close() {
+        if (runUnreg) {
+            runUnreg = false;
+            try {
+                ManagementFactory.getPlatformMBeanServer().unregisterMBean(MXBEAN_OBJECT_NAME);
+                LOG.info("Unregistered MBean {}", MXBEAN_OBJECT_NAME);
+            } catch (InstanceNotFoundException | MBeanRegistrationException e) {
+                LOG.warn("Error unregistering MBean {}", MXBEAN_OBJECT_NAME, e);
+            }
+        }
+    }
 
     @Override
     public void spyMessage(final Class<?> message, final StatisticsGroup statGroup) {
@@ -66,41 +121,16 @@ public class MessageIntelligenceAgencyImpl implements MessageIntelligenceAgency,
      * @return corresponding counter
      */
     private MessageCounters getCounters(final Class<?> message, final StatisticsGroup statGroup) {
-        ConcurrentMap<Class<?>, MessageCounters> groupData = getOrCreateGroupData(statGroup);
-        MessageCounters counters = getOrCreateCountersPair(message, groupData);
-        return counters;
-    }
-
-    private static MessageCounters getOrCreateCountersPair(final Class<?> msgType,
-                                                           final ConcurrentMap<Class<?>, MessageCounters> groupData) {
-        final MessageCounters lookup = groupData.get(msgType);
-        if (lookup != null) {
-            return lookup;
-        }
-
-        final MessageCounters newCounters = new MessageCounters();
-        final MessageCounters check = groupData.putIfAbsent(msgType, newCounters);
-        return check == null ? newCounters : check;
-
-    }
-
-    private ConcurrentMap<Class<?>, MessageCounters> getOrCreateGroupData(final StatisticsGroup statGroup) {
-        final ConcurrentMap<Class<?>, MessageCounters> lookup = inputStats.get(statGroup);
-        if (lookup != null) {
-            return lookup;
-        }
-
-        final ConcurrentMap<Class<?>, MessageCounters> newmap = new ConcurrentHashMap<>();
-        final ConcurrentMap<Class<?>, MessageCounters> check = inputStats.putIfAbsent(statGroup, newmap);
-
-        return check == null ? newmap : check;
+        return inputStats
+            .computeIfAbsent(statGroup, key -> new ConcurrentHashMap<>())
+            .computeIfAbsent(message, key -> new MessageCounters());
     }
 
     @Override
     public void run() {
         // log current counters and cleans it
         if (LOG.isDebugEnabled()) {
-            for (String counterItem : provideIntelligence()) {
+            for (var counterItem : provideIntelligence()) {
                 LOG.debug("Counter: {}", counterItem);
             }
         }
@@ -108,12 +138,12 @@ public class MessageIntelligenceAgencyImpl implements MessageIntelligenceAgency,
 
     @Override
     public List<String> provideIntelligence() {
-        List<String> dump = new ArrayList<>();
+        final var dump = new ArrayList<String>();
 
-        for (StatisticsGroup statGroup : StatisticsGroup.values()) {
-            Map<Class<?>, MessageCounters> groupData = inputStats.get(statGroup);
+        for (var statGroup : StatisticsGroup.values()) {
+            final var groupData = inputStats.get(statGroup);
             if (groupData != null) {
-                for (Entry<Class<?>, MessageCounters> statEntry : groupData.entrySet()) {
+                for (var statEntry : groupData.entrySet()) {
                     long amountPerInterval = statEntry.getValue().accumulate();
                     long cumulativeAmount = statEntry.getValue().getCumulative();
                     dump.add(String.format("%s: MSG[%s] -> +%d | %d",
@@ -130,6 +160,6 @@ public class MessageIntelligenceAgencyImpl implements MessageIntelligenceAgency,
 
     @Override
     public void resetStatistics() {
-        inputStats = new ConcurrentHashMap<>();
+        inputStats.clear();
     }
 }
index bf8602739b5e191badce3f7407941b79ef5890c7..6ffd0da383031fbf6df44ad4594e1ddf3741abd7 100644 (file)
@@ -5,14 +5,15 @@
  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
  * and is available at http://www.eclipse.org/legal/epl-v10.html
  */
-
 package org.opendaylight.openflowplugin.impl.statistics.ofpspecific;
 
 import java.util.List;
+import javax.management.MXBean;
 
 /**
  * Created by Martin Bobak &lt;mbobak@cisco.com&gt; on 11.5.2015.
  */
+@MXBean
 public interface MessageIntelligenceAgencyMXBean {
 
     List<String> provideIntelligence();
index ca06337d6e0bcdcc047fdf46cbd5186dda356f60..c4bf38f24d32fbcafa5097f2b8f8e71bdc163159 100644 (file)
@@ -21,6 +21,7 @@
     <argument ref="clusterSingletonServiceProvider"/>
     <argument ref="entityOwnershipService"/>
     <argument ref="mastershipChangeServiceManager"/>
+    <argument ref="messageIntelligenceAgency"/>
     <argument ref="diagStatusProvider"/>
     <argument ref="systemReadyMonitor"/>
   </bean>
@@ -74,4 +75,6 @@
              interface="org.opendaylight.infrautils.ready.SystemReadyMonitor"/>
   <reference id="mastershipChangeServiceManager"
              interface="org.opendaylight.openflowplugin.api.openflow.mastership.MastershipChangeServiceManager"/>
+  <reference id="messageIntelligenceAgency"
+             interface="org.opendaylight.openflowplugin.api.openflow.statistics.ofpspecific.MessageIntelligenceAgency"/>
 </blueprint>
index 3be51d33cfd1095c61e874bde9fac922e3474f9e..cba8d9b03f8fac963987b93a728a7dfac3a4f2dd 100644 (file)
@@ -31,48 +31,39 @@ import org.opendaylight.openflowjava.protocol.spi.connection.SwitchConnectionPro
 import org.opendaylight.openflowplugin.api.openflow.configuration.ConfigurationProperty;
 import org.opendaylight.openflowplugin.api.openflow.configuration.ConfigurationService;
 import org.opendaylight.openflowplugin.api.openflow.mastership.MastershipChangeServiceManager;
+import org.opendaylight.openflowplugin.api.openflow.statistics.ofpspecific.MessageIntelligenceAgency;
 import org.opendaylight.yangtools.concepts.Registration;
 import org.opendaylight.yangtools.yang.common.Uint16;
 import org.opendaylight.yangtools.yang.common.Uint32;
 
 @RunWith(MockitoJUnitRunner.class)
 public class OpenFlowPluginProviderImplTest {
-
     @Mock
     PingPongDataBroker dataBroker;
-
     @Mock
     RpcProviderService rpcProviderRegistry;
-
     @Mock
     NotificationPublishService notificationPublishService;
-
     @Mock
     DiagStatusProvider ofPluginDiagstatusProvider;
-
     @Mock
     SystemReadyMonitor systemReadyMonitor;
-
     @Mock
     WriteTransaction writeTransaction;
-
     @Mock
     EntityOwnershipService entityOwnershipService;
-
     @Mock
     Registration entityOwnershipListenerRegistration;
-
     @Mock
     SwitchConnectionProvider switchConnectionProvider;
-
     @Mock
     ClusterSingletonServiceProvider clusterSingletonServiceProvider;
-
     @Mock
     ConfigurationService configurationService;
-
     @Mock
     MastershipChangeServiceManager mastershipChangeServiceManager;
+    @Mock
+    MessageIntelligenceAgency messageIntelligenceAgency;
 
     private static final Uint16 THREAD_POOL_MIN_THREADS = Uint16.ONE;
     private static final Uint16 THREAD_POOL_MAX_THREADS = Uint16.valueOf(32000);
@@ -114,6 +105,7 @@ public class OpenFlowPluginProviderImplTest {
                 clusterSingletonServiceProvider,
                 entityOwnershipService,
                 mastershipChangeServiceManager,
+                messageIntelligenceAgency,
                 ofPluginDiagstatusProvider,
                 systemReadyMonitor);
 
index f6bd07f75eee0353feb73a11b3da276150fdd62e..3d24436290eef02ac47a1558b11a2d6bdb834d28 100644 (file)
@@ -5,42 +5,41 @@
  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
  * and is available at http://www.eclipse.org/legal/epl-v10.html
  */
-
 package org.opendaylight.openflowplugin.impl.karaf;
 
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
 import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
 
 import java.util.function.Function;
 import org.junit.After;
-import org.junit.Assert;
 import org.junit.Test;
-import org.mockito.Mockito;
 import org.opendaylight.openflowplugin.api.openflow.statistics.ofpspecific.MessageIntelligenceAgency;
 import org.opendaylight.openflowplugin.api.openflow.statistics.ofpspecific.MessageSpy;
-import org.opendaylight.openflowplugin.impl.OpenFlowPluginProviderImpl;
+import org.opendaylight.openflowplugin.impl.statistics.ofpspecific.MessageIntelligenceAgencyImpl;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader;
 
 /**
  * Test for {@link ClearStatsCommandProvider}.
  */
 public class ClearStatsCommandProviderTest extends AbstractKarafTest {
-
-    private ClearStatsCommandProvider clearStatsCommandProvider;
     private static final Function<String, Boolean> CHECK_NO_ACTIVITY_FUNCTION =
         input -> input.endsWith(": no activity detected");
-    private MessageIntelligenceAgency mi5;
+
+    private final MessageIntelligenceAgency mi5 = new MessageIntelligenceAgencyImpl();
+    private final ClearStatsCommandProvider clearStatsCommandProvider = new ClearStatsCommandProvider();
 
     @Override
     public void doSetUp() {
-        clearStatsCommandProvider = new ClearStatsCommandProvider();
-        mi5 = OpenFlowPluginProviderImpl.getMessageIntelligenceAgency();
-        mi5.resetStatistics();
-        Mockito.when(cmdSession.getConsole()).thenReturn(console);
+        clearStatsCommandProvider.messageIntelligenceAgency = mi5;
+        when(cmdSession.getConsole()).thenReturn(console);
     }
 
     @After
     public void tearDown() {
-        Mockito.verify(console).print(anyString());
+        verify(console).print(anyString());
         mi5.resetStatistics();
     }
 
@@ -49,10 +48,10 @@ public class ClearStatsCommandProviderTest extends AbstractKarafTest {
      */
     @Test
     public void testDoExecute_clean() throws Exception {
-        Assert.assertTrue(checkNoActivity(mi5.provideIntelligence(), CHECK_NO_ACTIVITY_FUNCTION));
+        assertTrue(checkNoActivity(mi5.provideIntelligence(), CHECK_NO_ACTIVITY_FUNCTION));
         clearStatsCommandProvider.execute(cmdSession);
 
-        Assert.assertTrue(checkNoActivity(mi5.provideIntelligence(), CHECK_NO_ACTIVITY_FUNCTION));
+        assertTrue(checkNoActivity(mi5.provideIntelligence(), CHECK_NO_ACTIVITY_FUNCTION));
     }
 
     /**
@@ -60,12 +59,11 @@ public class ClearStatsCommandProviderTest extends AbstractKarafTest {
      */
     @Test
     public void testDoExecute_dirty() throws Exception {
-        mi5 = OpenFlowPluginProviderImpl.getMessageIntelligenceAgency();
-        Assert.assertTrue(checkNoActivity(mi5.provideIntelligence(), CHECK_NO_ACTIVITY_FUNCTION));
+        assertTrue(checkNoActivity(mi5.provideIntelligence(), CHECK_NO_ACTIVITY_FUNCTION));
         mi5.spyMessage(OfHeader.class, MessageSpy.StatisticsGroup.FROM_SWITCH);
-        Assert.assertFalse(checkNoActivity(mi5.provideIntelligence(), CHECK_NO_ACTIVITY_FUNCTION));
+        assertFalse(checkNoActivity(mi5.provideIntelligence(), CHECK_NO_ACTIVITY_FUNCTION));
 
         clearStatsCommandProvider.execute(cmdSession);
-        Assert.assertTrue(checkNoActivity(mi5.provideIntelligence(), CHECK_NO_ACTIVITY_FUNCTION));
+        assertTrue(checkNoActivity(mi5.provideIntelligence(), CHECK_NO_ACTIVITY_FUNCTION));
     }
 }
index f9bb9763bff07a459c804d52548770420708ab43..c7b517c0506554a3f81228035852be09f0f72dce 100644 (file)
@@ -8,40 +8,38 @@
 
 package org.opendaylight.openflowplugin.impl.karaf;
 
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
 import static org.mockito.ArgumentMatchers.matches;
+import static org.mockito.Mockito.verify;
 
 import java.util.function.Function;
 import org.junit.After;
-import org.junit.Assert;
 import org.junit.Test;
-import org.mockito.Mockito;
 import org.opendaylight.openflowplugin.api.openflow.statistics.ofpspecific.MessageIntelligenceAgency;
 import org.opendaylight.openflowplugin.api.openflow.statistics.ofpspecific.MessageSpy;
-import org.opendaylight.openflowplugin.impl.OpenFlowPluginProviderImpl;
+import org.opendaylight.openflowplugin.impl.statistics.ofpspecific.MessageIntelligenceAgencyImpl;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader;
 
 /**
  * Test for {@link ShowStatsCommandProvider}.
  */
 public class ShowStatsCommandProviderTest extends AbstractKarafTest {
-
-    private ShowStatsCommandProvider showStatsCommandProvider;
-    private MessageIntelligenceAgency messageIntelligenceAgency;
+    private final MessageIntelligenceAgency messageIntelligenceAgency = new MessageIntelligenceAgencyImpl();
+    private final ShowStatsCommandProvider showStatsCommandProvider = new ShowStatsCommandProvider();
 
     private static final Function<String, Boolean> CHECK_NO_ACTIVITY_FUNCTION =
         input -> input.endsWith(": no activity detected");
 
     @Override
     public void doSetUp() {
-        showStatsCommandProvider = new ShowStatsCommandProvider();
-        messageIntelligenceAgency = OpenFlowPluginProviderImpl.getMessageIntelligenceAgency();
-        messageIntelligenceAgency.resetStatistics();
+        showStatsCommandProvider.messageIntelligenceAgency = messageIntelligenceAgency;
     }
 
     @After
     public void tearDown() {
         // Pattern.DOTALL is set inline via "(?s)" at the beginning
-        Mockito.verify(console).print(matches("(?s).+"));
+        verify(console).print(matches("(?s).+"));
         messageIntelligenceAgency.resetStatistics();
     }
 
@@ -50,9 +48,9 @@ public class ShowStatsCommandProviderTest extends AbstractKarafTest {
      */
     @Test
     public void testDoExecute_clean() throws Exception {
-        Assert.assertTrue(checkNoActivity(messageIntelligenceAgency.provideIntelligence(), CHECK_NO_ACTIVITY_FUNCTION));
+        assertTrue(checkNoActivity(messageIntelligenceAgency.provideIntelligence(), CHECK_NO_ACTIVITY_FUNCTION));
         showStatsCommandProvider.execute(cmdSession);
-        Assert.assertTrue(checkNoActivity(messageIntelligenceAgency.provideIntelligence(), CHECK_NO_ACTIVITY_FUNCTION));
+        assertTrue(checkNoActivity(messageIntelligenceAgency.provideIntelligence(), CHECK_NO_ACTIVITY_FUNCTION));
     }
 
     /**
@@ -60,14 +58,12 @@ public class ShowStatsCommandProviderTest extends AbstractKarafTest {
      */
     @Test
     public void testDoExecute_dirty() throws Exception {
-        Assert.assertTrue(checkNoActivity(messageIntelligenceAgency.provideIntelligence(), CHECK_NO_ACTIVITY_FUNCTION));
+        assertTrue(checkNoActivity(messageIntelligenceAgency.provideIntelligence(), CHECK_NO_ACTIVITY_FUNCTION));
 
         messageIntelligenceAgency.spyMessage(OfHeader.class, MessageSpy.StatisticsGroup.FROM_SWITCH);
-        Assert.assertFalse(checkNoActivity(messageIntelligenceAgency.provideIntelligence(),
-                CHECK_NO_ACTIVITY_FUNCTION));
+        assertFalse(checkNoActivity(messageIntelligenceAgency.provideIntelligence(), CHECK_NO_ACTIVITY_FUNCTION));
 
         showStatsCommandProvider.execute(cmdSession);
-        Assert.assertFalse(checkNoActivity(messageIntelligenceAgency.provideIntelligence(),
-                CHECK_NO_ACTIVITY_FUNCTION));
+        assertFalse(checkNoActivity(messageIntelligenceAgency.provideIntelligence(), CHECK_NO_ACTIVITY_FUNCTION));
     }
 }